Testing your code: assert and unittest
🌍 In real life. A car factory tests the brakes of every car before it leaves, and a cook tastes the curry before serving it. Nobody waits for a customer to find the problem.
A program can be checked the same way, by more code. The idea in one sentence: a test runs your code on an input whose right answer you already know and checks the answer, so a mistake shows up at once, every time you change the code.
Its words:
assert condition: does nothing when the condition is True, and stops with an AssertionError when it is False- test case: one input and its expected answer; edge case: an unusual one (empty, negative, one item, the biggest allowed)
unittest: Python's built-in testing tool: a class of test methods, each checked withself.assertEqual(got, expected)and friends- regression: a bug that comes back after it was fixed; the test written for it catches it
Step by step:
- for each input, write down the answer you expect, before you run anything
- check it:
assert area(2, 3) == 6 - include edge cases, where bugs like to hide
- run all the tests after every change
Watch a test catch a bug: area adds instead of multiplying, so the assert fails and the except reports it.
Why tests are worth writing. Checking by hand means running the program and reading its output, every time, for every case, and it's easy to skip one. A test does the same check in a fraction of a second, never gets bored, and keeps working after you've forgotten why the case mattered. With a test for each fixed bug, a later change that brings one back fails at once.
For more than a few checks, unittest keeps them organised: each method whose name starts with test is one test, and the runner reports which ones failed and why. In this app, run them with a runner and print its counts (the runner's own report also gives the time taken, which changes from run to run):
import io
import unittest
def area(w, h):
return w * h
class TestArea(unittest.TestCase):
def test_small(self):
self.assertEqual(area(2, 3), 6)
def test_zero(self): # an edge case
self.assertEqual(area(0, 5), 0)
def test_bad_input(self):
with self.assertRaises(TypeError):
area("2", "3")
suite = unittest.TestLoader().loadTestsFromTestCase(TestArea)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite) # the report is kept, not shown
print("tests run:", result.testsRun)
print("failed:", len(result.failures) + len(result.errors))
print("all passed:", result.wasSuccessful())pytest: the tool most projects use. unittest comes with Python, but most Python projects test with pytest, installed with pip install pytest. A pytest test is just a function whose name starts with test_, using a plain assert. In a terminal, pytest finds every file named test_*.py, runs every test_ function in it, and when an assert fails it shows the values on both sides, like assert 5 == 6, so you see at once what went wrong. It runs from a terminal, not inside this browser app; the shape of the tests is the part to learn:
def area(w, h):
return w * h
def test_small():
assert area(2, 3) == 6
def test_zero():
assert area(0, 5) == 0
# pytest would find and run every test_ function itself; here we call them by hand
for test in [test_small, test_zero]:
test()
print(test.__name__, "passed")Mistakes and edge cases.
- brackets around an assert:
assert (x > 0, "must be positive")checks a tuple, and a non-empty tuple is always True, so it never fails; writeassert x > 0, "must be positive" - assert for checking user input: Python skips every assert when run with
python -O, so asserts are for catching the programmer's mistakes; for bad input,raise ValueError(Lesson 18.3) - testing only the easy case: a test with an ordinary input misses the bug in the edge case; try empty, one item, negatives and the limits
- comparing decimals with assertEqual:
0.1 + 0.2isn't exactly0.3(Lesson 3.4); useself.assertAlmostEqual - a test method without the
testprefix:def check_small(self)is never run, so a broken test can look like a passing one
Quiz
What does this print?
def double(x): return x * 2 assert double(4) == 8 print("ok") try: assert double(3) == 7, "double(3) should be 6" except AssertionError as e: print("failed:", e)Why should a function not use
assertto check what a user typed?- Asserts can be switched off (python -O), so the check would vanish
- assert is slower than if
- assert only works inside classes
assert (len(items) > 0, "empty")with an empty list. What happens?- Nothing: it checks a two-item tuple, which is always True
- AssertionError: empty
- A TypeError
Which test is most likely to catch a
biggest(nums)that starts withbest = 0?- biggest([-5, -2, -9]) == -2
- biggest([3, 7, 1]) == 7
- biggest([10]) == 10
The runner says it ran 1 test, but there are two. Which line is wrong?
import unittest class TestText(unittest.TestCase): def test_upper(self): self.assertEqual("a".upper(), "A") def check_lower(self): self.assertEqual("A".lower(), "a")How does pytest find your tests?
- It runs every function named test_… in files named test_*.py
- You list each test in a TestSuite by hand
- It runs every function in your program
Coding tasks
average(nums)crashes with a ZeroDivisionError on an empty list. Add anassertas its first line, soaverage([])stops with an AssertionError saying"average of nothing"instead.biggest(nums)is right;bad_biggesthas a common bug. Writeclass TestBiggest(unittest.TestCase)with at least three tests ofbiggest, which all pass, and at least one of which fails whenbiggestis swapped forbad_biggest. (scoreandwith_bug, written for you, check that.)