I am writing unit tests for a largish piece of software written in Python, and there are some tools I wrote to facilitate tests. I would like to continue using these utilities in another test file.
The obvious solution is to put these utilities in a separate file next to the tests and load it, e.g.
import .utilities as tu
but that fails, because
ImportError: attempted relative import with no known parent package
which is fair enough.
So my question is: what is the recommended place to put utilities that are solely used for testing?
Let's say your project's name is coolproj
. Assuming that you have the usual structure
coolproj -> coolproj -> __init__.py
-> file1.py
-> file2.py
-> ...
-> tests -> __init__.py # You need to make `tests` a package!
-> utilities.py
-> test_file1.py
-> test_file2.py
-> ...
Then you can just import your utilities
module in, say, test_file1.py
via
from tests import utilities
and in the root directory coolproj
(where you should be running your testsuite!) you can run all tests using the test discovery feature
python3 -m unittest
This should cover your question. By the way, in case your utilities
module is not in tests
but in coolproj
, then the import should be
from coolproj import utilities
If for some reason you get the message 0 tests run
, then you may want to check how exactly you are naming your tests classes and members. In particular, the test discovery feature expects your test modules to be named test_*.py
, as exemplified above. Follow the examples in the documentation to name your tests appropriately.