0
0
PyTesttesting~5 mins

Single responsibility per test in PyTest

Choose your learning style9 modes available
Introduction

Each test should check only one thing. This makes tests easier to understand and fix.

When you want to find exactly what is broken quickly.
When tests become hard to read because they check many things.
When you want to keep tests simple and clear.
When you want to avoid one test failing for many reasons.
When you want to write tests that are easy to maintain.
Syntax
PyTest
def test_function():
    # Arrange
    # Act
    # Assert
    assert something == expected_value

Each test function should focus on one behavior or feature.

Use clear names to show what the test checks.

Examples
This test checks adding two positive numbers only.
PyTest
def test_add_positive_numbers():
    result = add(2, 3)
    assert result == 5
This test checks adding two negative numbers only.
PyTest
def test_add_negative_numbers():
    result = add(-1, -4)
    assert result == -5
This test checks adding zero to a number only.
PyTest
def test_add_zero():
    result = add(0, 5)
    assert result == 5
Sample Program

This example shows three tests. Each test checks one simple case of the add function. This way, if one test fails, you know exactly which case has a problem.

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


def test_add_positive_numbers():
    result = add(2, 3)
    assert result == 5

def test_add_negative_numbers():
    result = add(-1, -4)
    assert result == -5

def test_add_zero():
    result = add(0, 5)
    assert result == 5
OutputSuccess
Important Notes

Keep tests small and focused to find bugs faster.

One test = one reason to fail.

Good test names help understand what is tested.

Summary

Write tests that check only one thing.

This makes tests easier to read and fix.

Clear test names help everyone understand the test purpose.