…
…
Python Programming Fundamentals · Lesson 19 / 40 · Errors, debugging, and tests
PreviewIn this lesson you will
assert tests for a function that cover normal, boundary, and invalid input, put them in a test_ function, and show that the tests catch a broken versionYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Ada changed the discount rule at Corner Café and saved the code. A week later a customer said that an order of exactly $10 got no discount, and the mistake had been running quietly at the register for that whole week. In this lesson you will write small tests for functions, so that a mistake like this is caught in a few seconds every time the code changes.
By the end of this lesson you will have written one test function for each of two register functions. When you run the program, only these two lines will appear on the screen:
Outputtest_discount: passed
test_split_bill: passedThese two lines look small, but ten checks stand behind them: each check gives an input to a function and compares the result with a value you calculated by hand. If one check failed, you would see a red error message in place of these lines.
In the previous lesson you learned to pick a small input, calculate the expected value on paper, and compare it with the program's output by eye. This method works, but it has one problem: you do it by hand every time. On the day Ada fixed the discount rule, she tried an order of $30, the result was right, and she thought she was done. She did not think of trying exactly $10. A week later, when she changed something else, she did not try anything again. A check made by eye is forgotten, skipped, and not repeated after every change.
In this lesson you will turn that check into code. A test you write once tries the same inputs and makes the same comparison every time you run it. It does not get tired and it does not forget. You will learn three things:
assert and what happens when it fails,test_ function and read a failed test correctly.assert: silent if the condition is true, stop if it is falseassert is a Python keyword and it takes a condition after it: assert condition. The condition is an expression that gives true or false, like the ones you wrote in lessons 6 and 8. The rule has two parts. If the condition is true, nothing happens: nothing is printed and the program continues with the next line. If the condition is false, the program stops at that line and Python raises an error called AssertionError. In lesson 17 you learned to read a traceback; AssertionError is also an error type, and it appears on the last line of the traceback.
You can also put a comma after the condition and write a message: assert condition, "message". If the condition is false, this message appears next to the error. Do not write a vague message like "error"; say what the function should do: "10 and above should get 10 percent". The person who sees the error, whether it is you or a friend, understands from the message what broke.
A test is the most common use of assert: you call the function with a known input and compare the result with the expected value. The pattern is always the same: assert function(input) == expected. On the left is the result the function really gives; on the right is the result you calculated by hand. If the two are the same, the test passes.
Example 1 (case): The first three tests. Ada's rule is: 10 percent off orders of $10 and above. Because the amount is an integer, one tenth is found with amount // 10.
def discount(amount): if amount >= 10: return amount // 10 return 0 assert discount(30) == 3 assert discount(10) == 1 assert discount(9) == 0 print("tests passed")
Outputtests passedThe three assert lines printed nothing. The only line on the screen comes from the last print. This clears up a common mistake: people think "assert prints something when it passes", but a passing test is completely silent. That is why we put a line that says "passed" at the end of the tests: if you see that line, all the checks above it passed.
What appears on the screen when this program runs?
def discount(amount): if amount >= 10: return amount // 10 return 0 assert discount(30) == 3
Now follow the same program step by step. On each assert line, see that the function is called, which return in the body runs, and that the comparison comes out true. For 9, notice that the if line is false and the last return 0 runs.
Run the code line by line: see which line runs next, the variable boxes and the output.
def discount(amount): if amount >= 10: return amount // 10 return 0 assert discount(30) == 3 assert discount(10) == 1 assert discount(9) == 0 print("tests passed")
So what do we see when a test fails? The second function in Ada's register splits the bill between people. The cents must not disappear: if $10 is split between three people, each person should pay $3.33.
Example 2 (case): A failed test. The function uses floor division (//).
def split_bill(bill, people): return bill // people assert split_bill(30, 2) == 15 assert split_bill(10, 3) == 3.33, "Cents are disappearing" print("Done")
The message Python gives:
OutputTraceback (most recent call last):
File "<code>", line 5, in <module>
assert split_bill(10, 3) == 3.33, "Cents are disappearing"
^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Cents are disappearingThe first test passed, because 30 divides evenly by 2 and // and / give the same result. The second test caught the mistake: 10 // 3 gives 3, and the expected value is 3.33. Read the message from the bottom, as in lesson 17: the type is AssertionError, the explanation is the "Cents are disappearing" that you wrote, and the place is line 5. Done was not printed, because the program stopped at the line with the error. This is also an important lesson: when one test fails, the tests after it never run. You have to make that test pass first.
The real skill here is finding the expected value. We found 3.33 not by running the function and copying the number from the screen, but by dividing 10 by 3 on paper and rounding to two decimal places. If you find the expected value by running the function, you write the function's wrong result into the test: if you had run the function above and put 3 in the test, the test would pass and the mistake would stay hidden forever. The rule is short: calculate the expected value by hand; do not copy it from running the code.
A function can be given an endless number of inputs; you cannot try them all. To catch many mistakes with few tests, you choose inputs from three groups.
Normal input is the typical value the function sees every day: an order of $30, splitting a bill of $30 between two people. It shows that the function does its main job.
Boundary input is exactly on the threshold where the rule changes, and just below it. For the rule "$10 and above", the boundaries are 10 and 9. In lesson 7 you saw testing with boundary values; most mistakes hide here, because a small slip like writing > instead of >= shows up only at the exact threshold. In the split-bill function, a single person is also a boundary: the bill should stay as it is, undivided.
Invalid input is a value the function should not accept: a negative amount, zero people. In real life, pressing a wrong key produces these inputs. You decide in advance what the function will do with such an input and write it in the docstring; you can think of this as the function's promise. In this lesson the promise is: with invalid input, the function returns None. In lesson 8 you learned to ask about None with is None; a test is written exactly that way: assert split_bill(30, 0) is None. There is one more way to report the error openly; you will see it in lesson 32.
The test table for the register's two functions:
| Function | Normal | Boundary | Invalid |
|---|---|---|---|
discount(amount) | 30 → 3 | 9 → 0, 10 → 1 | -5 → None |
split_bill(bill, people) | (30, 2) → 15 | (30, 1) → 30 | (30, 0) → None |
split_bill(bill, people), with cents | (10, 3) → 3.33 | (30, -2) → None |
Filling in the table is a job you can do before writing any code. Calculate each value on the right on paper; if you cannot fill in a row, it means you have not yet decided what the function will do with that input.
See for yourself why the boundary test is a must. The function below has Ada's mistake: > was written instead of >=. The test checks that the discount for the given amount is one tenth of the amount. Change the amount and find which value catches the mistake.
Change the value of amount: at which amount is the mistake caught?
Pick a value; predict the output first, then look.
1def discount(amount):2 if amount > 10:3 return amount // 104 return 056amount = 307print("discount:", discount(amount))8assert discount(amount) == amount // 10, "10 and above should get 10 percent"9print("test passed")
discount: 3 test passed
Faded lines didn't run with this value. For 30 and 15, amount > 10 is also true; the broken function gives the right result and the test passes. Only at exactly 10 is 10 > 10 false, the return 0 on line 4 runs, and the test raises AssertionError. A single test written with a typical input would never have caught this mistake.
Ada's try with $30 showed nothing for this reason. The idea that "one test with a typical input is enough" is wrong: a typical input tests only the main path of the function, not its thresholds.
Now match each test with its group:
Match each test with the type of input it tests.
For each row, pick its match from the list, then check.
assert discount(30) == 3assert discount(10) == 1assert discount(9) == 0assert discount(-5) is Noneassert split_bill(30, 0) is Noneassert split_bill(30, 2) == 15Let us bring all the tests for the split-bill function together. The function now keeps its promise: if the number of people is 0 or negative, it returns None; otherwise it divides the bill and rounds to two decimal places. We put the tests inside a function called test_split_bill; we will talk about the reason in a moment.
Example 3 (case): The split-bill tests.
def split_bill(bill, people): """Splits the bill between people; returns None if people is 0 or negative.""" if people <= 0: return None return round(bill / people, 2) def test_split_bill(): assert split_bill(30, 2) == 15 # normal assert split_bill(10, 3) == 3.33 # with cents assert split_bill(30, 1) == 30 # boundary: one person assert split_bill(30, 0) is None # invalid assert split_bill(30, -2) is None # invalid print("test_split_bill: passed") test_split_bill()
Outputtest_split_bill: passedThe comment next to each test says which group it belongs to. A month later, someone who comes back to this file sees from the comments which cases are tested and which are missing. split_bill(30, 2) actually returns 15.0; because 15.0 == 15 is true, the test passes. Python compares an integer and a float by their values.
There is a trap with decimal results. In lesson 3 you saw that floating-point numbers sometimes carry small leftovers. In a test this leftover matters, because == wants the two numbers to be exactly the same.
Example 4 (case): The decimal comparison trap. The function that adds tax to a price is correct; still, the test fails.
def with_tax(price): return price * 1.1 print(with_tax(85)) assert with_tax(85) == 93.5
Python's output and message:
Output93.50000000000001
Traceback (most recent call last):
File "<code>", line 5, in <module>
assert with_tax(85) == 93.5
^^^^^^^^^^^^^^^^^^^^
AssertionErrorWhen you calculate 10 percent more than $85 by hand, you get $93.50; the expected value is right. But the computer finds 93.50000000000001 for 85 * 1.1, and this number is not exactly equal to 93.5. The message line is empty, because we did not write a message for assert; only AssertionError appears. The fix is to round the result before comparing:
def with_tax(price): return price * 1.1 print(round(with_tax(85), 2)) assert round(with_tax(85), 2) == 93.5 print("test passed")
Output93.5
test passedThe idea that "decimal results can safely be compared with ==" is wrong for this reason. In money calculations, rounding to two decimal places is both natural and enough. In books you may see one more way: asking whether the difference is very small, assert abs(with_tax(85) - 93.5) < 0.001. abs gives the size of a number without its sign. Both work; in this lesson we will use round.
What happens when this line runs?
assert 85 * 1.1 == 93.5As tests multiply, instead of leaving them scattered in the middle of the program, we collect them in one function. Its name starts with test_ and continues with the name of the function it tests: test_discount, test_split_bill. Inside are all the assert lines for that function and a "passed" message at the end. Defining the function does not run the tests; as you saw in lesson 14, the body runs only when the function is called. So do not forget to write the call test_discount() at the bottom: if you forget, the program ends without printing anything and you think the tests passed.
This arrangement has three benefits. First, the tests stay in one place, and you can see at a glance what is tested. Second, whenever you change the code, you rerun all the tests with one line. Third, this naming is a convention: test tools like pytest, which you will use when you work with Python on your own computer, find and run the functions whose names start with test_ by themselves. On this site, the hidden checks that run in the background when you press Check are exactly assert lines like these. Until now you tried to pass them; after this lesson you will write them yourself.
Now let us build the target program from the start of the lesson. Ada widened the discount rule: 15 percent off $25 and above, 10 percent off $10 and above. A negative amount is invalid and returns None. The new rule has two thresholds, so two boundary groups are tested.
Example 5 (case): The target program.
def discount(amount): """Tiered discount amount; None for a negative amount.""" if amount < 0: return None if amount >= 25: return amount * 15 / 100 if amount >= 10: return amount * 10 / 100 return 0 def split_bill(bill, people): """Splits the bill between people; returns None if people is 0 or negative.""" if people <= 0: return None return round(bill / people, 2) def test_discount(): assert discount(15) == 1.5 assert discount(10) == 1 assert discount(9.5) == 0 assert discount(25) == 3.75 assert discount(-2) is None print("test_discount: passed") def test_split_bill(): assert split_bill(30, 2) == 15 assert split_bill(10, 3) == 3.33 assert split_bill(30, 1) == 30 assert split_bill(30, 0) is None print("test_split_bill: passed") test_discount() test_split_bill()
Outputtest_discount: passed
test_split_bill: passedFrom now on, when Ada touches the discount rule, she will run these two calls. If someone accidentally turns the >= 10 line into > 10, the discount(10) == 1 test stops at that moment; the mistake does not wait a week at the register.
Tests are useful not only for the case but for any function with a tricky rule. Think of the leap-year rule: a year divisible by 4 is a leap year, but years divisible by 100 are not; years divisible by 400 are leap years again. This rule has two special cases, and normal inputs never test them.
Example 6 (outside the case): Leap year. We test a function that returns a bool with the same pattern: the real result == the expected one. Writing just assert is_leap_year(2024) also works, but in this lesson we keep to a single pattern.
def is_leap_year(year): return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) def test_is_leap_year(): assert is_leap_year(2024) == True, "2024 is a leap year" assert is_leap_year(2023) == False, "2023 is not a leap year" assert is_leap_year(1900) == False, "1900 is not a leap year (divisible by 100)" assert is_leap_year(2000) == True, "2000 is a leap year (divisible by 400)" print("test_is_leap_year: passed") test_is_leap_year()
Outputtest_is_leap_year: passedNow suppose someone "simplifies" the function and shortens the parenthesized part to year % 100 != 0: return year % 4 == 0 and year % 100 != 0. The 2024, 2023, and 1900 tests still pass. Only the 2000 test catches it:
OutputTraceback (most recent call last):
File "<code>", line 11, in <module>
test_is_leap_year()
~~~~~~~~~~~~~~~~~^^
File "<code>", line 8, in test_is_leap_year
assert is_leap_year(2000) == True, "2000 is a leap year (divisible by 400)"
^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 2000 is a leap year (divisible by 400)The traceback has two levels, because the assert is inside a function. Read it as in lesson 17: the last File block is the place of the error, line 8 inside test_is_leap_year; the block above says it was reached by the call on line 11. The message explains in its own words which rule was broken.
When a test fails, the first thought is "the function is broken". This is not always true: the test was also written by a person, and the expected value may have been calculated wrong. The right order is this. First, find from the traceback which assert line stopped. Then recalculate the expected value of that line by hand, with a calm head. If the expected value is wrong, fix the test. If the expected value is right, the problem is in the function, and you fix it with the methods of the previous lesson (a small input, printing intermediate values, tracing line by line).
Think of the opposite too: all the tests passed. This does not mean "the function is right for every input"; it means "right for the inputs I tried". Without the 2000 test above, the broken leap-year function would have passed all the tests. Tests give assurance only for the inputs they try. This is why we choose boundaries and special cases: few tests, but placed where mistakes hide.
Let us finish this section with a good habit: when you find a bug, first write the test that shows it, then fix it. The test fails first, passes after the fix, and stays in the file. If the same bug comes back months later, the test tells you right away. Put the steps below in the order of this habit.
You found a bug. Put the steps in the order of the "catch the bug with a test" habit.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Now it is your turn. In the cell below there is the leap-year function and only two normal tests. Try these three things in order: (1) Add two tests for 1900 and 2000 and run them. (2) Delete the or year % 400 == 0 part from the function (you can remove the parentheses too): which test catches it, and what does the message say? (3) Put the function back as it was and write a test for your own birth year; first find the expected value on paper.
Try it now· not graded; doesn't affect progress
assert line in parenthesesYou are used to writing the arguments inside parentheses when you call a function. This habit is dangerous with assert, because assert is not a function; it is a keyword. If you write assert (1 + 1 == 3, "error"), Python sees what is inside the parentheses as a single package: a package that holds a condition and a message. assert now tests not the condition but this package. In lesson 8 you saw that an empty string and None count as false and non-empty values count as true; a package with something inside also counts as true. The result: this test always passes, whatever the condition is, and catches no mistake.
Predict first:
What happens when these two lines run?
assert (1 + 1 == 3, "error") print("Got here")
When you run these two lines on your own computer, Python writes this:
Output<code>:1: SyntaxWarning: assertion is always true, perhaps remove parentheses?
Got hereThe warning means: "This check is always true; did you mean to remove the parentheses?" A warning is not an error and the program keeps running, so it is easy to miss. Keep the rule in mind: do not put parentheses around the condition and the message in an assert line. Using parentheses inside the condition is not a problem: assert (a + b) == 10, "total" works correctly, because the parentheses wrap only the sum and the comma is outside.
At Corner Café, the loyalty card gives one free coffee for 10 stamps. The stamps_left function should say how many stamps are left until the free coffee; when the card is exactly full (10, 20 stamps), it should return 0. The first version was 10 - stamps % 10, and with exactly 10 stamps it returned 10: when the card was full, it said "10 stamps left". Ada first wrote the test stamps_left(10) == 0 that shows the bug, saw that the test stopped, and then fixed the function. Now all the tests pass.
def stamps_left(stamps): """Stamps left until the free coffee; None for negative stamps.""" if stamps < 0: return None return (10 - stamps % 10) % 10 def test_stamps_left(): assert stamps_left(3) == 7 # normal assert stamps_left(9) == 1 # boundary: almost full assert stamps_left(10) == 0 # boundary: card is full (catches the bug) assert stamps_left(23) == 7 # normal: second card assert stamps_left(-1) is None # invalid print("test_stamps_left: passed") test_stamps_left()
test_stamps_left: passed
Writing `=` instead of `==` in an `assert` line. When you write a comparison, a single equals sign easily slips from your fingers:
def discount(amount): return 0 assert discount(10) = 1
Output File "<code>", line 4
assert discount(10) = 1
^
SyntaxError: invalid syntaxThis is not an AssertionError, it is a SyntaxError: Python stops while reading the line, and no line of the program runs. A single = is assignment; it means "put the right side in the box on the left", while what assert wants is a comparison that gives true or false. The Python on your own computer may add a suggestion like "did you mean ==?" to this line. The right way is a double equals sign: assert discount(10) == 1. For None, you use is, not ==: assert discount(-5) is None.
assert condition, "message" passes silently if the condition is true, and stops the program with AssertionError and the message if it is false. The test pattern is assert function(input) == expected; the expected value is calculated by hand, not copied from running the code. An assert line is not put in parentheses.is None) separately; decimal results are compared with round.test_ and called after every change. When a test fails, you first recalculate the expected value; all tests passing is assurance only for the inputs tried.Next lesson: In the unit task you will write unit and currency converter functions and add their own tests; then we will learn to reach the single characters inside strings.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
The letter-grade rule for a course: 85 and above is A, 70 and above is B, 50 and above is C, below that is F. A score below 0 or above 100 is invalid. For each of the three thresholds, the exact threshold and the value just below it are tested separately; although there are ten tests in total, each one tests something different.
def letter_grade(score): """Converts a score to a letter grade; None for a score outside 0-100.""" if score < 0 or score > 100: return None if score >= 85: return "A" if score >= 70: return "B" if score >= 50: return "C" return "F" def test_letter_grade(): assert letter_grade(92) == "A" # normal assert letter_grade(85) == "A" # boundary assert letter_grade(84) == "B" # boundary assert letter_grade(70) == "B" # boundary assert letter_grade(69) == "C" # boundary assert letter_grade(50) == "C" # boundary assert letter_grade(49) == "F" # boundary assert letter_grade(100) == "A" # boundary: highest score assert letter_grade(101) is None # invalid assert letter_grade(-5) is None # invalid print("test_letter_grade: passed") test_letter_grade()
Outputtest_letter_grade: passed