How to Fix Collection Error in pytest: Simple Solutions
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.
def add(a, b): return a + b # This test function is incorrectly named def check_add(): assert add(2, 3) == 5
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.
def add(a, b): return a + b # Correctly named test function def test_add(): assert add(2, 3) == 5
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
pytest --collect-only to verify test discovery before running tests.