-
Notifications
You must be signed in to change notification settings - Fork 4
/
test_observer.py
73 lines (55 loc) · 1.83 KB
/
test_observer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from unittest import TestCase
class Event(list):
def __call__(self, *args, **kwargs):
for item in self:
item(*args, **kwargs)
class Game:
def __init__(self):
self.rat_enters = Event()
self.rat_dies = Event()
self.notify_rat = Event()
class Rat:
def __init__(self, game):
self.game = game
self.attack = 1
game.rat_enters.append(self.rat_enters)
game.notify_rat.append(self.notify_rat)
game.rat_dies.append(self.rat_dies)
self.game.rat_enters(self)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.game.rat_dies(self)
def rat_enters(self, which_rat):
if which_rat != self:
self.attack += 1
self.game.notify_rat(which_rat)
def notify_rat(self, which_rat):
if which_rat == self:
self.attack += 1
def rat_dies(self, which_rat):
self.attack -= 1
class Evaluate(TestCase):
def test_single_rat(self):
game = Game()
rat = Rat(game)
self.assertEqual(1, rat.attack)
def test_two_rats(self):
game = Game()
rat = Rat(game)
rat2 = Rat(game)
self.assertEqual(2, rat.attack)
self.assertEqual(2, rat2.attack)
def test_three_rats_one_dies(self):
game = Game()
rat = Rat(game)
self.assertEqual(1, rat.attack)
rat2 = Rat(game)
self.assertEqual(2, rat.attack)
self.assertEqual(2, rat2.attack)
with Rat(game) as rat3:
self.assertEqual(3, rat.attack)
self.assertEqual(3, rat2.attack)
self.assertEqual(3, rat3.attack)
self.assertEqual(2, rat.attack)
self.assertEqual(2, rat2.attack)