Skip to content
Latchkey

pytest ModuleNotFoundError during collection in CI

During collection pytest imports each test module (and conftest.py), and one of them imports your package, which is not on sys.path. The error is the same ModuleNotFoundError, but it fires at collection time.

What this error means

pytest aborts collection with "ModuleNotFoundError: No module named 'myapp'" referencing a conftest.py or a test module path.

pytest
ImportError while loading conftest '/home/runner/work/app/tests/conftest.py'.
tests/conftest.py:3: in <module>
    from myapp import create_app
E   ModuleNotFoundError: No module named 'myapp'

Common causes

The package is not installed in the env

Tests import your package, but it was never installed (pip install -e .) into the interpreter running pytest.

rootdir / sys.path does not include the source

With a src/ layout or unusual rootdir, the package directory is not importable during collection.

How to fix it

Install the package before running tests

An editable install makes the package importable during collection like in production.

Terminal
pip install -e .
pytest

Add the source root to the import path

For a src layout, set pythonpath in pytest config so collection can import it.

pytest.ini
[pytest]
pythonpath = src

How to prevent it

  • Install the project (editable) before invoking pytest.
  • Set pythonpath in pytest config for src layouts.
  • Keep conftest imports limited to installed packages.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →