0

Here is my folder structure:

.
├── mod
│   └── a.py
└── tests
    └── test_a.py

2 directories, 2 files

tests/test_a.py simply looks like this:

import unittest
from mod import a

class ATestCase(unittest.TestCase):
    def test_a(self):
        print(a.a)

if __name__ == "__main__":
    unittest.main()

When I do unittest, surely everything is fine:

$ python -m unittest tests/test_a.py 
1
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

However, when I simply run tests/test_a.py as a python script, error happens:

$ python tests/test_a.py 
Traceback (most recent call last):
  File "tests/test_a.py", line 2, in <module>
    from mod import a
ImportError: No module named 'mod'

My question is why, using unittest, mod becomes importable?

czheo
  • 1,771
  • 2
  • 12
  • 22
  • @czheo have you seen this similar question http://stackoverflow.com/questions/1896918/running-unittest-with-typical-test-directory-structure Does this help? – user_3068807 Apr 29 '16 at 04:35
  • @shafaq Do you mean the unittest module modified "sys.path"? However, when I printed sys.path out in my test_a.py file, I didn't find it is modified. – czheo Apr 29 '16 at 04:42
  • It does the first item path[0]. Try printing `print os.path.abspath(sys.path[0])`. You will see it would give you the path to `mod` directory. While without `unittest` it would go to `test` directory. So `a` module is not traceable. – user_3068807 Apr 29 '16 at 05:22
  • https://docs.python.org/2/library/sys.html#sys.path here it is in documentation. – user_3068807 Apr 29 '16 at 05:23
  • @shafaq Got it. Thx! – czheo Apr 29 '16 at 05:38

1 Answers1

0

As mentioned and discussed this question : Running unittest with typical directory structure

The best solution in my opinion is to use the unittest command line interface which will add the directory to the sys.path so you don't have to (done in the TestLoader class).

Looking at the documentation: sys.path

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter.

Try printing print os.path.abspath(sys.path[0]) when using python -m unittest tests.test_a (in a function/method) and you will see ../mod on your path and that is why a is located.

Now run python tests/test_a.py and tests directory would be on path hence a would not be located.

Community
  • 1
  • 1
user_3068807
  • 397
  • 3
  • 13