
Code
Stunt Doubles
Some code talks to things you don't want in a test: sending messages, randomness, the clock, the network. A mock is a stunt double that stands in and records how it was used.
from unittest.mock import Mock
bell = Mock()
bell.ring("loud") # any method works!
bell.ring.assert_called_once_with("loud")
print(bell.ring.call_count) # 1
bell.size.return_value = 3 # program an answer
print(bell.size()) # 3
patch: swap something temporarily
patch swaps in a fake while a with block runs. Afterwards it
puts the original back:
from unittest.mock import patch
import random
with patch("random.randint", return_value=6):
print(random.randint(1, 6)) # always 6 in here
Pip tip: Patch the name where it is looked up. Our code calls
random.randint(...), so patching"random.randint"works. If a module didfrom random import randint, you'd patch that module's ownrandintname instead.
Assignment
Finish the two tests (plain assert-style test functions):
test_warn_dark: check thatwarn_darkreturns1and thatnotifier.sendwas called exactly once with"Reef is dark!".test_roll_storm: patchrandom.randintto return6and assert the result is"storm"; then patch it to return1and assert"calm".
Finish the two tests (plain assert-style test functions):
test_warn_dark: check thatwarn_darkreturns1and thatnotifier.sendwas called exactly once with"Reef is dark!".test_roll_storm: patchrandom.randintto return6and assert the result is"storm"; then patch it to return1and assert"calm".
main.py Python sleeping
Press Run to try your code, then Check to test it.