Skip to content
Foxipa
Code Completion 4 Challenges

Complete the Python unittest code

Practise writing test methods, checking expected exceptions, creating independent fixtures, and using subtests.

Intermediate ~12 min read

Challenge 1

Complete the test method so it checks the rectangle-area result against the expected value.

python Your answer
import unittest

def rectangle_area(width, height):
    return width * height

class TestRectangleArea(unittest.TestCase):
    

if __name__ == "__main__":
    unittest.main(argv=["exercise"], exit=False)

Press Ctrl⌘Enter to check your answer

Challenge 2

Write a test that verifies safe_divide rejects a zero denominator with ZeroDivisionError.

python Your answer
import unittest

def safe_divide(numerator, denominator):
    if denominator == 0:
        raise ZeroDivisionError("denominator cannot be zero")
    return numerator / denominator

class TestSafeDivide(unittest.TestCase):
    

if __name__ == "__main__":
    unittest.main(argv=["exercise"], exit=False)

Press Ctrl⌘Enter to check your answer

Challenge 3

Create a fresh item list before each cart test. The following methods expect self.items to exist.

python Your answer
import unittest

class TestCart(unittest.TestCase):
        def test_add_item(self):
        self.items.append("pear")
        self.assertEqual(self.items, ["pear"])

    def test_starts_empty(self):
        self.assertEqual(self.items, [])

if __name__ == "__main__":
    unittest.main(argv=["exercise"], exit=False)

Press Ctrl⌘Enter to check your answer

Challenge 4

Use a subTest context so failures identify the score being checked.

python Your answer
import unittest

def is_passing(score):
    return score >= 60

class TestPassingScore(unittest.TestCase):
    def test_boundaries(self):
        cases = [(59, False), (60, True), (100, True)]
        for score, expected in cases:
            

if __name__ == "__main__":
    unittest.main(argv=["exercise"], exit=False)

Press Ctrl⌘Enter to check your answer