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.
==================================== 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)
pip install -e .
pytestUse importlib import mode for src-layout
The importlib mode avoids sys.path surprises with modern layouts.
[tool.pytest.ini_options]
pythonpath = ["src"]
addopts = "--import-mode=importlib"Confirm dependencies are installed
- Make sure test/dev dependencies are installed in CI (
pip install -r requirements-dev.txtor.[test]). - Run
pytest --collect-onlyto see which module fails to import. - 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/testpathsand an explicit import mode in config. - Keep dev/test dependencies in a declared extra and install them in CI.