Python Tutorial · Going Further · Lesson 41 of 42

Python Testing with pytest

Write tests with assert and pytest, and why tests matter.

Why test?

Tests check that code does what you expect — and keep checking every time you change it.

assert

assert raises an AssertionError when its condition is false:

Example 1Try it yourself
def apply_discount(price, rate):
    return max(price - price * rate, 0)

assert apply_discount(100, 0.1) == 90
assert apply_discount(10, 2) == 0
print("all assertions passed")

Output

all assertions passed

pytest

pytest is the most popular Python test runner. Put tests in files named test_*.py, write functions starting with test_, and use plain assert:

# test_pricing.py
from pricing import apply_discount

def test_ten_percent_off():
    assert apply_discount(100, 0.1) == 90

def test_discount_cannot_exceed_price():
    assert apply_discount(10, 2) == 0
pip install pytest
pytest

A tiny test runner

Here's the idea behind pytest in a few lines — find test functions and report the results:

Example 2Try it yourself
def add(a, b):
    return a + b

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

def test_add_strings():
    assert add("a", "b") == "ab"

def test_broken():
    assert add(2, 2) == 5

for name, fn in list(globals().items()):
    if name.startswith("test_"):
        try:
            fn()
            print("PASS", name)
        except AssertionError:
            print("FAIL", name)

Output

PASS test_add_numbers
PASS test_add_strings
FAIL test_broken

Test yourself

What must pytest test function names start with?

  1. check_
  2. test_
  3. spec_
  4. it_
Show answer

Answer: test_