Last active
February 9, 2017 10:22
-
-
Save cdunklau/c25f6fa291fd8b88f0f3aee386226f42 to your computer and use it in GitHub Desktop.
Dependancy injection demonstration for making random stuff deterministic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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