Python unittest files in subdirectory causing import failures in parent

时间:2016-04-21 22:01:04

标签: python-2.7 python-import python-unittest

I'm adding unit and integration tests to an existing OSS library, and the imports are failing unexpectedly when I add a subdirectory of tests. I've boiled it down to the following:

.
├── driver.py
├── lib
│   ├── __init__.py
│   ├── a.py
│   └── b.py
└── test
    ├── __init__.py
    └── test_driver.py

My driver.py imports lib classes A and B:

$ cat driver.py
from lib import a, b

def do_it(): pass

if __name__ == '__main__': do_it()

and the following integration test works:

$ cat test/test_driver.py
import unittest, driver
from lib import a  # this import is required for some tests

class T(unittest.TestCase):
  def test_a(self): pass

Running:

$ python -m unittest discover  => Ran 1 test in 0.000s; OK

I'm now trying to add tests for the library files:

...
└── test
    ├── __init__.py
    ├── lib  <== Added dir and content
    │   ├── __init__.py
    │   └── test_B.py
    └── test_driver.py

test_B.py contains the following:

import unittest
from lib import b
class T2(unittest.TestCase):
    def test_b(self): pass

With that added, the test_driver.py starts failing:

ERROR: test.test_driver (unittest.loader.ModuleImportFailure)
ImportError: Failed to import test module: test.test_driver
...
ImportError: cannot import name a

Can anyone explain why adding a subdirectory of tests impact the tests in the parent? And what is a good way to work around this?


Update: I've got a solution, but still don't understand why. The solution was to move the integration tests to a separate subfolder:

├── test
│   ├── __init__.py   <= still needed for package discovery
│   ├── integration
│   │   ├── __init__.py
│   │   └── test_driver.py  <= moved from top level
│   └── lib
│       ├── __init__.py
│       └── test_B.py

and then all the tests ran correctly. Can anyone explain what's going on behind-the-scenes? Any link or doc suggestions appreciated. Thanks, jz

0 个答案:

没有答案