Python unittest import issues

This is my project:

my_project ./my_project ./__init__.py ./foo ./__init__.py ./bar.py ./tests ./__init__.py ./test_bar.py 

Inside test_bar.py I have the following import statement: from foo import bar

However, when I run python /my_project/tests/test_bar.py , I get this error:

ImportError: No module named foo .

Any ideas on how to fix this?

+5
source share
3 answers

Think about what's on your PYTHONPATH . The toplevel package for your project is my_project , so this should be the beginning of any import for something in your project.

 from my_project.foo import bar 

You can also use relative imports, although this is not so clear and breaks if you ever change the relative location of the module from which you performed this import.

 from ..foo import bar 

Ideally, the test folder is not a package and is not part of your application package. See the pytests page for good practice . This requires that you add setup.py to your package and install it in your virtual mode in development mode.

 pip install -e . 

Do not run tests by pointing directly to the file in your application. After properly structuring / installing your project, use the discovery engine for any structure you use to run tests for you. For example, using pytest just specify the test folder:

 pytest tests 

Or for the unittest built-in module:

 python -m unittest discover -s tests 
+8
source

You can use relative imports:

 from ..foo import bar 

https://docs.python.org/2/whatsnew/2.5.html#pep-328-absolute-and-relative-imports

but I also think that using absolute paths setting up your project in Vienna is the best way.

+1
source
 import sys sys.path.append('/path/to/my_project/') 

Now you can import

 from foo import bar 
0
source

Source: https://habr.com/ru/post/1213941/


All Articles