Syllabus Lesson 62 of 239 · Pythonic Code, Testing & Capstone
Pythonic Code, Testing & Capstone

Testing with pytest-style asserts

Tests are how you prove your code works and keep it working as you change it. The most popular Python test tool is pytest, and its style is refreshingly plain: a test is just a function whose name starts with test_, and it checks things with the ordinary assert statement.

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

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

def test_add_with_zero():
    assert add(0, 7) == 7

If the condition is true, the test passes silently. If it is false, assert raises AssertionError and pytest reports a failure, showing you the actual values. You run them from a terminal with the command pytest, which discovers and runs every test_ function for you.

Good tests cover more than the happy path. Think about edge cases: empty input, zero, negatives, the boundary value. A small habit that pays off: write a test for the bug before you fix it, so you know the fix actually worked.

def test_add_negatives():
    assert add(-2, -3) == -5

def test_add_identity():
    assert add(5, 0) == 5

You can put a short message after the condition to explain what should be true: assert add(2, 2) == 4, "two plus two is four". That message shows up when the test fails, making the report easier to read.

Your turn

First write average(numbers) that returns the mean of a list, and returns 0 for an empty list (no crash). Then write two pytest-style test functions for it: test_average_basic (asserts average([2, 4, 6]) == 4) and test_average_empty (asserts average([]) == 0). Each test function must contain at least one assert.

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output