Testing Python code
Assertions and test cases
Compare actual results with expected results.
Lesson 44 of 63
Reading: about 1 min
Lesson + practice: about 13 min
Difficulty: Intermediate
On this page5 sections
A test uses a known input and checks the result. assert is useful for a quick check. unittest also provides assertion methods such as assertEqual; run tests without the -O optimization flag.
Worked example
def double(value):
return value * 2
assert double(4) == 8
print("check passed")check passed
Why this works
The expression after assert is true, so execution continues. A false assertion raises AssertionError. Good tests cover behavior rather than repeating the implementation.
Another case
def double(value):
return value * 2
print(double(-3))-6
Practice
Check double(0) and double(-3). What results should the function return?
Check the practice result
Reveal answer
They return 0 and -6.
Try another case
What happens when assert double(2) == 5 runs?
Check your answer
Reveal answer
It raises AssertionError because double(2) returns 4, and the script stops at that line.
Your progress
Reveal the check answer or reach the end to complete this lesson.