Labs ICT
โญ Pro Login

Test Functions & Naming

Rules for writing test functions that pytest can discover.

Test Function Naming Rules

pytest discovers tests based on naming conventions. To ensure your tests are found and executed correctly, follow these rules:

  • Test files must be named test_*.py or *_test.py.
  • Test functions must start with test_.
  • Test classes must start with Test and contain test_ methods.
  • Test methods inside test classes must start with test_.

Writing Test Functions

A test function is a regular Python function that starts with test_ and uses assert to verify behavior:

# test_string_utils.py

def upper(s):
    return s.upper()

def test_upper_basic():
    assert upper("hello") == "HELLO"

def test_upper_empty():
    assert upper("") == ""

def test_upper_numbers():
    assert upper("abc123") == "ABC123"

Test Classes

You can group related tests into classes. The class name must start with Test (with a capital T) and must not have an __init__ method:

class TestStringUpper:
    def test_basic(self):
        assert "hello".upper() == "HELLO"

    def test_empty(self):
        assert "".upper() == ""

    def test_with_spaces(self):
        assert "hello world".upper() == "HELLO WORLD"

Test classes are useful for grouping tests that share the same setup or test the same component.

Writing Descriptive Test Names

Good test names describe what is being tested and the expected outcome:

# Bad names
def test_1():
    assert True

def test_function():
    assert add(1, 2) == 3

# Good names
def test_add_returns_sum_of_two_positive_numbers():
    assert add(1, 2) == 3

def test_add_handles_zero():
    assert add(0, 5) == 5

def test_add_handles_negative_numbers():
    assert add(-1, -2) == -3

Descriptive names make it easy to understand what went wrong when a test fails.

๐Ÿงช Quick Quiz

What must a test function name start with?