Skip to content

Instantly share code, notes, and snippets.

@cdunklau
Last active February 9, 2017 10:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdunklau/c25f6fa291fd8b88f0f3aee386226f42 to your computer and use it in GitHub Desktop.
Save cdunklau/c25f6fa291fd8b88f0f3aee386226f42 to your computer and use it in GitHub Desktop.
Dependancy injection demonstration for making random stuff deterministic
import random
def default_diceroller():
return random.randint(1, 6)
class CrapsGame(object):
_diceroller = default_diceroller
def __init__(self, nplayers):
self.nplayers = nplayers
def roll(self):
return self._diceroller(), self._diceroller()
from dicegames import CrapsGame
def make_deterministic_diceroller(outputs):
outputs_iter = iter(outputs)
def diceroller():
roll = next(outputs_iter, None)
if roll is None:
raise AssertionError('Dice roller expended unexpectedly')
return roll
return diceroller
def test_craps_game():
game = CrapsGame(5)
game._diceroller = make_deterministic_diceroller([1, 2, 3])
assert game.roll() == (1, 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment