🐍 Python for Everyone

← Back to the quiz

Chapter 27 Exercises 40 min, hands-on

Exercises: Testing Your Code

How to run these Download starter.py below, then run python3 starter.py from inside the folder you saved it in. It both defines your TODOs and runs the test suite immediately, so you'll see pass/fail output as soon as you run it — no separate test command required. Every task uses only the standard library (unittest, unittest.mock) — no installs needed.
Optional: running with pytest If you have pytest installed (pip install pytest), you can run the exact same test classes with pytest starter.py -v from inside this folder — pytest runs unittest.TestCase classes directly, no changes needed. It's a good way to compare pytest's output style against unittest's on identical code.

1 A function to test

Write add(a, b) — return a + b.

2 A function that raises

Write divide(a, b) — return a / b, but raise ValueError("Cannot divide by zero") if b == 0.

3 Your first TestCase

Write a unittest.TestCase class TestMathOps testing add() and that divide() raises ValueError on zero.

4 A fixture with setUp

Write TestCartFixture with a setUp(self) that builds a fresh empty cart before each test.

5 Code with an external dependency

Write get_username(user_id, db_client) — calls db_client.fetch_user(user_id) and returns its "username".

6 Mocking that dependency

Write TestGetUsername using unittest.mock.Mock() to fake the database client, with assert_called_once_with.

7 A function with edge cases

Write apply_late_fee(balance, days_late) — no fee unless days_late > 0.

8 Testing edge cases with AAA

Write TestLateFee with three Arrange/Act/Assert tests: no days late, some days late, and negative days late.

🐞 Task 9 — Debug the Code

This test is supposed to prove two calls to make_empty_cart() never share state, but it fails. Find and fix the bug — it could be in the function or the test.

buggy_make_empty_cart.py
def make_empty_cart(_shared_cart=[]):
    return _shared_cart


class TestMakeEmptyCart(unittest.TestCase):
    def test_two_calls_are_independent(self):
        cart_a = make_empty_cart()
        cart_a.append("apple")

        cart_b = make_empty_cart()

        self.assertEqual(cart_b, [])
← Back to Quiz Practice Bank →