forked from opsani/statesman
-
Notifications
You must be signed in to change notification settings - Fork 0
/
statesman_test.py
1411 lines (1193 loc) · 62.5 KB
/
statesman_test.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
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import builtins
import contextlib
import datetime
from typing import Any, Dict, Iterator, List, Optional
import devtools
import pydantic
import pytest
import statesman
builtins.debug = devtools.debug
class TestBaseModel:
@pytest.fixture()
def model(self) -> statesman.BaseModel:
return statesman.BaseModel()
@pytest.fixture()
def actions(self) -> List[statesman.Action]:
return [
statesman.Action(callable=lambda: 1234, type=statesman.Action.Types.entry),
statesman.Action(callable=lambda: 1234, type=statesman.Action.Types.after),
statesman.Action(callable=lambda: 1234, type=None),
statesman.Action(callable=lambda: 5678, type=statesman.Action.Types.after),
statesman.Action(callable=lambda: 'whatever'),
]
def test_add_action(self, model: statesman.BaseModel) -> None:
assert model._actions == []
action = statesman.Action(callable=lambda: 1234, type=statesman.Action.Types.entry)
model._add_action(action)
assert model._actions == [action]
def test_remove_action(self, model: statesman.BaseModel) -> None:
assert model._actions == []
action = statesman.Action(callable=lambda: 1234, type=statesman.Action.Types.entry)
model._add_action(action)
assert model._actions == [action]
model._remove_action(action)
assert model._actions == []
class TestCollection:
@pytest.fixture()
def model(self, actions: List[statesman.Action]) -> statesman.BaseModel:
model = statesman.BaseModel()
model._actions = actions.copy()
return model
def test_by_object(self, model: statesman.BaseModel, actions: List[statesman.Action]) -> None:
assert model._actions == actions
action = actions[4]
model._remove_actions([action])
assert model._actions == actions[0:4]
def test_none(self, model: statesman.BaseModel, actions: List[statesman.Action]) -> None:
assert model._actions == actions
model._remove_actions()
assert model._actions == []
def test_type(self, model: statesman.BaseModel, actions: List[statesman.Action]) -> None:
assert model._actions == actions
model._remove_actions(statesman.Action.Types.entry)
assert model._actions == actions[1:5]
def test_get_actions(self, model: statesman.BaseModel, actions: List[statesman.Action]) -> None:
assert model._actions == actions
matched = model._get_actions(statesman.Action.Types.after)
assert matched == [actions[1], actions[3]]
class TestState:
class States(statesman.StateEnum):
first = 'First'
second = 'Second'
@pytest.fixture()
def state(self) -> statesman.State:
return statesman.State(name='Testing')
def test_add_action(self, state: statesman.State) -> None:
action = state.add_action(lambda: 1234, statesman.Action.Types.entry)
assert action
assert state.actions == [action]
def test_add_action_invalid_type(self, state: statesman.State) -> None:
with pytest.raises(ValueError, match='cannot add state action with type "Types.after": must be "Types.entry" or "Types.exit"'):
state.add_action(lambda: 1234, statesman.Action.Types.after)
@pytest.mark.parametrize(
('value', 'expected'),
[
(States.first, True),
('first', True),
('First', False),
(1234, False),
(None, False),
],
)
def test_equality(self, value: Any, expected: bool) -> None:
state = statesman.State(name=TestState.States.first)
assert (state == value) == expected
class TestListFrom:
def test_enum(self) -> None:
states = statesman.State.from_enum(States)
assert states
assert len(states) == 4
assert (states[0].name, states[0].description) == ('starting', 'Starting')
class TestAction:
def test_callable_is_required(self) -> None:
with pytest.raises(pydantic.ValidationError) as e:
statesman.Action()
assert e
assert '2 validation errors for Action' in str(e.value)
assert e.value.errors()[0]['loc'] == ('callable',)
assert (
e.value.errors()[0]['msg']
== 'field required'
)
def test_signature_is_hydrated(self) -> None:
def some_func(count: int, labels: Dict[str, str]) -> float:
...
action = statesman.Action(callable=some_func)
assert action.signature
assert repr(action.signature) == '<Signature (count: int, labels: Dict[str, str]) -> float>'
def test_types(self) -> None:
action = statesman.Action(callable=lambda: 1234, type=statesman.Action.Types.entry)
assert action.type == 'entry'
@pytest.mark.asyncio
async def test_call_action(self) -> None:
action = statesman.Action(callable=lambda: 1234)
@pytest.mark.asyncio
async def test_argument_matching(self) -> None:
# TODO: Test with and without *args and **kwargs
def action_body(count: int, another: bool = False, *args, something=None, number=1234) -> None:
...
# parametrize with a variations of args
# TODO: Test passing count as positional or keyword, another as keyword while count is positional
# TODO: Test signature with and without *args and **kwargs
action = statesman.Action(callable=action_body)
await action(1234)
class States(statesman.StateEnum):
starting = 'Starting'
running = 'Running'
stopping = 'Stopping'
stopped = 'Stopped'
class TestStateMachine:
@pytest.fixture()
def state_machine(self) -> statesman.StateMachine:
return statesman.StateMachine(states=statesman.State.from_enum(States))
@pytest.mark.asyncio
async def test_get_states_names(self, state_machine: statesman.StateMachine) -> None:
states = state_machine.get_states('starting', 'stopped')
assert len(states) == 2
assert list(map(lambda i: i.name, states)) == ['starting', 'stopped']
@pytest.mark.asyncio
async def test_get_states_by_state_enum(self, state_machine: statesman.StateMachine) -> None:
states = state_machine.get_states(States)
assert len(states) == 4
assert list(map(lambda i: i.name, states)) == ['starting', 'running', 'stopping', 'stopped']
@pytest.mark.asyncio
async def test_get_states_by_state_enum_list(self, state_machine: statesman.StateMachine) -> None:
states = state_machine.get_states(States.starting, States.running)
assert len(states) == 2
assert list(map(lambda i: i.name, states)) == ['starting', 'running']
def test_repr(self, state_machine: statesman.StateMachine) -> None:
assert repr(state_machine) == "StateMachine(states=[State(name='starting', description='Starting'), State(name='running', description='Running'), State(name='stopping', description='Stopping'), State(name='stopped', description='Stopped')], events=[], state=None)"
class TestTransition:
@pytest.fixture()
def transition(self) -> statesman.Transition:
state_machine = statesman.StateMachine()
state_machine.add_states(statesman.State.from_enum(States))
starting = state_machine.get_state(States.starting)
stopping = state_machine.get_state(States.stopping)
return statesman.Transition(state_machine=state_machine, source=starting, target=stopping)
@pytest.mark.asyncio
async def test_lifecycle(self, transition: statesman.Transition) -> None:
assert transition.created_at
assert transition.started_at is None
assert transition.finished_at is None
assert transition.cancelled is None
await transition()
assert transition.started_at is not None
assert transition.finished_at is not None
assert transition.cancelled == False
@pytest.mark.asyncio
async def test_runtime(self, transition: statesman.Transition) -> None:
assert transition.runtime is None
await transition()
assert transition.runtime is not None
assert isinstance(transition.runtime, datetime.timedelta)
@pytest.mark.asyncio
async def test_is_finished(self, transition: statesman.Transition) -> None:
assert transition.is_finished is False
await transition()
assert transition.is_finished is True
@pytest.mark.asyncio
async def test_is_executing(self, transition: statesman.Transition) -> None:
was_executing = None
def check_executing(transition: statesman.Transition):
nonlocal was_executing
was_executing = transition.is_executing
state = transition.state_machine.get_state(States.stopping)
state.add_action(check_executing, statesman.Action.Types.entry)
assert transition.is_executing is False
await transition()
assert was_executing is True
assert transition.is_executing is False
@pytest.mark.asyncio
async def test_args_and_kwargs(self, transition: statesman.Transition) -> None:
assert transition.args is None
assert transition.kwargs is None
await transition(1234, foo='Bar')
assert transition.args == (1234,)
assert transition.kwargs == {'foo': 'Bar'}
@pytest.mark.asyncio
async def test_params_passed_to_actions(self, transition: statesman.Transition) -> None:
called = False
def check_executing(count: int, foo: str):
nonlocal called
called = True
assert count == 1234
assert foo == 'Bar'
state = transition.state_machine.get_state(States.stopping)
state.add_action(check_executing, statesman.Action.Types.entry)
assert transition.is_executing is False
await transition(1234, foo='Bar')
assert called is True # Ensure that our inner assertions actually ran
@pytest.mark.asyncio
async def test_internal_transition(self, mocker) -> None:
state_machine = statesman.StateMachine()
state_machine.add_states(statesman.State.from_enum(States))
stopping = state_machine.get_state(States.stopping)
await state_machine.enter_state(stopping)
transition = statesman.Transition(
state_machine=state_machine,
source=stopping,
target=stopping,
state=States.stopping,
type=statesman.Transition.Types.internal,
)
assert transition.state_machine.state == stopping
entry_stub = mocker.stub(name='entering stopping')
exit_stub = mocker.stub(name='exiting stopping')
def entry(): return entry_stub()
def exit(): return exit_stub()
stopping.add_action(entry, statesman.Action.Types.entry)
stopping.add_action(exit, statesman.Action.Types.exit)
await transition()
entry_stub.assert_not_called()
exit_stub.assert_not_called()
@pytest.mark.asyncio
async def test_self_transition(self, mocker) -> None:
state_machine = statesman.StateMachine()
state_machine.add_states(statesman.State.from_enum(States))
stopping = state_machine.get_state(States.stopping)
await state_machine.enter_state(stopping)
transition = statesman.Transition(
state_machine=state_machine,
source=stopping,
target=stopping,
state=States.stopping,
type=statesman.Transition.Types.self,
)
assert transition.state_machine.state == stopping
entry_stub = mocker.stub(name='entering stopping')
exit_stub = mocker.stub(name='exiting stopping')
def entry(): return entry_stub()
def exit(): return exit_stub()
stopping.add_action(entry, statesman.Action.Types.entry)
stopping.add_action(exit, statesman.Action.Types.exit)
await transition()
entry_stub.assert_called_once()
exit_stub.assert_called_once()
@pytest.mark.asyncio
async def test_results_is_none_when_event_is_none(self, transition: statesman.Transition) -> None:
assert transition.event is None
assert transition.results is None
assert await transition()
assert transition.results is None
@pytest.mark.asyncio
async def test_results_is_populated_with_return_value_of_on_event_handlers(self, mocker) -> None:
state_machine = statesman.StateMachine()
state_machine.add_states(statesman.State.from_enum(States))
stopping = state_machine.get_state(States.stopping)
starting = state_machine.get_state(States.starting)
await state_machine.enter_state(stopping)
event = statesman.Event(
name='finish',
sources=[stopping],
target=stopping,
)
start_stub = mocker.stub(name='entering starting')
start_stub.return_value = 31337
def on_event(): return start_stub()
event.add_action(on_event, statesman.Action.Types.on)
state_machine.add_event(event)
transition = statesman.Transition(
state_machine=state_machine,
source=stopping,
target=starting,
type=statesman.Transition.Types.external,
event=event,
)
assert transition.state_machine.state == stopping
assert await transition()
assert transition.results == [31337]
class TestProgrammaticStateMachine:
def test_add_state(self) -> None:
state_machine = statesman.StateMachine()
state_machine.add_state(
statesman.State(
name=States.starting,
),
)
assert len(state_machine.states) == 1
state = state_machine.states[0]
assert state == States.starting
def test_add_state_cannot_duplicate_existing_name(self) -> None:
state_machine = statesman.StateMachine()
state_machine.add_state(
statesman.State(
name=States.starting,
),
)
assert len(state_machine.states) == 1
with pytest.raises(ValueError, match='a state named "starting" already exists'):
state_machine.add_state(
statesman.State(
name=States.starting,
),
)
def test_add_states(self) -> None:
state_machine = statesman.StateMachine()
state_machine.add_states(statesman.State.from_enum(States))
assert len(state_machine.states) == 4
state = state_machine.states[0]
assert state.name == States.starting.name
assert state.description == States.starting.value
def test_add_states_enum_names(self) -> None:
state_machine = statesman.StateMachine()
state_machine.add_states([
statesman.State(
name=States.starting,
description=States.starting,
),
statesman.State(
name=States.stopping,
),
])
assert len(state_machine.states) == 2
state1, state2 = state_machine.states
assert state1.name == 'starting'
assert state1.description == 'Starting'
assert state2.name == 'stopping'
assert state2.description is None # we didn't pass description
def test_enter_states_via_initializer(self) -> None:
state_machine = statesman.StateMachine(states=statesman.State.from_enum(States))
assert len(state_machine.states) == 4
state = state_machine.states[0]
assert state == States.starting
@pytest.mark.asyncio
async def test_enter_state_name_not_found(self) -> None:
state_machine = statesman.StateMachine(states=statesman.State.from_enum(States))
assert state_machine.state is None
with pytest.raises(LookupError, match='state entry failed: no state was found with the name "invalid"'):
await state_machine.enter_state('invalid')
@pytest.mark.asyncio
async def test_enter_state_enum_not_found(self) -> None:
class OtherStates(statesman.StateEnum):
invalid = 'invalid'
state_machine = statesman.StateMachine(states=statesman.State.from_enum(States))
assert state_machine.state is None
with pytest.raises(LookupError, match='state entry failed: no state was found with the name "invalid"'):
await state_machine.enter_state(OtherStates.invalid)
@pytest.mark.asyncio
async def test_enter_state_not_in_machine(self) -> None:
state = statesman.State('invalid')
state_machine = statesman.StateMachine(states=statesman.State.from_enum(States))
assert state_machine.state is None
with pytest.raises(ValueError, match='state entry failed: the state object given is not in the state machine'):
await state_machine.enter_state(state)
@pytest.mark.asyncio
async def test_enter_state_runs_state_actions(self, mocker) -> None:
state_machine = statesman.StateMachine()
state_machine.add_states(statesman.State.from_enum(States))
starting = state_machine.get_state(States.starting)
stopping = state_machine.get_state(States.stopping)
stub = mocker.stub(name='starting')
def action(): return stub()
starting.add_action(action, statesman.Action.Types.entry)
starting.add_action(action, statesman.Action.Types.exit)
stopping.add_action(action, statesman.Action.Types.entry)
stopping.add_action(action, statesman.Action.Types.exit)
# Test from zero state producing one entry state action
await state_machine.enter_state(starting)
stub.assert_called_once()
# Assign a new state producing two additional actions: exit starting, entry stopping
await state_machine.enter_state(stopping)
stub.assert_called()
assert stub.call_count == 3
@pytest.mark.asyncio
async def test_create_no_state(self) -> None:
state_machine = await statesman.StateMachine.create(states=statesman.State.from_enum(States))
assert state_machine.state is None
@pytest.mark.asyncio
async def test_create_enter_specific_state(self) -> None:
state_machine = await statesman.StateMachine.create(
states=statesman.State.from_enum(States),
state=States.stopping,
)
assert state_machine.state == States.stopping
@pytest.mark.asyncio
@pytest.mark.parametrize(
('callback'),
[
'guard_transition',
'before_transition',
'on_transition',
'after_transition',
],
)
@pytest.mark.asyncio
async def test_enter_state_with_args(self, callback, mocker) -> None:
state_machine = statesman.StateMachine(states=statesman.State.from_enum(States), state=States.starting)
assert state_machine.state == States.starting
with extra(state_machine):
callback_mock = mocker.spy(state_machine, callback)
await state_machine.enter_state(States.stopping, 1234, foo='bar')
callback_mock.assert_called_once()
assert len(callback_mock.call_args.args) == 2
assert isinstance(callback_mock.call_args.args[0], statesman.Transition), 'expected a Transition'
assert callback_mock.call_args.args[1]
assert callback_mock.call_args.kwargs == {'foo': 'bar'}
@pytest.mark.asyncio
async def test_doesnt_run_state_actions_for_internal_transitions(self, mocker) -> None:
state_machine = statesman.StateMachine(states=statesman.State.from_enum(States), state=States.starting)
assert state_machine.state == States.starting
# NOTE: we are already in Starting and entering it again
with extra(state_machine):
state = state_machine.get_state(States.starting)
entry_action = mocker.stub(name='entry action')
state.add_action(lambda: entry_action(), statesman.Action.Types.entry)
exit_action = mocker.stub(name='exit action')
state.add_action(lambda: exit_action(), statesman.Action.Types.exit)
on_callback_mock = mocker.spy(state_machine, 'on_transition')
await state_machine.enter_state(States.starting, 1234, foo='bar', type_=statesman.Transition.Types.internal)
on_callback_mock.assert_called_once()
entry_action.assert_not_called()
exit_action.assert_not_called()
@pytest.mark.asyncio
async def test_runs_state_actions_for_self_transitions(self, mocker) -> None:
state_machine = statesman.StateMachine(states=statesman.State.from_enum(States), state=States.starting)
assert state_machine.state == States.starting
# NOTE: we are already in Starting and entering it again
with extra(state_machine):
state = state_machine.get_state(States.starting)
entry_action = mocker.stub(name='entry action')
state.add_action(lambda: entry_action(), statesman.Action.Types.entry)
exit_action = mocker.stub(name='exit action')
state.add_action(lambda: exit_action(), statesman.Action.Types.exit)
on_callback_mock = mocker.spy(state_machine, 'on_transition')
await state_machine.enter_state(States.starting, 1234, foo='bar', type_=statesman.Transition.Types.self)
on_callback_mock.assert_called_once()
entry_action.assert_called_once()
exit_action.assert_called_once()
@pytest.mark.parametrize(('target_state',
'transition_type',
'error_message'),
[(States.starting,
statesman.Transition.Types.external,
'source and target states cannot be the same for external transitions'),
(States.running,
statesman.Transition.Types.internal,
'source and target states must be the same for internal or self transitions'),
(States.stopping,
statesman.Transition.Types.self,
'source and target states must be the same for internal or self transitions'),
],
)
@pytest.mark.asyncio
async def test_raises_if_states_and_transition_type_are_inconsistent(
self, target_state: statesman.StateEnum, transition_type: statesman.Transition.Types, error_message: str
) -> None:
state_machine = statesman.StateMachine(states=statesman.State.from_enum(States), state=States.starting)
assert state_machine.state == States.starting
with pytest.raises(pydantic.ValidationError, match=error_message):
await state_machine.enter_state(target_state, type_=transition_type)
class TestEntryConfig:
@pytest.mark.asyncio
async def test_allow(self) -> None:
state_machine = statesman.StateMachine(states=statesman.State.from_enum(States))
state_machine.__config__.state_entry = statesman.Entry.allow
assert state_machine.state is None
assert await state_machine.enter_state(States.starting)
assert state_machine.state == States.starting
assert await state_machine.enter_state(States.stopping)
assert state_machine.state == States.stopping
assert await state_machine.enter_state(States.stopped)
assert state_machine.state == States.stopped
@pytest.mark.asyncio
async def test_initial(self) -> None:
# Enter once for initial, then raise on next try
state_machine = statesman.StateMachine(states=statesman.State.from_enum(States))
state_machine.__config__.state_entry = statesman.Entry.initial
assert state_machine.state is None
assert await state_machine.enter_state(States.starting)
assert state_machine.state == States.starting
with pytest.raises(RuntimeError, match="state entry failed: `enter_state` is only available to set initial state"):
assert await state_machine.enter_state(States.stopping)
@pytest.mark.asyncio
async def test_ignore(self) -> None:
# Return false every time
state_machine = statesman.StateMachine(states=statesman.State.from_enum(States))
state_machine.__config__.state_entry = statesman.Entry.ignore
assert state_machine.state is None
assert not await state_machine.enter_state(States.starting)
assert state_machine.state is None
assert not await state_machine.enter_state(States.stopping)
assert state_machine.state is None
assert not await state_machine.enter_state(States.stopped)
assert state_machine.state is None
@pytest.mark.asyncio
async def test_forbid(self) -> None:
state_machine = statesman.StateMachine(states=statesman.State.from_enum(States))
state_machine.__config__.state_entry = statesman.Entry.forbid
assert state_machine.state is None
with pytest.raises(RuntimeError, match="state entry failed: use of the `enter_state` method is forbidden"):
assert await state_machine.enter_state(States.starting)
def test_add_event_fails_if_existing(self) -> None:
state_machine = statesman.StateMachine(states=statesman.State.from_enum(States), state=States.starting)
state = state_machine.states[0]
state_machine.add_event(
statesman.Event(
name='finish',
sources=[state],
target=state,
),
)
with pytest.raises(ValueError, match='an event named "finish" already exists'):
state_machine.add_event(
statesman.Event(
name='finish',
sources=[state],
target=state,
),
)
def test_add_event_fails_with_unknown_state(self) -> None:
state_machine = statesman.StateMachine()
state = statesman.State('invalid')
with pytest.raises(ValueError, match='cannot add an event that references unknown states: "invalid"'):
state_machine.add_event(
statesman.Event(
name='finish',
sources=[state],
target=state,
),
)
def test_add_event_allows_active_sentinel_state(self) -> None:
state_machine = statesman.StateMachine(states=statesman.State.from_enum(States))
state_machine.add_event(
statesman.Event(
name='finish',
sources=state_machine.states,
target=statesman.State.active(),
),
)
def test_cant_remove_active_state(self) -> None:
state_machine = statesman.StateMachine()
with pytest.raises(ValueError, match='cannot remove the active State'):
state_machine.remove_state(statesman.State.active())
def test_removing_state_clears_all_referencing_events(self) -> None:
state_machine = statesman.StateMachine(states=statesman.State.from_enum(States), state=States.starting)
state = state_machine.states[0]
event = statesman.Event(
name='finish',
sources=[state],
target=state,
)
state_machine.add_event(event)
assert state_machine.events == [event]
state_machine.remove_state(state)
assert state_machine.events == []
class TestTrigger:
@pytest.fixture()
def state_machine(self) -> statesman.StateMachine:
state_machine = statesman.StateMachine()
state_machine.add_states([
statesman.State(
name=States.starting,
),
statesman.State(
name=States.stopping,
),
])
state_machine.add_event(
statesman.Event(
name='finish',
sources=state_machine.get_states(States.starting, States.running),
target=state_machine.get_state(States.stopping),
),
)
state_machine.add_event(
statesman.Event(
name='reset',
sources=state_machine.get_states(States.stopping),
target=state_machine.get_state(States.starting),
),
)
return state_machine
@pytest.mark.asyncio
async def test_get_event(self, state_machine: statesman.StateMachine) -> None:
event = state_machine.get_event('finish')
assert event is not None
@pytest.mark.asyncio
async def test_get_event_not_found(self, state_machine: statesman.StateMachine) -> None:
event = state_machine.get_event('invalid')
assert event is None
@pytest.mark.asyncio
async def test_get_event_invalid_type_raises(self, state_machine: statesman.StateMachine) -> None:
assert state_machine.state is None
with pytest.raises(TypeError) as e:
state_machine.get_event(1234)
assert str(e.value) == "cannot get event for name of type \"int\": 1234"
@pytest.mark.asyncio
async def test_can_trigger(self, state_machine: statesman.StateMachine) -> None:
state_machine.__config__.state_entry = statesman.Entry.allow
await state_machine.enter_state(States.starting)
assert state_machine.state == States.starting
assert state_machine.can_trigger_event('finish')
assert not state_machine.can_trigger_event('reset')
await state_machine.trigger_event('finish')
assert state_machine.state == States.stopping
assert not state_machine.can_trigger_event('finish')
assert state_machine.can_trigger_event('reset')
@pytest.mark.asyncio
async def test_can_trigger_from_state(self, state_machine: statesman.StateMachine) -> None:
assert state_machine.can_trigger_event('finish', from_state=States.starting)
assert state_machine.can_trigger_event('finish', from_state="starting")
assert state_machine.can_trigger_event('finish', from_state=state_machine.get_state("starting"))
assert not state_machine.can_trigger_event('reset', from_state=States.starting)
assert not state_machine.can_trigger_event('reset', from_state="starting")
assert not state_machine.can_trigger_event('reset', from_state=state_machine.get_state("starting"))
@pytest.mark.asyncio
async def test_can_trigger_from_state(self, state_machine: statesman.StateMachine) -> None:
assert state_machine.triggerable_events() == []
assert state_machine.triggerable_events(from_state=None) == []
assert state_machine.triggerable_events(from_state="stopping") == [state_machine.get_event("reset")]
assert state_machine.triggerable_events(from_state="starting") == [state_machine.get_event("finish")]
@pytest.mark.asyncio
async def test_by_name(self, state_machine: statesman.StateMachine) -> None:
await state_machine.enter_state(States.starting)
assert state_machine.state == States.starting
await state_machine.trigger_event('finish')
assert state_machine.state == States.stopping
@pytest.mark.asyncio
async def test_by_event(self, state_machine: statesman.StateMachine) -> None:
await state_machine.enter_state(States.starting)
assert state_machine.state == States.starting
event = state_machine.get_event('finish')
await state_machine.trigger_event(event)
assert state_machine.state == States.stopping
@pytest.mark.asyncio
async def test_trigger_without_state_raises(self, state_machine: statesman.StateMachine) -> None:
assert state_machine.state is None
with pytest.raises(RuntimeError, match='event trigger failed: the "finish" event does not support initial state transitions'):
await state_machine.trigger_event('finish')
@pytest.mark.asyncio
async def test_trigger_from_incompatible_state(self, state_machine: statesman.StateMachine) -> None:
await state_machine.enter_state(States.stopping)
with pytest.raises(RuntimeError, match='event trigger failed: the "finish" event cannot be triggered from the current state of "stopping"'):
await state_machine.trigger_event('finish')
@pytest.mark.asyncio
async def test_with_invalid_name(self, state_machine: statesman.StateMachine) -> None:
await state_machine.enter_state(States.starting)
with pytest.raises(LookupError, match="event trigger failed: no event was found with the name \"invalid\""):
await state_machine.trigger_event('invalid')
@pytest.mark.asyncio
async def test_with_invalid_type(self, state_machine: statesman.StateMachine) -> None:
await state_machine.enter_state(States.starting)
with pytest.raises(TypeError, match="event trigger failed: cannot trigger an event of type \"int\": 1234"):
await state_machine.trigger_event(1234)
class TestReturnTypes:
@pytest.fixture()
def event(self, state_machine: statesman.StateMachine) -> statesman.Event:
event = state_machine.get_event('finish')
event.add_action(lambda: 31337, statesman.Action.Types.on)
event.add_action(lambda: 187, statesman.Action.Types.on)
event.add_action(lambda: 420, statesman.Action.Types.on)
return event
@pytest.mark.parametrize(('return_type', 'expected_return_value',),
[
(bool, True),
(object, 31337),
(tuple, (True, 31337)),
(list, [31337, 187, 420]),
]
)
@pytest.mark.asyncio
async def test_return_types(self, state_machine: statesman.StateMachine, event, return_type, expected_return_value) -> None:
await state_machine.enter_state(States.starting)
assert state_machine.state == States.starting
event.return_type = return_type
result = await state_machine.trigger_event('finish')
assert result == expected_return_value
@pytest.mark.parametrize(('return_type', 'expected_return_value',),
[
(bool, True),
(object, 31337),
(tuple, (True, 31337)),
(list, [31337, 187, 420]),
]
)
@pytest.mark.asyncio
async def test_return_types_override_on_trigger(self, state_machine: statesman.StateMachine, event, return_type, expected_return_value) -> None:
await state_machine.enter_state(States.starting)
assert state_machine.state == States.starting
event.return_type = statesman.Transition
result = await state_machine.trigger_event('finish', return_type=return_type)
assert result == expected_return_value
@pytest.mark.asyncio
async def test_transition_return_type(self, state_machine: statesman.StateMachine, event) -> None:
await state_machine.enter_state(States.starting)
assert state_machine.state == States.starting
event.return_type = statesman.Transition
transition = await state_machine.trigger_event('finish')
assert isinstance(transition, statesman.Transition)
assert transition.event == event
assert transition.succeeded == True
assert transition.results == [31337, 187, 420]
@pytest.mark.asyncio
async def test_with_event_not_in_machine(self, state_machine: statesman.StateMachine) -> None:
invalid_event = statesman.Event(
name='invalid',
sources=state_machine.states,
target=state_machine.get_state(States.stopping),
)
await state_machine.enter_state(States.starting)
with pytest.raises(TypeError, match="event trigger failed: cannot trigger an event of type \"int\": 1234"):
await state_machine.trigger_event(1234)
@pytest.mark.asyncio
async def test_cancel_via_guard_state_machine_method(self, state_machine: statesman.StateMachine, mocker) -> None:
await state_machine.enter_state(States.starting)
with extra(state_machine):
guard_mock = mocker.patch.object(state_machine, 'guard_transition')
guard_mock.return_value = False
success = await state_machine.trigger_event('finish')
guard_mock.assert_awaited_once()
assert not success, 'should have been guarded'
@pytest.mark.asyncio
async def test_returning_none_from_guard_does_not_cancel(self, state_machine: statesman.StateMachine, mocker) -> None:
await state_machine.enter_state(States.starting)
with extra(state_machine):
guard_mock = mocker.patch.object(state_machine, 'guard_transition')
guard_mock.return_value = None
success = await state_machine.trigger_event('finish')
guard_mock.assert_awaited_once()
assert success, 'should not have been guarded'
@pytest.mark.asyncio
async def test_returning_invalid_value_from_guard_raises_value_error(self, state_machine: statesman.StateMachine, mocker) -> None:
await state_machine.enter_state(States.starting)
with extra(state_machine):
guard_mock = mocker.patch.object(state_machine, 'guard_transition')
guard_mock.return_value = "invalid"
with pytest.raises(ValueError, match="invalid return value from guard_transition: must return True, False, or None"):
await state_machine.trigger_event('finish')
guard_mock.assert_awaited_once()
@pytest.mark.asyncio
async def test_non_assertion_errors_raise(self, state_machine: statesman.StateMachine, mocker) -> None:
await state_machine.enter_state(States.starting)
with extra(state_machine):
guard_mock = mocker.patch.object(state_machine, 'guard_transition')
guard_mock.side_effect = RuntimeError(f'failed!')
with pytest.raises(RuntimeError, match='failed!'):
success = await state_machine.trigger_event('finish')
guard_mock.assert_awaited_once()
assert not success, 'should have been guarded'
@pytest.mark.asyncio
async def test_guard_with_silence(self, state_machine: statesman.StateMachine, mocker) -> None:
state_machine.__config__.guard_with = statesman.Guard.silence
await state_machine.enter_state(States.starting)
with extra(state_machine):
guard_mock = mocker.patch.object(state_machine, 'guard_transition')
guard_mock.return_value = False
success = await state_machine.trigger_event('finish')
guard_mock.assert_awaited_once()
assert not success, 'should have been guarded'
@pytest.mark.asyncio
async def test_guard_with_warning(self, state_machine: statesman.StateMachine, mocker) -> None:
state_machine.__config__.guard_with = statesman.Guard.warning
await state_machine.enter_state(States.starting)
with extra(state_machine):
guard_mock = mocker.patch.object(state_machine, 'guard_transition')
guard_mock.return_value = False
with pytest.warns(UserWarning, match='transition guard failure: guard_transition returned False'):
await state_machine.trigger_event('finish')
@pytest.mark.asyncio
async def test_guard_with_exception(self, state_machine: statesman.StateMachine, mocker) -> None:
state_machine.__config__.guard_with = statesman.Guard.exception
await state_machine.enter_state(States.starting)
with extra(state_machine):
guard_mock = mocker.patch.object(state_machine, 'guard_transition')
guard_mock.return_value = False
with pytest.raises(RuntimeError, match="transition guard failure: guard_transition returned False"):
await state_machine.trigger_event('finish')
class TestActions:
@pytest.mark.asyncio
async def test_guard(self, state_machine: statesman.StateMachine, mocker) -> None:
await state_machine.enter_state(States.starting)
event = state_machine.get_event('finish')
guard_action = mocker.stub(name='action')
guard_action.return_value = True
event.add_action(lambda: guard_action(), statesman.Action.Types.guard)
assert await state_machine.trigger_event('finish'), 'guard passed'
guard_action.assert_called_once()
@pytest.mark.asyncio
async def test_cancel_via_guard_action_bool(self, state_machine: statesman.StateMachine, mocker) -> None:
state_machine.__config__.guard_with = statesman.Guard.silence
await state_machine.enter_state(States.starting)
event = state_machine.get_event('finish')
guard_action = mocker.stub(name='action')
guard_action.return_value = False
event.add_action(lambda: guard_action(), statesman.Action.Types.guard)
# NOTE: The AssertionError is being caught and aborts the test
success = await state_machine.trigger_event('finish')
guard_action.assert_called_once()
assert not success, 'should have been cancelled by guard'
@pytest.mark.asyncio
async def test_none_return_value_from_guard_does_not_cancel(self, state_machine: statesman.StateMachine, mocker) -> None:
await state_machine.enter_state(States.starting)
event = state_machine.get_event('finish')
guard_action = mocker.stub(name='action')
guard_action.return_value = None
event.add_action(lambda: guard_action(), statesman.Action.Types.guard)
success = await state_machine.trigger_event('finish')
guard_action.assert_called_once()
assert success, 'should not have been cancelled by guard'
@pytest.mark.asyncio
async def test_invalid_return_value_from_guard_raises_value_error(self, state_machine: statesman.StateMachine, mocker) -> None:
await state_machine.enter_state(States.starting)
event = state_machine.get_event('finish')
guard_action = mocker.stub(name='action')
guard_action.return_value = "invalid"
event.add_action(lambda: guard_action(), statesman.Action.Types.guard)
with pytest.raises(ValueError, match="invalid return value from guard action: must return True, False, or None"):
await state_machine.trigger_event('finish')
guard_action.assert_called_once()
@pytest.mark.asyncio
async def test_cancel_via_guard_action_exception(self, state_machine: statesman.StateMachine, mocker) -> None:
await state_machine.enter_state(States.starting)
event = state_machine.get_event('finish')
guard_action = mocker.stub(name='action')
guard_action.side_effect = AssertionError('should be suppressed')
event.add_action(lambda: guard_action(), statesman.Action.Types.guard)
# NOTE: The AssertionError is being caught and aborts the test
success = await state_machine.trigger_event('finish')
assert not success, 'cancelled by guard'
guard_action.assert_called_once()
@pytest.mark.asyncio
async def test_guard_actions_run_sequentially(self, state_machine: statesman.StateMachine, mocker) -> None:
await state_machine.enter_state(States.starting)
event = state_machine.get_event('finish')
guard_action1 = mocker.stub(name='first guard')
guard_action1.return_value = False
guard_action2 = mocker.stub(name='second guard')
guard_action2.return_value = True
event.add_action(lambda: guard_action1(), statesman.Action.Types.guard)
event.add_action(lambda: guard_action2(), statesman.Action.Types.guard)
assert not await state_machine.trigger_event('finish'), 'guard failed'
guard_action1.assert_called_once()
guard_action2.assert_not_called()