How to Write Unit Tests with pytest: A Practical Guide

pytest is Python’s most popular testing framework, combining simple syntax with powerful features and minimal boilerplate. This practical guide covers the essentials of writing unit tests with pytest, from basic assertions to reusable fixtures, so you can start testing your code with confidence.

Install pytest using pip install pytest. Create a test file named test_*.py or *_test.py, and place it in your project directory. Write test functions prefixed with test_ — pytest automatically discovers and executes them.

Article illustration

1. Write Simple Test Functions

Define functions starting with test_ and use assert statements to validate expected behavior:

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

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0

2. Test Exceptions and Floating-Point Values

Use pytest.raises to verify exceptions and pytest.approx for accurate floating-point comparisons:

import pytest

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

def test_divide():
    with pytest.raises(ValueError):
        divide(1, 0)
    assert divide(1, 3) == pytest.approx(0.3333)

3. Share Setup Code with Fixtures

Fixtures provide reusable setup and teardown. Decorate a function with @pytest.fixture and inject it as a test parameter:

@pytest.fixture
def sample_data():
    return {"a": 1, "b": 2}

def test_sum(sample_data):
    assert sample_data["a"] + sample_data["b"] == 3

4. Run and Control Tests

Execute pytest in the terminal. Useful options include:

  • -v — verbose output
  • -k — filter tests by name
  • --maxfail=1 — stop after first failure

Detailed reports show exact tracebacks, making debugging fast and efficient.

Writing unit tests with pytest is straightforward yet scales to complex projects. Start with simple asserts, add fixtures to organize reusable state, and explore features like parametrized tests and mocking to make your suite robust. A solid test suite keeps your code reliable and maintainable.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *