Python adding unit test inside package

Viewed 1678

I have a python package for which I am trying to write unit tests The package looks as below

helper/
utils/
app/
requirements.txt
README.md
tests/

I come from java background so I thought of organizing the tests in the same package as that of their source therefore my tests directory looks as below

tests/
  helper/
    helper_a_test.py
  utils/
    util_a_test.py
  app/
    myapp_test.py

when I trying invoking the tests as below

python -m unittest discover

The test fails due to import error from source with error module app, helper, utils not found. I have __init__.py file is all my packages. I moved all the tests inside tests sub-directory into tests root directory as below.

tests/
  helper_a_test.py
  util_a_test.py
  myapp_test.py

Now all test works as expected. Can someone explain why is this happening, also is it good practice to keep all tests inside one directory rather that on its own package?

1 Answers

You have at least two ways to go back to your original structure and make it work:

  • The first and most direct one is adding an __init__.py in your test structure (at all levels, also the tests folder, that you may have missed).

  • The second one is to transform your code into a python package (adding a setup.py, so that your app will be installable with pip), install your package in the local interpreter and then run the tests.

I would also suggest using pytest and call directly pytest instead of python -m unittest.

Related