the_mandrill
the_mandrill

Reputation: 30832

Python package structure to enable unit tests ('Parent module not loaded' error)

I'm a newcomer to Python and I'm struggling with getting the right project structure so that I can create a package and a separate tests directory next to it for unit tests.

I've tried following the canonical format described at: http://docs.python-guide.org/en/latest/writing/structure/#sample-repository . Unfortunately even using the example on github I can't get that work:

python tests\test_basic.py
Traceback (most recent call last):
 File "tests\test_basic.py", line 3, in <module>
  from .context import sample
 SystemError: Parent module '' not loaded, cannot perform relative import

python -m unittest doesn't work either:

ERROR: sample (unittest.loader._FailedTest)
ImportError: Failed to import test module: sample
Traceback (most recent call last):
  File "C:\ProgramData\chocolatey\lib\python3\tools\lib\unittest\loader.py", line 462, in _find_test_path
    package = self._get_module_from_name(name)
  File "C:\ProgramData\chocolatey\lib\python3\tools\lib\unittest\loader.py", line 369, in _get_module_from_name
    __import__(name)
  File "E:\source\python\samplemod\sample\__init__.py", line 1, in <module>
    from .core import hmm
  File "E:\source\python\samplemod\sample\core.py", line 9
    print get_hmm()
                ^
SyntaxError: invalid syntax

EDIT: The following suggests that it's running tests but isn't (as verified by making the tests fail)

> python setup.py test
running test

Any idea what's going on here? If even the recommended format doesn't work then I'm high and dry... I'm on python 3.5.1 on Windows

EDIT: I've found that if I install nose (python -m pip install nose) then I can run the unit tests with:

python -m nose

Upvotes: 2

Views: 1216

Answers (1)

cosmicFluke
cosmicFluke

Reputation: 355

There's an excellent explanation of the issue here.

Long story short, you run into trouble when you try to use relative imports in a script (as opposed to within a module). Quick solution is to use the -m argument when running your test script.

python -m tests\test_basic.py

If that doesn't work, you can try working with absolute imports. The link above will provide more detail.

Upvotes: 2

Related Questions