-
-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathtest_async.py
More file actions
557 lines (393 loc) · 16.7 KB
/
test_async.py
File metadata and controls
557 lines (393 loc) · 16.7 KB
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
import re
import pytest
from statemachine.exceptions import InvalidDefinition
from statemachine.exceptions import InvalidStateValue
from statemachine import State
from statemachine import StateChart
@pytest.fixture()
def async_order_control_machine(): # noqa: C901
class OrderControl(StateChart):
allow_event_without_transition = False
waiting_for_payment = State(initial=True)
processing = State()
shipping = State()
completed = State(final=True)
add_to_order = waiting_for_payment.to(waiting_for_payment)
receive_payment = waiting_for_payment.to(
processing, cond="payments_enough"
) | waiting_for_payment.to(waiting_for_payment, unless="payments_enough")
process_order = processing.to(shipping, cond="payment_received")
ship_order = shipping.to(completed)
def __init__(self):
self.order_total = 0
self.payments = []
self.payment_received = False
super().__init__()
async def payments_enough(self, amount):
return sum(self.payments) + amount >= self.order_total
async def before_add_to_order(self, amount):
self.order_total += amount
return self.order_total
async def before_receive_payment(self, amount):
self.payments.append(amount)
return self.payments
async def after_receive_payment(self):
self.payment_received = True
async def on_enter_waiting_for_payment(self):
self.payment_received = False
return OrderControl
async def test_async_order_control_machine(async_order_control_machine):
sm = async_order_control_machine()
assert await sm.add_to_order(3) == 3
assert await sm.add_to_order(7) == 10
assert await sm.receive_payment(4) == [4]
assert sm.waiting_for_payment.is_active
with pytest.raises(sm.TransitionNotAllowed):
await sm.process_order()
assert sm.waiting_for_payment.is_active
assert await sm.receive_payment(6) == [4, 6]
await sm.process_order()
await sm.ship_order()
assert sm.order_total == 10
assert sm.payments == [4, 6]
assert sm.completed.is_active
def test_async_state_from_sync_context(async_order_control_machine):
"""Test that an async state machine can be used from a synchronous context"""
sm = async_order_control_machine()
assert sm.add_to_order(3) == 3
assert sm.add_to_order(7) == 10
assert sm.receive_payment(4) == [4]
assert sm.waiting_for_payment.is_active
with pytest.raises(sm.TransitionNotAllowed):
sm.process_order()
assert sm.waiting_for_payment.is_active
assert sm.send("receive_payment", 6) == [4, 6] # test the sync version of the `.send()` method
sm.send("process_order") # test the sync version of the `.send()` method
sm.ship_order()
assert sm.order_total == 10
assert sm.payments == [4, 6]
assert sm.completed.is_active
class AsyncConditionExpressionMachine(StateChart):
"""Regression test for issue #535: async conditions in boolean expressions."""
allow_event_without_transition = False
s1 = State(initial=True)
go_not = s1.to.itself(cond="not cond_false")
go_and = s1.to.itself(cond="cond_true and cond_true")
go_or_false_first = s1.to.itself(cond="cond_false or cond_true")
go_or_true_first = s1.to.itself(cond="cond_true or cond_false")
go_blocked = s1.to.itself(cond="not cond_true")
go_and_blocked = s1.to.itself(cond="cond_true and cond_false")
go_or_both_false = s1.to.itself(cond="cond_false or cond_false")
async def cond_true(self):
return True
async def cond_false(self):
return False
async def on_enter_state(self, target):
"""Async callback to ensure the SM uses AsyncEngine."""
async def test_async_condition_not(recwarn):
"""Issue #535: 'not cond_false' should allow the transition."""
sm = AsyncConditionExpressionMachine()
await sm.activate_initial_state()
await sm.go_not()
assert sm.s1.is_active
assert not any("coroutine" in str(w.message) for w in recwarn.list)
async def test_async_condition_not_blocked():
"""Issue #535: 'not cond_true' should block the transition."""
sm = AsyncConditionExpressionMachine()
await sm.activate_initial_state()
with pytest.raises(sm.TransitionNotAllowed):
await sm.go_blocked()
async def test_async_condition_and():
"""Issue #535: 'cond_true and cond_true' should allow the transition."""
sm = AsyncConditionExpressionMachine()
await sm.activate_initial_state()
await sm.go_and()
assert sm.s1.is_active
async def test_async_condition_and_blocked():
"""Issue #535: 'cond_true and cond_false' should block the transition."""
sm = AsyncConditionExpressionMachine()
await sm.activate_initial_state()
with pytest.raises(sm.TransitionNotAllowed):
await sm.go_and_blocked()
async def test_async_condition_or_false_first():
"""Issue #535: 'cond_false or cond_true' should allow the transition."""
sm = AsyncConditionExpressionMachine()
await sm.activate_initial_state()
await sm.go_or_false_first()
assert sm.s1.is_active
async def test_async_condition_or_true_first():
"""'cond_true or cond_false' should allow the transition."""
sm = AsyncConditionExpressionMachine()
await sm.activate_initial_state()
await sm.go_or_true_first()
assert sm.s1.is_active
async def test_async_condition_or_both_false():
"""'cond_false or cond_false' should block the transition."""
sm = AsyncConditionExpressionMachine()
await sm.activate_initial_state()
with pytest.raises(sm.TransitionNotAllowed):
await sm.go_or_both_false()
async def test_async_state_should_be_initialized(async_order_control_machine):
"""Test that the state machine is initialized before any event is triggered
Given how async works on python, there's no built-in way to activate the initial state that
may depend on async code from the StateMachine.__init__ method.
We do a `_ensure_is_initialized()` check before each event, but to check the current state
just before the state machine is created, the user must await the activation of the initial
state explicitly.
"""
sm = async_order_control_machine()
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
with pytest.raises(
InvalidStateValue,
match=re.escape(
r"There's no current state set. In async code, "
r"did you activate the initial state? (e.g., `await sm.activate_initial_state()`)"
),
):
sm.current_state # noqa: B018
await sm.activate_initial_state()
assert sm.waiting_for_payment.is_active
@pytest.mark.timeout(5)
async def test_async_catch_errors_as_events_in_condition():
"""Async engine catches errors in conditions with catch_errors_as_events."""
class SM(StateChart):
s1 = State(initial=True)
s2 = State(final=True)
error_state = State(final=True)
go = s1.to(s2, cond="bad_cond")
error_execution = s1.to(error_state)
def bad_cond(self, **kwargs):
raise RuntimeError("Condition boom")
sm = SM()
sm.send("go")
assert sm.configuration == {sm.error_state}
@pytest.mark.timeout(5)
async def test_async_catch_errors_as_events_in_transition():
"""Async engine catches errors in transition callbacks with catch_errors_as_events."""
class SM(StateChart):
s1 = State(initial=True)
s2 = State()
error_state = State(final=True)
go = s1.to(s2, on="bad_action")
finish = s2.to(error_state)
# Transition 'on' content error is caught per-block, so the transition
# completes to s2. error.execution fires from s2.
error_execution = s1.to(error_state) | s2.to(error_state)
def bad_action(self, **kwargs):
raise RuntimeError("Transition boom")
sm = SM()
sm.send("go")
assert sm.configuration == {sm.error_state}
@pytest.mark.timeout(5)
async def test_async_catch_errors_as_events_in_after():
"""Async engine catches errors in after callbacks with catch_errors_as_events."""
class SM(StateChart):
s1 = State(initial=True)
s2 = State()
error_state = State(final=True)
go = s1.to(s2)
error_execution = s2.to(error_state)
def after_go(self, **kwargs):
raise RuntimeError("After boom")
sm = SM()
sm.send("go")
assert sm.configuration == {sm.error_state}
@pytest.mark.timeout(5)
async def test_async_catch_errors_as_events_in_before():
"""Async engine catches errors in before callbacks with catch_errors_as_events."""
class SM(StateChart):
s1 = State(initial=True)
error_state = State(final=True)
go = s1.to(s1)
error_execution = s1.to(error_state)
def before_go(self, **kwargs):
raise RuntimeError("Before boom")
async def on_enter_state(self, **kwargs):
"""Async callback to force the async engine."""
sm = SM()
await sm.activate_initial_state()
await sm.go()
assert sm.configuration == {sm.error_state}
@pytest.mark.timeout(5)
async def test_async_invalid_definition_in_transition_propagates():
"""InvalidDefinition in async transition propagates."""
class SM(StateChart):
s1 = State(initial=True)
s2 = State(final=True)
go = s1.to(s2, on="bad_action")
def bad_action(self, **kwargs):
raise InvalidDefinition("Bad async")
sm = SM()
with pytest.raises(InvalidDefinition, match="Bad async"):
sm.send("go")
@pytest.mark.timeout(5)
async def test_async_invalid_definition_in_after_propagates():
"""InvalidDefinition in async after callback propagates."""
class SM(StateChart):
s1 = State(initial=True)
s2 = State(final=True)
go = s1.to(s2)
def after_go(self, **kwargs):
raise InvalidDefinition("Bad async after")
sm = SM()
with pytest.raises(InvalidDefinition, match="Bad async after"):
sm.send("go")
@pytest.mark.timeout(5)
async def test_async_runtime_error_in_after_without_catch_errors_as_events():
"""RuntimeError in async after callback without catch_errors_as_events propagates."""
class SM(StateChart):
catch_errors_as_events = False
s1 = State(initial=True)
s2 = State(final=True)
go = s1.to(s2)
def after_go(self, **kwargs):
raise RuntimeError("Async after boom")
sm = SM()
with pytest.raises(RuntimeError, match="Async after boom"):
sm.send("go")
# --- Actual async engine tests (async callbacks trigger AsyncEngine) ---
# Note: async engine catch_errors_as_events with async callbacks has a known limitation:
# _send_error_execution calls sm.send() which returns an unawaited coroutine.
# The tests below cover the paths that DO work in the async engine.
@pytest.mark.timeout(5)
async def test_async_engine_invalid_definition_in_condition_propagates():
"""AsyncEngine: InvalidDefinition in async condition always propagates."""
class SM(StateChart):
s1 = State(initial=True)
s2 = State(final=True)
go = s1.to(s2, cond="bad_cond")
async def bad_cond(self, **kwargs):
raise InvalidDefinition("Async bad definition")
sm = SM()
await sm.activate_initial_state()
with pytest.raises(InvalidDefinition, match="Async bad definition"):
await sm.send("go")
@pytest.mark.timeout(5)
async def test_async_engine_invalid_definition_in_transition_propagates():
"""AsyncEngine: InvalidDefinition in async transition execution always propagates."""
class SM(StateChart):
s1 = State(initial=True)
s2 = State(final=True)
go = s1.to(s2, on="bad_action")
async def bad_action(self, **kwargs):
raise InvalidDefinition("Async bad transition")
sm = SM()
await sm.activate_initial_state()
with pytest.raises(InvalidDefinition, match="Async bad transition"):
await sm.send("go")
@pytest.mark.timeout(5)
async def test_async_engine_invalid_definition_in_after_propagates():
"""AsyncEngine: InvalidDefinition in async after callback propagates."""
class SM(StateChart):
s1 = State(initial=True)
s2 = State(final=True)
go = s1.to(s2)
async def after_go(self, **kwargs):
raise InvalidDefinition("Async bad after")
sm = SM()
await sm.activate_initial_state()
with pytest.raises(InvalidDefinition, match="Async bad after"):
await sm.send("go")
@pytest.mark.timeout(5)
async def test_async_engine_runtime_error_in_after_without_catch_errors_as_events_propagates():
"""AsyncEngine: RuntimeError in async after callback without catch_errors_as_events raises."""
class SM(StateChart):
catch_errors_as_events = False
s1 = State(initial=True)
s2 = State(final=True)
go = s1.to(s2)
async def after_go(self, **kwargs):
raise RuntimeError("Async after boom no catch")
sm = SM()
await sm.activate_initial_state()
with pytest.raises(RuntimeError, match="Async after boom no catch"):
await sm.send("go")
@pytest.mark.timeout(5)
async def test_async_engine_start_noop_when_already_initialized():
"""BaseEngine.start() is a no-op when state machine is already initialized."""
class SM(StateChart):
s1 = State(initial=True)
s2 = State(final=True)
go = s1.to(s2)
async def on_go(
self,
): ... # No-op: presence of async callback triggers AsyncEngine selection
sm = SM()
await sm.activate_initial_state()
assert sm.current_state_value is not None
sm._engine.start() # Should return early
assert sm.s1.is_active
class TestAsyncEnabledEvents:
async def test_passing_async_condition(self):
class MyMachine(StateChart):
s0 = State(initial=True)
s1 = State(final=True)
go = s0.to(s1, cond="is_ready")
async def is_ready(self):
return True
sm = MyMachine()
await sm.activate_initial_state()
assert [e.id for e in await sm.enabled_events()] == ["go"]
async def test_failing_async_condition(self):
class MyMachine(StateChart):
s0 = State(initial=True)
s1 = State(final=True)
go = s0.to(s1, cond="is_ready")
async def is_ready(self):
return False
sm = MyMachine()
await sm.activate_initial_state()
assert await sm.enabled_events() == []
async def test_kwargs_forwarded_to_async_conditions(self):
class MyMachine(StateChart):
s0 = State(initial=True)
s1 = State(final=True)
go = s0.to(s1, cond="check_value")
async def check_value(self, value=0):
return value > 10
sm = MyMachine()
await sm.activate_initial_state()
assert await sm.enabled_events() == []
assert [e.id for e in await sm.enabled_events(value=20)] == ["go"]
async def test_async_condition_exception_treated_as_enabled(self):
class MyMachine(StateChart):
s0 = State(initial=True)
s1 = State(final=True)
go = s0.to(s1, cond="bad_cond")
async def bad_cond(self):
raise RuntimeError("boom")
sm = MyMachine()
await sm.activate_initial_state()
assert [e.id for e in await sm.enabled_events()] == ["go"]
async def test_duplicate_event_across_transitions_deduplicated(self):
"""Same event on multiple passing transitions appears only once."""
class MyMachine(StateChart):
s0 = State(initial=True)
s1 = State(final=True)
s2 = State(final=True)
go = s0.to(s1, cond="cond_a") | s0.to(s2, cond="cond_b")
async def cond_a(self):
return True
async def cond_b(self):
return True
sm = MyMachine()
await sm.activate_initial_state()
ids = [e.id for e in await sm.enabled_events()]
assert ids == ["go"]
assert len(ids) == 1
async def test_mixed_enabled_and_disabled_async(self):
class MyMachine(StateChart):
s0 = State(initial=True)
s1 = State(final=True)
s2 = State(final=True)
go = s0.to(s1, cond="cond_true")
stop = s0.to(s2, cond="cond_false")
async def cond_true(self):
return True
async def cond_false(self):
return False
sm = MyMachine()
await sm.activate_initial_state()
assert [e.id for e in await sm.enabled_events()] == ["go"]