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_*.pyand functions namedtest_*. pytest finds them automatically. - Use plain
assert:assert add(2, 3) == 5. - Run everything with
pytest, orpytest -vfor details.
Must-know features
| Feature | Use |
|---|---|
pytest.raises(ValueError) | check that an error is raised |
@pytest.mark.parametrize | run one test with many inputs |
@pytest.fixture | reusable 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
# 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]