How to Use pytest Naming Convention for Test Discovery
In
pytest, test files should start with test_ or end with _test.py, and test functions or methods must start with test_. This naming convention allows pytest to automatically find and run your tests without extra configuration.Syntax
pytest uses specific naming rules to find tests automatically:
- Test files: Must be named starting with
test_or ending with_test.py. - Test functions or methods: Must start with
test_. - Test classes: Should start with
Testand not have an__init__method.
Following these rules ensures pytest discovers your tests without extra setup.
python
test_example.py def test_addition(): assert 1 + 1 == 2 class TestMath: def test_subtraction(self): assert 2 - 1 == 1
Example
This example shows a test file named test_math.py with two test functions and one test class. All follow pytest naming conventions, so pytest will find and run them automatically.
python
test_math.py def test_multiply(): assert 3 * 4 == 12 class TestDivision: def test_divide(self): assert 10 / 2 == 5 def test_divide_by_zero(self): import pytest with pytest.raises(ZeroDivisionError): _ = 1 / 0
Output
============================= test session starts ==============================
collected 3 items
test_math.py ... [100%]
============================== 3 passed in 0.01s ===============================
Common Pitfalls
Common mistakes include:
- Naming test files or functions without the
test_prefix, so pytest skips them. - Using
Testclasses with an__init__method, which pytest does not support. - Defining test functions inside classes that do not start with
Test.
Always follow the naming rules strictly to avoid missing tests.
python
wrong_name.py def add_test(): assert 1 + 1 == 2 class MathTests: def test_subtract(self): assert 2 - 1 == 1 # Correct naming test_correct.py def test_add(): assert 1 + 1 == 2 class TestMath: def test_subtract(self): assert 2 - 1 == 1
Quick Reference
| Item | Naming Rule |
|---|---|
| Test file | Starts with 'test_' or ends with '_test.py' |
| Test function or method | Starts with 'test_' |
| Test class | Starts with 'Test' and no __init__ method |
| Non-test code | Should not start with 'test_' to avoid confusion |
Key Takeaways
Always name test files starting with 'test_' or ending with '_test.py' for pytest to find them.
Prefix test functions and methods with 'test_' to ensure pytest discovers and runs them.
Test classes should start with 'Test' and must not have an __init__ method.
Incorrect naming causes pytest to skip tests silently, so follow conventions strictly.
Use the quick reference table to remember pytest naming rules easily.