0
0
PytestHow-ToBeginner ยท 4 min read

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 Test and 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 Test classes 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

ItemNaming Rule
Test fileStarts with 'test_' or ends with '_test.py'
Test function or methodStarts with 'test_'
Test classStarts with 'Test' and no __init__ method
Non-test codeShould 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.