0
0
PytestDebug / FixBeginner · 4 min read

How to Fix Collection Error in pytest: Simple Solutions

A collection error in pytest usually happens when pytest cannot find or load test files or functions due to naming or syntax issues. To fix it, ensure your test files and functions follow pytest naming conventions and contain valid Python code.
🔍

Why This Happens

Pytest collects tests by scanning files and functions that match certain naming patterns. If your test file or function names don't start with test_ or end with _test.py, pytest won't find them. Also, syntax errors or import problems in test files cause collection errors.

python
def add(a, b):
    return a + b

# This test function is incorrectly named

def check_add():
    assert add(2, 3) == 5
Output
ERROR collecting test_sample.py collected 0 items / 1 error ERROR: file contains syntax errors or import errors preventing collection
🔧

The Fix

Rename test functions to start with test_ so pytest can collect them. Also, check your test files for syntax errors and fix them. This allows pytest to find and run your tests without collection errors.

python
def add(a, b):
    return a + b

# Correctly named test function

def test_add():
    assert add(2, 3) == 5
Output
============================= test session starts ============================== collected 1 item test_sample.py . [100%] ============================== 1 passed in 0.01s ===============================
🛡️

Prevention

Always name your test files starting with test_ or ending with _test.py, and test functions starting with test_. Use an editor or linter to catch syntax errors early. Run pytest --collect-only to check which tests pytest finds before running them.

⚠️

Related Errors

Other common pytest errors include import errors when test files cannot find modules, and indentation errors causing syntax failures. Fix these by verifying import paths and using consistent indentation (spaces preferred).

Key Takeaways

Always name test files and functions using pytest conventions to avoid collection errors.
Fix syntax and import errors in test files to ensure pytest can collect tests.
Use pytest --collect-only to verify test discovery before running tests.
Lint your code and use an editor to catch errors early.
Check import paths and indentation to prevent related errors.