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 did from random import randint, you'd patch that module's own randint name instead.

Assignment

Finish the two tests (plain assert-style test functions):

  1. test_warn_dark: check that warn_dark returns 1 and that notifier.send was called exactly once with "Reef is dark!".
  2. test_roll_storm: patch random.randint to return 6 and assert the result is "storm"; then patch it to return 1 and assert "calm".