# pytest "ImportError while importing test module" in CI

> Fix pytest "ImportError while importing test module" in CI - a test file failed to import, often from a duplicate module name, missing dependency, or bad sys.path.

Source: https://latchkey.dev/learn/python/pytest-importerror-while-importing-test-module-in-ci  
Updated: 2026-06-26

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.

## Diagnose it: what did pytest actually collect?

Most pytest failures that only happen in CI are collection or import-path problems rather than test failures. The runner has a different working directory, a different `sys.path`, and usually no editable install, so a test module that imports your package locally may not resolve at all.

```Terminal
# what would run, without running it
pytest --collect-only -q | tail -20

# where pytest thinks the root is (drives conftest and import mode)
pytest --collect-only 2>&1 | grep -i rootdir

# is the package importable at all from the runner cwd?
python -c "import yourpackage, sys; print(yourpackage.__file__)"
python -c "import sys; print(sys.path)"
```

> Exit code 5 means zero tests were collected. It is a configuration result, not a passing run, and CI that only checks for a non-zero exit will treat it as success unless you assert on the collected count.

## Make a zero-test run fail the build

```Terminal
# fail explicitly when nothing is collected
pytest --strict-markers -q
test "${PIPESTATUS[0]}" -ne 5 || { echo "pytest collected no tests"; exit 1; }
```

## FAQ

### What causes pytest "ImportError while importing test module" in CI?

There are 2 common causes: a dependency the test imports is missing and duplicate test filenames without packages. The test file imports a package not installed in the CI environment, so its import fails at collection.

### How do I fix pytest "ImportError while importing test module" in CI?

There are 2 fixes depending on which cause you have: install the missing dependency and disambiguate duplicate test modules. Work through them in order, since the first is the most common.

### What does pytest "ImportError while importing test module" in CI actually mean?

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.

### How do I stop pytest "ImportError while importing test module" in CI happening again?

Install all test dependencies (a dev requirements set) in CI. The prevention section lists 3 changes that keep it from recurring.

---

Latchkey runs CI/CD that repairs its own failures. Agent entry points: https://latchkey.dev/agent.txt, https://latchkey.dev/openapi.json, https://latchkey.dev/llms.txt
