6

I'm trying out the one of the recommended python package layouts with the src directory.

enter image description here

My problem is when I run pytest from the command line my tests are not finding my python package. I tried running from the top level of this directory and within the tests directory but still getting ModuleNotFoundError exception. I'm running python 3.5 with pytest-3.5.0.

What is the recommend way to execute pytest from this type of python package layout?

Danny
  • 340
  • 5
  • 10

2 Answers2

11

If you're using py.test to run the tests, it won't find the application as you must have not installed it. You can use python -m pytest to run your tests, as python will auto-add your current working directory to your PATH.

Hence, using python -m pytest .. would work if you're doing it in the src directory

The structure that I normally use is:

root
├── packagename
│   ├── __init__.py
│   └── ...
└── tests
    └── ...    

This way when I simply run python -m pytest in the root directory it works fine. Read more at: https://stackoverflow.com/a/34140498/1755083

Second option, if you still want to run this with py.test you can use:

PYTHONPATH=src/ py.test

and run it from the root. This simply adds the src folder to your PYTHONPATH and now your tests will know where to find the packagename package.

The third option is to use pip with -e to install your package in the editable mode. This creates a link to the packagename folder and installs it with pip - so any modification done in packagename is immediately reflected in pip's installation (as it is a link). The issue with this is that you need to redo the installation if you move the repo and need to keep track of which one is installed if you have more than 1 clones/packages.

AbdealiJK
  • 3,037
  • 1
  • 17
  • 34
  • 3
    The whole idea of putting the package into `src/` is to _prevent_ it from being imported. You want to test the installed package, not the development folder. – Nico Schlömer Apr 30 '21 at 12:26
1

Just my two cents:

Don't use py.test, use pytest. The py.test is an old and deprecated command.

Notice Windows users; you may or may not have PYTHONPATH defined on your system. In such a case, I used the following commands to run tests:

set PYTHONPATH=src
pytest

To examine the PYTHONPATH:

echo %PYTHONPATH%
src

And the directory structure on containing src folder:

setup.py
src
    utils
        algo.py
        srel.py
        __init__.py
tests
    algo_test.py
    srel_test.py
    __init__.py

Finally, the documentation says that you might omit the __init__.py files. Removing them worked for me in this case.

Jan Bodnar
  • 9,881
  • 5
  • 60
  • 71