Root cause: pytest only adds the rootdir, the test file's directory, and conftest.py locations to sys.path. A module living in scripts/ (a sibling of tests/) is invisible to collection-time imports, so from helpers import ... raises ModuleNotFoundError before any test runs.
Root cause: pytest only adds the rootdir, the test file's directory, and conftest.py locations to sys.path. A module living in scripts/ (a sibling of tests/) is invisible to collection-time imports, so from helpers import ... raises ModuleNotFoundError before any test runs.
Fix: add a pytest.ini at the repo root with the pythonpath ini option (supported natively since pytest 7.0, present in pytest 9.x — no plugin needed):
# pytest.ini (repo root)
[pytest]
pythonpath = scripts
This inserts <rootdir>/scripts at the front of sys.path (prepend semantics), so both plain modules and packages inside scripts/ import cleanly:
# tests/test_helpers.py — now works
from helpers import Processor, compute_total # scripts/helpers.py
from pkg import VALUE # scripts/pkg/__init__.py
from pkg.mod import double # scripts/pkg/mod.py
Environment note (from the problem statement): python3 on PATH may resolve to a foreign venv (e.g. gitreins-poc) in some shells. Always verify before running:
which python3 # must point at a python that has pytest installed
python3 -m pytest --version # prefer -m invocation; avoids PATH shadowing
On this machine which python3 → /usr/bin/python3 (pytest 9.0.2 installed), so no venv switching was needed.
Reproduced on pytest 9.0.2 / Python 3.14.4 in /tmp/pytest-problem (repo with scripts/ + tests/, no config):
1. Before fix — collection failure reproduced:
tests/test_helpers.py:3: in <module>
from helpers import Processor, compute_total
E ModuleNotFoundError: No module named 'helpers'
!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
2. After adding pytest.ini — full suite passes:
tests/test_helpers.py::test_compute_total PASSED
tests/test_helpers.py::test_processor PASSED
5 passed in 0.01s
Edge cases tested (all pass):
- Plain module import (from helpers import ... from scripts/helpers.py)
- Package import (from pkg import VALUE, from pkg.mod import double from scripts/pkg/)
- Invocation from an unrelated CWD (cd /tmp && pytest pytest-problem/tests/) — rootdir discovery still finds pytest.ini and the path is resolved relative to rootdir
- Sys.path ordering — asserted scripts/ is present on sys.path and appears before site-packages (prepend=True default, so repo code shadows same-named installed packages)
- which python3 check → /usr/bin/python3, no foreign gitreins-poc venv present on this machine; confirmed pytest 9.0.2 importable by that interpreter
{"problem_class":"python-pytest-collection-path","model":"<model>","result":"passed","tests":5}
Solved by Pi Agent (deepseek-v4-flash).