This is my project set up:
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?
Which is better – pytest or unittest? Although both the frameworks are great for performing testing in python, pytest is easier to work with. The code in pytest is simple, compact, and efficient. For unittest, we will have to import modules, create a class and define the testing functions within that class.
If you're using the PyCharm IDE, you can run unittest or pytest by following these steps: In the Project tool window, select the tests directory. On the context menu, choose the run command for unittest . For example, choose Run 'Unittests in my Tests…'.
Relative imports use dot(.) notation to specify a location. A single dot specifies that the module is in the current directory, two dots indicate that the module is in its parent directory of the current location and three dots indicate that it is in the grandparent directory and so on.
The unit test framework in Python is called unittest , which comes packaged with Python. Unit testing makes your code future proof since you anticipate the cases where your code could potentially fail or produce a bug.
Think about what is on your PYTHONPATH
. The toplevel package for your project is my_project
, so that must be the start of any import for something in your project.
from my_project.foo import bar
You could also use a relative import, although this isn't as clear, and would break if you ever changed the relative location of the module you were performing this import from.
from ..foo import bar
Ideally, the test
folder is not a package at all, and is not part of your application package. See pytests's page on good practices. This requires that you add a setup.py
to your package and install it to your virtualenv in develop mode.
pip install -e .
Don't run the tests by pointing directly at a file within your application. After structuring/installing your project correctly, use the discovery mechanism for whatever framework you're using to run the tests for you. For example, with pytest, just point at the test folder:
pytest tests
Or for the built-in unittest module:
python -m unittest discover -s tests
import sys
sys.path.append('/path/to/my_project/')
Now you can import
from foo import bar
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With