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.
==================================== 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
- Read the collection traceback to find the file and line that raised.
- Install the missing dependency or correct the import path / src layout.
- Re-run; exit code 2 clears once collection succeeds.
python -m pip install -e .
pytestMove side effects out of module scope
Defer environment-dependent work into fixtures or test bodies so importing the module cannot fail.
@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.