Reputation: 12207
I'm starting to use pytest, and I think I have something set up wrong.
I have directory called "cyan" with all of my code. It has some top-level stuff and a lib directory with all of the code that does work, as is normal.
I have a tests directory where I'm trying to put pytest tests.
I currently have one test: test_A:
import pytest
from cyan.lib import dataCrunch
import os,sys
def test_foo():
print os.getcwd()
print sys.path
assert 1==0
You'll notice the "from cyan.lib import" line. It SHOULD be "from lib import", but that doesn't work.
The reason it doesn't work is clear from the results of the test:
/Users/brianp/work/cyan
['/Users/brianp/work', .........]
the .... is all standard library venv stuff, as expected.
when I print sys.path from a normal python run I get:
['', .........]
which seems right.
So, somehow when I run pytest, sitting in the cyan directory, the parent directory is getting into the pythonpath instead of the current directory.
I have __init__.py
in all appropriate directories.
ADDED:
Ok, thanks to @timchap's comment I've learned some things:
The docs that Tim posted imply that having a pytest.ini in my cyan dir should make that be the rootdir. THAT doesn't work.
What appears to be happening is that it starts at the tests dir, and looks up in the path until it finds a directory WITHOUT __init__.py
. Since my root directory has one, it kept going up until the parent directory.
Maybe that's the entire problem? that my root dir has __init__.py
? Seems like a weird assumption to make...
Upvotes: 7
Views: 15961
Reputation: 12207
To add details to @timchap's answer:
Rootdir is calculated exactly as it says in the link he posted.
However, rootdir is not what is used for determining pythonpath (sys.path).
Where normally, when you run python, it adds '' (or '.') to the pythonpath, so that things in the current directory can be imported, pytest tries to do something more complicated.
pytest looks up from (I believe) the test directory, and keeps looking up until it finds a directory WITHOUT __init__.py
. If the root directory of your project happens to have __init__.py
for any reason, then it will go one directory too high, and probably all local imports (unless they are relative) will fail.
Upvotes: 6
Reputation: 513
The pytest documentaiton provides some information on how the root directory for a pytest run is determined. This doesn't quite seem to explain your observation, but it does provide some insight into how the root dir determination should work.
After some reflection, I think that the behaviour you are observing makes sense - pytest seems to be attempting to add the parent directory of the current package to the path, so that modules using absolute imports for the current package work properly.
To avoid this ambiguity in future, you might consider using relative imports in your test modules.
Upvotes: 1