I'm trying to setup a project (Python 3.4.4, pytest 3.3.1) to use pytest, but pytest is failing to run tests in a file or a directory. I think I'm using pytest wrong, but am not what the correct workflow would be.
What I've tried
Following the suggestions in "Good Integration Practices" and also due to the personal preference of having the source and the tests in separate folders, I have setup my project as follows:
parent_directory/
setup.py
src/
project_name/
__init__.py # empty
utils.py
tests/
__init__.py # empty
project_name/
__init__.py # empty
test_utils.py # has `import project_name.utils.py`
With this exact setup, "Usage and Invocations" says I should be able to run the tests
using
python -m pytest
and that pytest will add the current directory to sys.path
("except that calling via python will also add the current directory to sys.path."). If I try to do that from parent_directory/src
, no tests are collected (collected 0 items
). If I do that from parent_directory/
, I get ImportError: No module named 'project_name'
.
After some reading -- (see "Test root path"), I have found out that adding (an empty) conftest.py
to src/
"will have pytest recognizing your application modules without specifying PYTHONPATH".
After doing this, I can go to parent_directory/
and successfully run
pytest
and
pytest -k test_some_specific_test_function_name
Notice that I could switch from python -m pytest
to just pytest
, which I'm happy about.
However, if I try to run tests in a specific file (or directory), e.g.
pytest tests/project_name/test_utils.py
I, once again, get ImportError: No module named 'project_name'
. This behavior is quite surprising to me.
I have checked:
Question
What would be the correct workflow that would allow me to preserve my directory structure while, ideally from parent_directory/
, being able to call all of:
pytest
pytest -k test_some_specific_test_function_name
pytest tests/project_name/test_utils.py
without some manual sys.path
hacking.
I'm sure I'm missing something obvious. Thanks!
See Question&Answers more detail:
os