Testing Python code
Project: test a study summary
Test totals, empty data, and invalid durations.
Lesson 48 of 63
Reading: about 2 min
Lesson + practice: about 20 min
Difficulty: Intermediate
On this page5 sections
Implement a small summary function and exercise its normal and invalid cases. Keep each test input independent so failures identify a specific rule.
Worked example
import unittest
def summarize(values):
if any(type(value) is not int or value <= 0 for value in values):
raise ValueError("positive integers required")
return {"sessions": len(values), "minutes": sum(values)}
class SummaryTests(unittest.TestCase):
def test_regular(self):
self.assertEqual(summarize([20, 25]), {"sessions": 2, "minutes": 45})
def test_empty(self):
self.assertEqual(summarize([]), {"sessions": 0, "minutes": 0})
def test_invalid(self):
with self.assertRaises(ValueError):
summarize([20, True])
if __name__ == "__main__":
unittest.main()... ---------------------------------------------------------------------- Ran 3 tests in 0.000s OK
Why this works
The function checks every duration before computing. An empty list is valid here and yields zero totals. Tests express these intended rules explicitly.
Another case
print(sum([]), len([]))0 0
Practice
Add a test for [-1] and a test for [1].
Check the practice result
Reveal answer
[-1] should raise ValueError; [1] should return one session and one minute.
Try another case
What should summarize([0]) do, and how would you test it?
Check your answer
Reveal answer
It should raise ValueError because 0 is not positive. Add a test that calls it inside self.assertRaises(ValueError).
Your progress
Reveal the check answer or reach the end to complete this lesson.