Introduction
Patterns help make tests clear and reliable. They guide how to write tests so they catch problems well.
Jump into concepts and practice - no test required
Patterns help make tests clear and reliable. They guide how to write tests so they catch problems well.
# Example of a simple pytest test pattern import pytest def test_example(): # Arrange: set up data or state value = 5 # Act: perform the action result = value + 3 # Assert: check the result assert result == 8
This pattern is called Arrange-Act-Assert (AAA).
It helps keep tests organized and easy to follow.
def test_sum(): # Arrange numbers = [1, 2, 3] # Act total = sum(numbers) # Assert assert total == 6
def test_string_upper(): # Arrange text = 'hello' # Act result = text.upper() # Assert assert result == 'HELLO'
This test file uses the AAA pattern to check the add function with positive and negative numbers.
import pytest def add(a, b): return a + b def test_add_positive_numbers(): # Arrange x = 4 y = 5 # Act result = add(x, y) # Assert assert result == 9 def test_add_negative_numbers(): # Arrange x = -3 y = -7 # Act result = add(x, y) # Assert assert result == -10
Using patterns like AAA makes tests easier to read and maintain.
Patterns reduce mistakes by giving a clear structure to follow.
Consistent test patterns help teams work better together.
Patterns improve test clarity and reliability.
They help avoid repeated code and make tests easier to maintain.
Following patterns builds confidence that tests catch real problems.
def test_sum():
result = sum([1, 2, 3])
assert result == 6
def test_divide():
result = 10 / 0
assert result == 0