Import error running unittest in Python3

Viewed 13267

I have a problem importing files in Python 3.6. My directories tree is as given below:

project/
    app/
    ├── __init__.py
    ├── a.py
    └── b.py
    test/
    ├── __init__.py
    ├── test_a.py
    └── test_b.py

It works my application (but, no works the tests) using following import statement in b.py:

from a import *

But, it does not work my application (but, works the tests) using this other in b.py:

from .a import *

So, I choose from a import *. Executing test like python3 -m unittest I always get following error:

E.
======================================================================
ERROR: tests.test_cell (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: tests.test_cell
Traceback (most recent call last):
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/loader.py", line 428, in _find_test_path
    module = self._get_module_from_name(name)
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/loader.py", line 369, in _get_module_from_name
    __import__(name)
  File "/Users/serrodcal/Repositories/project/tests/test_b.py", line 2, in <module>
    from app.b import *
  File "/Users/serrodcal/Repositories/project/app/b.py", line 1, in <module>
    from a import *
ModuleNotFoundError: No module named 'a'


----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (errors=1)

In this case, my import statement in test_b.py is as given below:

from unittest import TestCase
from app.cell import *

Is there any way to fix this problem?

2 Answers

IMHO for a user friendly and intuitive language as Python, it's import system is one of most unfriendly I've seen around.

Ugly as it might be I usually do something like (python 3.6+):

try:
    from a import class_defined_in_a_py
except (ModuleNotFoundError, ImportError):
    from .a import class_defined_in_a_py

First import works for app, second works for tests.

Related