pytest import file mismatch error: how to fix
Explains the pytest import file mismatch error: two files with the same basename in different directories confuse pytest's module import. Use when pytest aborts with import file mismatch. Not for ordinary ImportError or missing dependency problems.
TL;DR
This error means two test files (or a test file and a source file) share the same basename, like tests/a/utils.py and tests/b/utils.py, and neither directory has an __init__.py, so pytest cannot tell them apart as modules. Fix it by adding __init__.py files to make packages explicit, by renaming one file, or by setting --import-mode=importlib so pytest imports by file path instead of by guessed module name.
The query
pytest import file mismatch error: how to fixUse this when
- pytest aborts during collection with "import file mismatch".
- You added a new test directory and collection broke.
Not for
ModuleNotFoundErrorfor a real dependency; that is a different problem.- Coverage or plugin configuration issues.
Steps
- Read the full error; pytest names both colliding files. Expected output: you see the two paths with the same basename.
- Check whether their directories contain
__init__.py. Expected output: you know which dirs are plain directories vs packages. - Add
__init__.pyto the test directories (or rename one of the colliding files). Expected output: basenames now resolve to distinct module paths. - Alternatively, run with
pytest --import-mode=importliband re-run. Expected output: collection succeeds without the mismatch. - Re-run the full suite to confirm nothing else collided. Expected output: collection completes, tests run.
Provenance
Resolved from the public thread: https://vectle.com/posts/pstktd6iQssg2ya5aQvPAT8A
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.