Python · Module 13 · Lesson 11 min read

Unit Testing with pytest

Why test?

Tests check your code automatically, so you can change it later without fear of breaking something.

pytest basics

  • Put tests in files named test_*.py and functions named test_*. pytest finds them automatically.
  • Use plain assert: assert add(2, 3) == 5.
  • Run everything with pytest, or pytest -v for details.

Must-know features

FeatureUse
pytest.raises(ValueError)check that an error is raised
@pytest.mark.parametrizerun one test with many inputs
@pytest.fixturereusable setup (sample data, temp files)
pytest.approx(0.3)compare floats safely (0.1 + 0.2 != 0.3!)

What makes a good test

  • Test one behaviour per test, with a descriptive name.
  • Cover normal cases, edge cases (empty list, zero, negative) and errors.
  • Follow Arrange → Act → Assert.

💻 Run pytest on a computer (pip install pytest).

Example

Python
# test_calculator.py — run with:  pytest -v
import pytest

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

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

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

@pytest.mark.parametrize("a, b, expected", [
    (1, 1, 2),
    (-1, 1, 0),
    (0.1, 0.2, pytest.approx(0.3)),
])
def test_add_many(a, b, expected):
    assert add(a, b) == expected

def test_divide_by_zero():
    with pytest.raises(ValueError, match="zero"):
        divide(1, 0)

@pytest.fixture
def numbers():
    return [3, 1, 2]

def test_sorted(numbers):
    assert sorted(numbers) == [1, 2, 3]