1

I have a project that looks like this:

project/
  setup.py
  project/
    __init__.py
    a.py
    b.py
  test/
    __init__.py
    test_a.py
    test_b.py

and b.py contains the import statement import a.

Running python -m unittest or python setup.py test from the project root directory results in ModuleNotFoundError when test_b.py tries to run from project import b.

As far as I can tell, this is nearly the exact setup as https://stackoverflow.com/a/24266885/4190459 but it's not working. Any pointers appreciated!

Alex
  • 1,997
  • 1
  • 15
  • 32

2 Answers2

1

This is caused by the relative module import import a that exists in b.py

For Python 3, this should be:

from . import a
Will Keeling
  • 22,055
  • 4
  • 51
  • 61
  • Thanks! I thought that python looked in the same directory as default, but apparently it's more complicated than that. – Alex Apr 11 '18 at 15:34
  • Yes, `import a` works in Python 2 where relative imports are default, but you need to be explicit about them in Python 3, hence `from . import a` – Will Keeling Apr 11 '18 at 15:48
  • This seems to break running b.py from the command line, though. Doing `python b.py` results in `ImportError: cannot import name 'a'`. – Alex Apr 11 '18 at 16:07
  • That's because you're running `b.py` as a script, when it is a module in a package, and that breaks the relative import. There are some solutions to support both usages, which are explained here: https://stackoverflow.com/questions/16981921/relative-imports-in-python-3 – Will Keeling Apr 11 '18 at 16:20
  • Wow, what a mess. Thanks for the help. Running `python -m project.b` now seems to work. A bit wordy perhaps, but seems to be the "official" way of doing things. Thanks again! – Alex Apr 11 '18 at 16:28
0

Your import statement in b.py should be.

from project import a

Then in test_a.py you can do

import unittest
from project import a
from project import b


class Test(unittest.TestCase):
    def test(self):
        print(a.a_var)
        print(b.b_var)
        pass

you can then run your tests like

python -m unittest
a
b
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
ioluwayo
  • 9
  • 1