python · level 3 · unit 6 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
The mail server goes down. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
from unittest.mock import Mock
def send_welcome(mailer, email):
try:
mailer.send(email, "Welcome!")
return "sent"
except ConnectionError:
return "will retry later"
mailer = Mock()
print(send_welcome(mailer, "ana@example.com"))
mailer.send.side_effect = ConnectionError("server down")
print(send_welcome(mailer, "ben@example.com"))
print(mailer.send.call_count)
your turn
Your turn. Load the dice for a test.
Inside the first block, make the dice always land on 6. Inside the second, make them land on any other number.
fix it
The fake payment service crashes. Fix it!
- The error says a string is not callable. What did line 8 turn
chargeinto? chargemust stay a mock that can be called. Set what the call hands back instead.- Change line 8 to
fake.charge.return_value = "R-77", then run.
nailed it
you can test code that talks to the world. :D
- A
Mockreturns what you set and records every call. assert_called_once_withchecks exactly how it was called.patchswaps a real name for a mock inside awithblock.
new words in your collection
- dependency
- mock
- patch
This lesson isn’t saved. A free account remembers every lesson you finish.