Comprehensive Guide to Common pytest Assertion Techniques
This article introduces the core assertion methods in pytest, covering basic assertions, multiple assertions, exception handling, specific exception messages, list and dictionary checks, floating‑point approximations, string and tuple validation, subset verification, and log capture, each illustrated with clear Python code examples.
Preface In pytest, assertions are a core part of test cases, used to verify that functions or methods produce expected results and provide detailed error information for quick debugging.
1. Basic Assertions Demonstrates a simple add function and test cases that use assert to compare the function's output with expected values.
def add(a, b):
return a + b def test_add():
assert add(1, 2) == 3
assert add(-1, 1) == 0
assert add(0, 0) == 02. Multiple Assertions Shows how several assert statements can be placed in a single test to verify multiple conditions.
def test_add_multiple_conditions():
assert add(1, 2) == 3
assert add(-1, 1) == 0
assert add(0, 0) == 0
assert add(100, 200) == 3003. Assertion of Exceptions Uses the with pytest.raises() context manager to confirm that a function raises a specific exception.
def divide(a, b):
return a / b def test_divide_zero():
with pytest.raises(ZeroDivisionError):
divide(1, 0)4. Assertion of Specific Exception Messages Verifies that the raised exception contains a particular message by using the match argument.
def test_divide_zero_message():
with pytest.raises(ZeroDivisionError, match="division by zero"):
divide(1, 0)5. Assertions on Lists and Dictionaries Checks that functions return expected list or dictionary structures.
def process_data():
return [1, 2, 3] def test_process_data():
assert process_data() == [1, 2, 3] def get_user_info():
return {"name": "Alice", "age": 25} def test_get_user_info():
assert get_user_info() == {"name": "Alice", "age": 25}6. Assertions on Floating‑Point Numbers Uses pytest.approx to compare floating‑point results within a tolerance.
def calculate_pi():
return 3.14159265358979323846 def test_calculate_pi():
assert calculate_pi() == pytest.approx(3.141592653589793, abs=1e-10)7. Assertions on Strings Validates that a function returns the expected string.
def greet(name):
return f"Hello, {name}!" def test_greet():
assert "Hello, Alice!" == greet("Alice")
assert "Hello, Bob!" == greet("Bob")8. Assertions on Tuples Checks that a function returns the correct tuple.
def get_coordinates():
return (1.0, 2.0) def test_get_coordinates():
assert get_coordinates() == (1.0, 2.0)9. Assertions on Subsets of Lists and Dictionaries Uses all and any to verify conditions across collection elements.
def get_students():
return [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}] def test_get_students():
students = get_students()
assert all(student["age"] >= 18 for student in students)
assert any(student["name"] == "Alice" for student in students)10. Assertions on Log Output Captures log messages with the caplog fixture and asserts that a specific message appears.
import logging
logger = logging.getLogger(__name__)
def log_error(message):
logger.error(message) def test_log_error(caplog):
caplog.set_level(logging.ERROR)
log_error("An error occurred")
assert "An error occurred" in caplog.text11. Summary The guide covered basic, multiple, exception, message‑specific, collection, floating‑point, string, tuple, subset, and log assertions in pytest, providing practical code snippets for each scenario.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.