Show contents
Chapter 4 of 6 · 20 min
Testing your code so you can sleep at night
By the end of this chapter, you'll be able to
- Write test functions with assert and a clear message
- Choose test cases: normal, edge and invalid
- Test that a function really raises an error
- Run your tests with pytest in a real project
A test is a function that checks
A test calls your code with known data and checks the result with assert. If it's wrong, assert raises an AssertionError: the test fails. By convention, each test is a function whose name starts with test_ and describes the case checked.
def price_with_tax(price, rate):
return round(price * (1 + rate / 100), 2)
def test_normal_rate():
assert price_with_tax(100, 20) == 120
def test_zero_rate():
assert price_with_tax(19.99, 0) == 19.99
def test_rounding():
assert price_with_tax(9.99, 5.5) == 10.54
def run(*tests):
passed = 0
for test in tests:
try:
test()
print("OK ", test.__name__)
passed += 1
except AssertionError:
print("FAIL ", test.__name__)
print(f"{passed}/{len(tests)} tests passed")
run(test_normal_rate, test_zero_rate, test_rounding)
OK test_normal_rate
OK test_zero_rate
OK test_rounding
3/3 tests passed
run is a mini test runner: it runs each function, catches the failures and gives a summary. *tests lets you pass it as many functions as you like, and test.__name__ gives each function's name. In a real project, the pytest tool plays this role (see below).
Which cases to test?
A single test "that works" doesn't prove much. For each function, think of three families of cases:
- the normal case: the most common use (
price_with_tax(100, 20)); - the edge cases: zero, empty list, first or last item, a value right on the boundary;
- the invalid cases: forbidden data must be refused cleanly.
Bugs mostly hide in edge cases. To test many cases at once, store them in a dictionary {input: expected result}. The second argument of assert is a message displayed when it fails:
def is_leap(year):
if year % 400 == 0:
return True
if year % 100 == 0:
return False
return year % 4 == 0
cases = {2024: True, 2023: False, 1900: False, 2000: True, 2100: False}
for year, expected in cases.items():
assert is_leap(year) == expected, f"{year}: expected {expected}"
print(len(cases), "cases checked")
5 cases checked
A naive version, return year % 4 == 0, would pass the tests on 2024 and 2023… but fail on 1900:
def is_leap(year):
return year % 4 == 0
cases = {2024: True, 2023: False, 1900: False}
for year, expected in cases.items():
assert is_leap(year) == expected, f"{year}: expected {expected}"
Python stops on AssertionError: 1900: expected False: the message immediately says which case is the problem. Without the edge case 1900, this bug would have gone unnoticed.
assert raises an AssertionError with the message: we know exactly which case to fix.
Text description of the animation
- Naive version: is_leap simply returns year % 4 == 0.
- 2024 is divisible by 4: the result is right, assert says nothing.
- 2023: right too. Two tests passed, you could believe the function is correct.
- 1900 is divisible by 4 but isn't a leap year (a century not divisible by 400). The result is wrong.
- assert raises an AssertionError with the message: we know exactly which case to fix.
Testing that an error is really raised
An invalid case must raise an error. To check it, you call the function inside a try. If nothing is raised, you make the test fail yourself:
def average(grades):
return sum(grades) / len(grades)
def test_simple_average():
assert average([10, 14]) == 12
def test_empty_list():
try:
average([])
except ZeroDivisionError:
raise AssertionError("average([]) crashes instead of returning 0")
for test in (test_simple_average, test_empty_list):
try:
test()
print("OK ", test.__name__)
except AssertionError as error:
print("FAIL ", test.__name__, "-", error)
OK test_simple_average
FAIL test_empty_list - average([]) crashes instead of returning 0
Here, the test did its job: it found a real bug. An empty list makes average crash. We fix the function (if not grades: return 0), run again, and the test passes.
In a real project: pytest
On your computer, the standard tool is called pytest (install it with pip install pytest). You write your tests in test_*.py files, with no runner: pytest finds the test_… functions by itself, runs them and shows a detailed report. pytest.raises replaces the try to check that an error is raised.
# File test_price.py: run the pytest command in the project folder
import pytest
from price import price_with_tax, average
def test_normal_rate():
assert price_with_tax(100, 20) == 120
def test_average_empty_list():
assert average([]) == 0
def test_negative_rate_refused():
with pytest.raises(ValueError):
price_with_tax(100, -5)
Your turn
Worked exercise
Worked exercise: initials
Here's a function that's supposed to return the initials of a name ("ada lovelace" gives "A.L."). Write at least four tests: a normal case, a compound name with a hyphen ("Jean-Paul Sartre" gives "J.S.": the hyphen doesn't create a new word), extra spaces, and an empty string. Find and fix the bug your tests reveal.
def initials(full_name):
words = full_name.split(" ")
return "".join(w[0].upper() + "." for w in words)
assert initials("ada lovelace") == "A.L."
assert initials("Jean-Paul Sartre") == "J.S."
assert initials(" grace hopper ") == "G.H."
Hint 1
" a b ".split(" ") contains empty strings.Hint 2
split() with no argument splits on any run of spaces and ignores those at the start and the end.Show the solution and common mistakes
def initials(full_name):
words = full_name.split()
return "".join(w[0].upper() + "." for w in words)
assert initials("ada lovelace") == "A.L."
assert initials("Jean-Paul Sartre") == "J.S."
assert initials(" grace hopper ") == "G.H."
assert initials("") == ""
print("All the tests pass")
All the tests pass
With split(" "), the extra spaces produce empty "words", and w[0] on an empty string raises an IndexError. split() with no argument solves the problem, and the empty string naturally gives "".
Common mistakes:
- Only testing
"ada lovelace": the test passes, and the spaces bug stays hidden. - Fixing the code so that it passes one specific test (
if full_name == " grace hopper ": …) instead of fixing the cause.
Summary
- 1A test calls the code with known data and checks the result with assert.
- 2Test the normal case, the edge cases and the invalid cases: bugs hide on the boundaries.
- 3For an invalid case, check that the expected error is really raised.
- 4Don't compare decimals with ==: round them or use math.isclose.
- 5In a real project, pytest finds and runs the test_… functions automatically.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.