Specification for a function you don't need to write:
safe_average(nums)
Returns the average of nums as a float. If nums is empty, returns 0.0 — it must not raise an exception.
Your job: write a unittest.TestCase class, TestSafeAverage, with test methods test_typical and test_empty_list that verify this specification. Call safe_average directly.
Checked against a correct implementation (all should pass) and a buggy one that crashes on an empty list (at least one of your tests should fail).
import unittest
class TestSafeAverage(unittest.TestCase):
def test_typical(self):
self.assertEqual(safe_average([2, 4, 6]), 4.0)
def test_empty_list(self):
self.assertEqual(safe_average([]), 0.0)
This ties back to the very first thing this course taught about exceptions: a function that's supposed to handle a bad case gracefully (rather than let an exception propagate) needs a test that specifically exercises that case.
test_typical is table stakes — it confirms the basic averaging math works. But the specification's most important claim is about the edge case: an empty list should return 0.0, not crash. If the underlying implementation forgot to guard against that (going straight to sum(nums) / len(nums), which divides by zero when nums is empty), it would raise a ZeroDivisionError the moment test_empty_list calls safe_average([]) — and that uncaught exception inside your test method is treated as the test failing, exactly as it should.
Notice this mirrors the pattern from every problem in this section so far: the specification tells you where the interesting edge is ("if nums is empty... must not raise"), and a thorough test suite is one that specifically goes and checks that exact edge, rather than only testing the straightforward case.
import unittest
class TestSafeAverage(unittest.TestCase):
def test_typical(self):
self.assertEqual(safe_average([2, 4, 6]), 4.0)
def test_empty_list(self):
self.assertEqual(safe_average([]), 0.0)
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.