Update for pytest 7 and newer: use the pythonpath
setting
Recently, pytest
has added a new core plugin that supports sys.path
modifications via the pythonpath
configuration value. The solution is thus much simpler now and doesn’t require any workarounds anymore:
pyproject.toml
example:
[tool.pytest.ini_options]
pythonpath = [
"."
]
pytest.ini
example:
[pytest]
pythonpath = .
The path entries are calculated relative to the rootdir, thus .
adds junk
directory to sys.path
in this case.
Multiple path entries are also allowed: for a layout
junk/
├── src/
| └── lib.py
├── junk/
│ ├── __init__.py
│ └── ook.py
└── tests
├── test_app.py
└── test_lib.py
the configuration
[tool.pytest.ini_options]
pythonpath = [
".", "src",
]
or
[pytest]
pythonpath = . src
will add both lib
module and junk
package to sys.path
, so
import junk
import lib
will both work.
Original answer
Just put an empty conftest.py
file in the project root directory:
$ pwd
/home/usr/tmp/junk
$ touch conftest.py
Your project structure should become:
junk
├── conftest.py
├── junk
│ ├── __init__.py
│ └── ook.py
└── tests
└── test_ook.py
What happens here: when pytest
discovers a conftest.py
, it modifies sys.path
so it can import stuff from the conftest module. So, since now an empty conftest.py
is found in rootdir, pytest
will be forced to append it to sys.path
. The side effect of this is that your junk
module becomes importable.