Alex
Alex

Reputation: 2077

How to setup project structure so unittest imports work?

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!

Upvotes: 1

Views: 59

Answers (2)

ioluwayo
ioluwayo

Reputation: 9

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

Upvotes: 0

Will Keeling
Will Keeling

Reputation: 23004

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

For Python 3, this should be:

from . import a

Upvotes: 1

Related Questions