pytest Imports Fail Without PYTHONPATH - Configure pythonpath in CI
pytest couldn’t import your first-party package because its source root isn’t on sys.path. With a src-layout (or a custom root) you must tell pytest where the code lives, or install the project, so imports resolve in CI.
What this error means
Collection fails with ModuleNotFoundError for your own package (No module named 'myapp') even though the files exist. It passes locally where you set PYTHONPATH or installed the project, but CI’s clean checkout doesn’t.
ImportError while importing test module '/repo/tests/test_api.py'.
...
ModuleNotFoundError: No module named 'myapp'
# repo uses src/ layout: myapp lives in src/myappCommon causes
Source root not on sys.path
With a src/ layout the package isn’t importable from the repo root, and pytest doesn’t add src/ to sys.path unless told. CI has no ambient PYTHONPATH to compensate.
Relying on a local PYTHONPATH export
A developer shell exports PYTHONPATH=src; the CI job doesn’t, so imports that worked locally fail in the pipeline.
How to fix it
Set pythonpath in pytest config
Declare the source root so pytest adds it to sys.path for collection.
[tool.pytest.ini_options]
pythonpath = ["src"]Or install the project editable
An editable install puts the package on sys.path regardless of layout or working directory - the most robust option.
pip install -e .
pytestHow to prevent it
- Set
pythonpathin pytest config for src-layout projects. - Install the project with
pip install -e .in CI. - Don’t depend on an ambient
PYTHONPATHthat only exists locally.