×

python · level 3 · unit 6 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A stands in for things your tests should not touch.

Some code relies on a you cannot use in a test: a payment service, an email server, a dice roll. A mock from unittest.mock stands in for it. It accepts any call, returns whatever you set as its return_value, and records how it was called.

Afterwards, ask it questions: assert_called_once_with(505) raises an error unless that exact call happened once. Set side_effect to an error and the mock raises it, so you can test the unhappy path too.

swaps a real name for a mock inside a with block.

from unittest.mock import Mock

def checkout(basket, payments):
    total = sum(basket.values())
    receipt = payments.charge(total)
    return f"Paid {total}, receipt {receipt}"

fake = Mock()
fake.charge.return_value = "R-1001"
print(checkout({"tea": 180, "cake": 325}, fake))
fake.charge.assert_called_once_with(505)
print(fake.charge.call_count)

checkout is handed its payment service as an argument, which is what lets a test swap in a mock.