0
0
PyTesttesting~5 mins

Arrange-Act-Assert pattern in PyTest

Choose your learning style9 modes available
Introduction

The Arrange-Act-Assert pattern helps organize tests clearly. It makes tests easy to read and understand by splitting them into three simple steps.

When writing a new test for a function or feature.
When you want to make your test steps clear and simple.
When debugging tests to find which part fails.
When sharing tests with teammates for easy understanding.
When maintaining tests to add or update checks later.
Syntax
PyTest
def test_example():
    # Arrange
    setup_data = ...

    # Act
    result = function_to_test(setup_data)

    # Assert
    assert result == expected_value

Arrange: Prepare everything needed for the test.

Act: Run the code or function you want to test.

Examples
This test checks if the sum function adds numbers correctly.
PyTest
def test_sum():
    # Arrange
    numbers = [1, 2, 3]

    # Act
    total = sum(numbers)

    # Assert
    assert total == 6
This test verifies that the upper() method converts text to uppercase.
PyTest
def test_uppercase():
    # Arrange
    text = 'hello'

    # Act
    result = text.upper()

    # Assert
    assert result == 'HELLO'
Sample Program

This test checks if the multiply function returns the correct product of two numbers.

PyTest
def multiply(a, b):
    return a * b


def test_multiply():
    # Arrange
    x = 4
    y = 5

    # Act
    product = multiply(x, y)

    # Assert
    assert product == 20
OutputSuccess
Important Notes

Keep each section focused: Arrange only sets up, Act only runs code, Assert only checks results.

Use comments or blank lines to separate the three parts for clarity.

This pattern works well with pytest but can be used in any testing framework.

Summary

The Arrange-Act-Assert pattern organizes tests into three clear steps.

It makes tests easier to read, write, and maintain.

Use it to improve your testing habits and teamwork.