PATH issue with pytest 'ImportError: No module named YadaYadaYada'
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Secret Catacombs
--
Chapters
00:00 Question
00:56 Accepted answer (Score 130)
01:25 Answer 2 (Score 432)
01:50 Answer 3 (Score 378)
05:45 Answer 4 (Score 145)
06:02 Thank you
--
Full question
https://stackoverflow.com/questions/1025...
Answer 2 links:
[pythonpath]: https://docs.pytest.org/en/7.1.x/referen...
[Apteryx]: https://stackoverflow.com/users/2896799/...
[answer]: https://stackoverflow.com/a/34140498/265...
[their docs]: https://docs.pytest.org/
[conftest.py]: https://docs.pytest.org/en/3.6.0/writing...
[In py.test, what is the use of conftest.py files?]: https://stackoverflow.com/q/34466027/265...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #unittesting #pytest
#avk47
ACCEPTED ANSWER
Score 484
I'm not sure why py.test does not add the current directory in the PYTHONPATH itself, but here's a workaround (to be executed from the root of your repository):
python -m pytest tests/
It works because Python adds the current directory in the PYTHONPATH for you.
ANSWER 2
Score 159
I had the same problem. I fixed it by adding an empty __init__.py file to my tests directory.
ANSWER 3
Score 133
Yes, the source folder is not in Python's path if you cd to the tests directory.
You have two choices:
Add the path manually to the test files. Something like this:
import sys, os myPath = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, myPath + '/../')Run the tests with the env var
PYTHONPATH=../.
ANSWER 4
Score 67
Run pytest itself as a module with:
python -m pytest tests
This happens when the project hierarchy is, for example, package/src package/tests and in tests you import from src. Executing as a module will consider imports as absolute rather than relative to the execution location.