Skip to content
Latchkey

pytest "errors during collection" exit 2 in CI

pytest imports every test module during collection. If one raises at import time (a bad import, a syntax error, a missing dependency), pytest counts a collection error and stops with exit code 2 before running tests.

What this error means

pytest ends with "!!!!!! Interrupted: N errors during collection !!!!!!" and exit code 2. The traceback points at module-level code in a test file, not at a test body.

pytest
==================================== ERRORS ====================================
_______________ ERROR collecting tests/test_api.py ____________________________
tests/test_api.py:4: in <module>
    from app.services import client
E   ModuleNotFoundError: No module named 'app.services'
!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!

Common causes

A module-level import fails

A test file imports something not installed or not importable in CI, so collection raises before any test runs.

Top-level code in a test file errors

Code at module scope (a constant computed from a missing env var, a syntax error) throws while pytest imports the file.

How to fix it

Fix the failing import or top-level code

  1. Read the collection traceback to find the file and line that raised.
  2. Install the missing dependency or correct the import path / src layout.
  3. Re-run; exit code 2 clears once collection succeeds.
Terminal
python -m pip install -e .
pytest

Move side effects out of module scope

Defer environment-dependent work into fixtures or test bodies so importing the module cannot fail.

tests/conftest.py
@pytest.fixture
def client():
    return make_client(os.environ['API_URL'])

How to prevent it

  • Keep test modules importable without external state at module scope.
  • Install your package so its imports resolve in CI.
  • Move env-dependent setup into fixtures, not module-level code.

Frequently asked questions

What causes ""errors during collection""?
A test file imports something not installed or not importable in CI, so collection raises before any test runs.
How do I fix "errors during collection"?
Fix the failing import or top-level code

Related guides

References

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