PATH issue with pytest 'ImportError: No module named YadaYadaYada'
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3
--
Chapters
00:00 Path Issue With Pytest 'Importerror: No Module Named Yadayadayada'
00:46 Answer 1 Score 133
01:10 Answer 2 Score 159
01:23 Accepted Answer Score 484
01:42 Answer 4 Score 67
02:05 Thank you
--
Full question
https://stackoverflow.com/questions/1025...
--
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.