Skip to content
Latchkey

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.

pytest
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.

Terminal
pip install -r requirements-dev.txt
pytest

Disambiguate duplicate test modules

Add __init__.py files or switch to importlib import mode so same-named files do not collide.

pytest.ini
[pytest]
addopts = --import-mode=importlib

How 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=importlib to avoid name collisions.

Frequently asked questions

What causes ""ImportError while importing test module""?
The test file imports a package not installed in the CI environment, so its import fails at collection.
How do I fix "ImportError while importing test module"?
Ensure test dependencies are installed before pytest runs.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card