-
Notifications
You must be signed in to change notification settings - Fork 2
/
test_statmach.py
338 lines (279 loc) · 11.9 KB
/
test_statmach.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
"""Test code and examples for ``statmach``."""
import enum
from time import time
import pytest
from statmach import State, Machine
import statmach
__author__ = statmach.__author__
__copyright__ = statmach.__copyright__
__license__ = statmach.__license__
__repository__ = statmach.__repository__
__description__ = "Test code and examples for ``statmach``."
__version__ = "1.0.10" # Version set by https://github.com/hlovatt/tag2ver
log = []
class LoggingState(State):
def __init__(self, *, ident, enter_throws=False, exit_throws=False):
super().__init__(ident=ident)
self.enter_throws = enter_throws
self.exit_throws = exit_throws
def __enter__(self):
log.append(f'Enter state {self.ident}')
if self.enter_throws:
assert False, f'Enter state {self.ident} throw'
return self
def __exit__(self, exc_type, exc_val, exc_tb):
log.append(f'Exit state {self.ident}')
if self.exit_throws:
assert False, f'Exit state {self.ident} throw'
return False
class LoggingMachine(Machine):
def __init__(self, *, initial_state, enter_throws=False, exit_throws=False):
super().__init__(initial_state=initial_state)
self.enter_throws = enter_throws
self.exit_throws = exit_throws
def __enter__(self):
log.append(f'Enter machine')
if self.enter_throws:
assert False, f'Enter machine throw'
return self
def __exit__(self, exc_type, exc_val, exc_tb):
try:
_ = super().__exit__(None, None, None) # Exception from super `__exit__` is propagated (do not catch).
finally:
log.append(f'Exit machine')
if self.exit_throws:
assert False, f'Exit machine throw'
return False
# noinspection PyTypeChecker
class Test_statmach:
# noinspection PyMethodMayBeStatic
def setup_method(self):
global log
log.clear()
def test_minimal_sm_that_does_nothing(self):
Events = enum.Enum('Events', 'MACHINE STATE')
s0 = State()
s0.actions[Events.STATE] = s0, None
with Machine(initial_state=s0) as machine:
machine.actions[Events.MACHINE] = s0, None
assert machine.state is s0
assert machine.fire(Events.MACHINE) is None
assert machine.state is s0
assert machine.fire(Events.STATE) is None
assert machine.state is s0
def test_edge_detector(self):
"""
https://en.wikipedia.org/wiki/Mealy_machine
.. image:: media/EdgeDetectorStateDiagram.png
:alt: Edge Detector State Diagram
:width: 864px
:height: 720px
"""
Bit = enum.Enum('Bit', 'ZERO ONE') # 1. & 2. Define the inputs (in this case also the outputs).
s_i = State(ident='i') # 3. Define the states.
s_0 = State(ident=0)
s_1 = State(ident=1)
s_i.actions = {Bit.ZERO: (s_0, Bit.ZERO), Bit.ONE: (s_1, Bit.ZERO)} # 4. Define the actions.
s_0.actions = {Bit.ZERO: (s_0, Bit.ZERO), Bit.ONE: (s_1, Bit.ONE)}
s_1.actions = {Bit.ZERO: (s_0, Bit.ONE), Bit.ONE: (s_1, Bit.ZERO)}
with Machine(initial_state=s_i) as machine: # 5. Define the machine.
assert machine.state is s_i
assert machine.fire(Bit.ZERO) is Bit.ZERO # 6. Fire events and obtain outputs.
assert machine.state is s_0
assert machine.fire(Bit.ZERO) is Bit.ZERO
assert machine.state is s_0
assert machine.fire(Bit.ONE) is Bit.ONE
assert machine.state is s_1
assert machine.fire(Bit.ONE) is Bit.ZERO
assert machine.state is s_1
assert machine.fire(Bit.ZERO) is Bit.ONE
assert machine.state is s_0
# noinspection PyArgumentList
def test_traffic_lights(self):
"""
.. image:: media/TrafficLightStateDiagram.png
"""
class Inputs(enum.Enum): # 1. The inputs.
RED_TIMEOUT = enum.auto()
AMBER_TIMEOUT = enum.auto()
GREEN_TIMEOUT = enum.auto()
ERROR = enum.auto()
class Outputs(enum.Enum): # 2. The outputs.
RED = enum.auto()
AMBER = enum.auto()
GREEN = enum.auto()
FLASHING_RED = enum.auto()
flashing_red = State(ident='flashing_red', value=Outputs.FLASHING_RED) # 3. The states.
red = State(ident='red', value=Outputs.RED)
amber = State(ident='amber', value=Outputs.AMBER)
green = State(ident='green', value=Outputs.GREEN)
red.actions[Inputs.RED_TIMEOUT] = green.action # 4a. The *state* actions.
green.actions[Inputs.GREEN_TIMEOUT] = amber.action
amber.actions[Inputs.AMBER_TIMEOUT] = red.action
with Machine(initial_state=red) as machine: # 5. The machine.
machine.actions[Inputs.RED_TIMEOUT] = flashing_red.action # 4b. The *machine* actions.
machine.actions[Inputs.AMBER_TIMEOUT] = flashing_red.action
machine.actions[Inputs.GREEN_TIMEOUT] = flashing_red.action
machine.actions[Inputs.ERROR] = flashing_red.action
assert machine.state is red
assert machine.fire(Inputs.RED_TIMEOUT) is Outputs.GREEN # 6. Fire events and obtain outputs.
assert machine.state is green
assert machine.fire(Inputs.GREEN_TIMEOUT) is Outputs.AMBER
assert machine.state is amber
assert machine.fire(Inputs.AMBER_TIMEOUT) is Outputs.RED
assert machine.state is red
assert machine.fire(Inputs.AMBER_TIMEOUT) is Outputs.FLASHING_RED
assert machine.state is flashing_red
assert machine.fire(Inputs.ERROR) is Outputs.FLASHING_RED
assert machine.state is flashing_red
def test_state_active_time(self):
class StateTime(State):
def __init__(self):
super().__init__(value=self.state_active_time) # Value is a function.
self._enter_time = None
def state_active_time(self):
return time() - self._enter_time
def __enter__(self):
self._enter_time = time()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self._enter_time = None
return False
state_active_time = 1
s = StateTime()
s.actions[state_active_time] = s.action
with Machine(initial_state=s) as m:
assert m.fire(state_active_time)() >= 0 # Value is a function which is called, 2nd `()`.
def test_transitioning_between_states_and_enter_and_exit_overrides(self):
Events = enum.Enum('Events', 'MACHINE_TO_STATE_0 STATE_TO_STATE_1')
states = [LoggingState(ident=0), LoggingState(ident=1)]
states[0].actions[Events.STATE_TO_STATE_1] = states[1], None
states[1].actions[Events.STATE_TO_STATE_1] = states[1], None
with LoggingMachine(initial_state=states[0]) as machine:
machine.actions[Events.MACHINE_TO_STATE_0] = states[0], None
assert machine.state is states[0]
assert machine.fire(Events.MACHINE_TO_STATE_0) is None
assert machine.state is states[0]
assert machine.fire(Events.STATE_TO_STATE_1) is None
assert machine.state is states[1]
assert machine.fire(Events.STATE_TO_STATE_1) is None
assert machine.state is states[1]
assert machine.fire(Events.MACHINE_TO_STATE_0) is None
assert machine.state is states[0]
assert log == [
'Enter machine',
'Enter state 0',
'Exit state 0',
'Enter state 1',
'Exit state 1',
'Enter state 0',
'Exit state 0',
'Exit machine',
]
def test_that_unhandled_event_gets_raised(self):
Events = enum.Enum('Events', 'UNHANDLED')
state0 = State()
with pytest.raises(KeyError):
with Machine(initial_state=state0) as machine:
assert machine.state is state0
machine.fire(Events.UNHANDLED)
def test_that_exception_can_be_suppressed(self):
Events = enum.Enum('Events', 'UNHANDLED')
class SuppressAllExceptions(State):
def __exit__(self, exc_type, exc_val, exc_tb):
return True # Suppress the exception.
state0 = SuppressAllExceptions()
with Machine(initial_state=state0) as machine:
assert machine.state is state0
assert machine.fire(Events.UNHANDLED) is None
assert machine.state is state0
def test_not_entering_initial_state_if_no_event(self):
s0 = LoggingState(ident=0)
with LoggingMachine(initial_state=s0):
pass
assert log == [
'Enter machine',
'Exit machine',
]
def test_nesting_order(self):
s0 = LoggingState(ident=0)
with LoggingMachine(initial_state=s0) as m:
m.actions[1] = s0, None
m.fire(1)
assert log == [
'Enter machine',
'Enter state 0',
'Exit state 0',
'Exit machine',
]
def test_machine_enter_throwing(self):
s0 = LoggingState(ident=0, enter_throws=True)
with pytest.raises(AssertionError, match='Enter machine throw'):
with LoggingMachine(initial_state=s0, enter_throws=True) as m:
m.actions[1] = s0, None
m.fire(1)
assert log == [
'Enter machine',
]
def test_state_enter_throwing(self):
s0 = LoggingState(ident=0, enter_throws=True)
with pytest.raises(AssertionError, match='Enter state 0 throw'):
with LoggingMachine(initial_state=s0) as m:
m.actions[1] = s0, None
m.fire(1)
assert log == [
'Enter machine',
'Enter state 0',
'Exit state 0',
'Exit machine',
]
def test_machine_exit_throwing(self):
s0 = LoggingState(ident=0)
with pytest.raises(AssertionError, match='Exit machine throw'):
with LoggingMachine(initial_state=s0, exit_throws=True) as m:
m.actions[1] = s0, None
m.fire(1)
assert log == [
'Enter machine',
'Enter state 0',
'Exit state 0',
'Exit machine',
]
def test_state_exit_throwing(self):
s0 = LoggingState(ident=0, exit_throws=True)
with pytest.raises(AssertionError, match='Exit state 0 throw'):
with LoggingMachine(initial_state=s0) as m:
m.actions[1] = s0, None
m.fire(1)
assert log == [
'Enter machine',
'Enter state 0',
'Exit state 0',
'Exit machine',
]
def test_machine_and_state_exit_throwing(self):
s0 = LoggingState(ident=0, exit_throws=True)
# State exit throw swallowed because machine exit also throws.
with pytest.raises(AssertionError, match='Exit machine throw'):
with LoggingMachine(initial_state=s0, exit_throws=True) as m:
m.actions[1] = s0, None
m.fire(1)
assert log == [
'Enter machine',
'Enter state 0',
'Exit state 0',
'Exit machine',
]
def test_new_state_handles_less_events(self):
Events = enum.Enum('Events', 's0 s1')
s0 = State()
s1 = State()
s0.actions = {Events.s0: s0.action, Events.s1: s1.action}
s1.actions = {Events.s0: s0.action} # Missing `s1`.
with pytest.raises(AssertionError, match=(
'Set of current events handled, {<Events.s0: 1>, <Events.s1: 2>},'
' not the same as set of new events, {<Events.s0: 1>}'
)
):
with Machine(initial_state=s0) as m:
m.fire(Events.s1)