pytest "ImportError while importing test module" in CI
pytest tried to import a test module during collection and the import itself raised. The hint points at duplicate filenames, a missing __init__.py, or a dependency the test imports that is not installed.
What this error means
pytest reports "ERROR collecting tests/test_x.py - ImportError while importing test module" followed by the underlying import error and a hint about test module names.
ImportError while importing test module '/home/runner/work/app/tests/test_api.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests/test_api.py:2: in <module>
import requests
E ModuleNotFoundError: No module named 'requests'Common causes
A dependency the test imports is missing
The test file imports a package not installed in the CI environment, so its import fails at collection.
Duplicate test filenames without packages
Two test_x.py files in different folders with no __init__.py collide under the default import mode.
How to fix it
Install the missing dependency
Ensure test dependencies are installed before pytest runs.
pip install -r requirements-dev.txt
pytestDisambiguate duplicate test modules
Add __init__.py files or switch to importlib import mode so same-named files do not collide.
[pytest]
addopts = --import-mode=importlibHow to prevent it
- Install all test dependencies (a dev requirements set) in CI.
- Use unique test filenames or package the test tree with
__init__.py. - Consider
--import-mode=importlibto avoid name collisions.