Testing Python code
Test boundaries and errors
Check invalid inputs and threshold values.
Lesson 46 of 63
Reading: about 2 min
Lesson + practice: about 16 min
Difficulty: Intermediate
On this page5 sections
Tests should cover values at and around a rule boundary. Use assertRaises for expected exceptions. Exact integer checks reject Boolean values when they are not valid counts.
Worked example
import unittest
def minutes(value):
if type(value) is not int or value <= 0:
raise ValueError("positive integer required")
return value
case = unittest.TestCase()
case.assertEqual(minutes(1), 1)
for bad in (0, -1, True, "2"):
with case.assertRaises(ValueError):
minutes(bad)
print("five cases passed")five cases passed
Why this works
One is the smallest valid value; zero and negative values violate the range; True and text violate the exact-type rule.
Another case
import unittest
case = unittest.TestCase()
with case.assertRaises(ValueError):
int("five")
print("error checked")error checked
Practice
Add 1.5 to the invalid cases. Why should this validator reject it?
Check the practice result
Reveal answer
1.5 is a float, not an exact int, so the function raises ValueError.
Try another case
Why test both 1 and 0 rather than only a typical value such as 25?
Check your answer
Reveal answer
1 is the smallest valid value and 0 the first invalid one. Testing both sides of the boundary catches mistakes such as writing < instead of <=.
Your progress
Reveal the check answer or reach the end to complete this lesson.