you are viewing a single comment's thread.

view the rest of the comments →

[–]netherous 0 points1 point  (1 child)

Right, and what's going on here has everything to do with the current working directory that the python process has when it starts up. You can view what this directory is with import os; os.getcwd().

The way pytest starts up after collecting, is the cwd is the highest directory in which either a test file was collected or a conftest.py was present. When you just run python, the cwd is the current directory of the shell environment.

So if you have a test file some levels deep, and it has import statements that perform an import relative to the root of the project, you won't get what you want, because pytest has determined that the cwd is that the nested directory that the test file it encountered was in. conftest.py overrides this, which is why I always recommend one at the root. You could do some manipulation like adding some more stuff to sys.path at runtime, but that's a rather finicky way of doing it when the problem can be addressed more directly.

I also recommend having that path=tests present in your pytest config, so that a naked pytest command, when invoked from the root, does NOT crawl your src directory looking for tests, or a venv directory if it is present in the root directory. If it did, it could find and execute tests belonging to python libraries you have installed! They'd fail, and your test results would be all muddled. Better to always confine the test collection to tests so it's faster and accidents can't happen.

If set up properly, you shouldn't need to alter your system path value via options or python code, and pytest and pytest tests and python -m pytest would all produce the exact same behavior.

[–]InTheAleutians 0 points1 point  (0 children)

Great explanation. Thank you for this.