pytest "import file mismatch" - Fix Duplicate Module / Cache Errors
pytest found two test files that resolve to the same module name, or stale bytecode caches that don’t match the source. Without package __init__.py files, identically named test files collide on import.
What this error means
Collection fails with import file mismatch, telling you a module imported from one path doesn’t match the cached one. It often appears after copying tests or running in a container over a previously-built checkout.
import file mismatch:
imported module 'test_utils' has this __file__ attribute:
/repo/a/test_utils.py
which is not the same as the test file we want to collect:
/repo/b/test_utils.py
HINT: remove __pycache__ / .pyc files and/or use a unique basenameDiagnose 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.
# 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)"Common causes
Duplicate test module names without packages
Two test_utils.py files in different directories with no __init__.py both import as the top-level module test_utils, so pytest can’t tell them apart.
Stale __pycache__/.pyc files
Cached bytecode from a previous layout or a different checkout path no longer matches the source, triggering the mismatch on import.
How to fix it
Make test directories packages
Add __init__.py so identically-named files live in distinct importable packages.
touch tests/a/__init__.py tests/b/__init__.py
# now a.test_utils and b.test_utils are distinctClear stale caches
find . -name '__pycache__' -type d -prune -exec rm -rf {} +
find . -name '*.pyc' -delete
pytestOr use importlib import mode
The importlib import mode avoids the shared-top-level-name problem entirely.
[tool.pytest.ini_options]
addopts = "--import-mode=importlib"Make a zero-test run fail the build
# fail explicitly when nothing is collected
pytest --strict-markers -q
test "${PIPESTATUS[0]}" -ne 5 || { echo "pytest collected no tests"; exit 1; }How to prevent it
- Give test directories
__init__.pyor use--import-mode=importlib. - Use unique test file basenames across directories.
- Don’t mount or cache stale
__pycache__into CI containers.