Skip to content
Latchkey

pytest "ModuleNotFoundError" During Collection - Fix Imports

pytest failed to import a test module while collecting it. Either your package isn’t installed/importable, or pytest’s rootdir and sys.path insertion don’t put your code where the imports expect.

What this error means

Collection aborts with "ERROR collecting ..." and an ImportError/ModuleNotFoundError for your own package or a dependency. The tests never run because pytest can’t import them.

pytest output
==================================== ERRORS ====================================
____________________ ERROR collecting tests/test_api.py ____________________
ImportError while importing test module '/repo/tests/test_api.py'.
...
ModuleNotFoundError: No module named 'app'

Common causes

Project not installed

For from app import ... to work, the project must be importable. Without pip install -e ., pytest can’t find your package from an arbitrary working directory.

rootdir / import mode mismatch

pytest’s default import mode and rootdir detection can fail to add your source root to sys.path, especially with a src-layout or missing __init__.py files.

A missing third-party dependency

A test imports a package that wasn’t installed in the CI environment, so collection of that module fails.

How to fix it

Install your project (editable)

Terminal
pip install -e .
pytest

Use importlib import mode for src-layout

The importlib mode avoids sys.path surprises with modern layouts.

pyproject.toml
[tool.pytest.ini_options]
pythonpath = ["src"]
addopts = "--import-mode=importlib"

Confirm dependencies are installed

  1. Make sure test/dev dependencies are installed in CI (pip install -r requirements-dev.txt or .[test]).
  2. Run pytest --collect-only to see which module fails to import.
  3. Reproduce the failing import with python -c "import <module>".

How to prevent it

  • Install the project with pip install -e . (or .[test]) in CI.
  • Set pythonpath/testpaths and an explicit import mode in config.
  • Keep dev/test dependencies in a declared extra and install them in CI.

Related guides

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