0
0
PyTesttesting~5 mins

Test file and function naming conventions in PyTest

Choose your learning style9 modes available
Introduction

Good naming helps pytest find and run your tests automatically. It also makes your tests easy to understand.

When creating new test files to organize your tests clearly.
When writing test functions so pytest can detect and run them.
When sharing tests with teammates to keep naming consistent.
When debugging tests to quickly find the right test file or function.
When setting up automated test runs that rely on naming patterns.
Syntax
PyTest
Test file names: start with 'test_' or end with '_test.py'
Test function names: start with 'test_'

Pytest automatically discovers files and functions following these patterns.

Using these conventions avoids the need to manually specify test locations.

Examples
A test file named with 'test_' prefix and a test function starting with 'test_'.
PyTest
test_math_operations.py

def test_addition():
    assert 1 + 1 == 2
A test file named with '_test' suffix and a test function starting with 'test_'.
PyTest
calculator_test.py

def test_subtraction():
    assert 5 - 3 == 2
Another example showing the standard naming for test files and functions.
PyTest
test_utils.py

def test_helper_function():
    assert helper() == 'done'
Sample Program

This test file named 'test_math.py' contains a test function 'test_add' that pytest will find and run automatically.

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

# test_math.py

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
    assert add(0, 0) == 0
OutputSuccess
Important Notes

Always start test function names with 'test_' so pytest can detect them.

Test files should be named starting with 'test_' or ending with '_test.py' for automatic discovery.

Keep names descriptive but simple to help others understand what is tested.

Summary

Test files must start with 'test_' or end with '_test.py'.

Test functions must start with 'test_'.

Following these rules lets pytest find and run your tests automatically.