forked from fgmacedo/python-statemachine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_copy.py
More file actions
191 lines (132 loc) · 4.73 KB
/
Copy pathtest_copy.py
File metadata and controls
191 lines (132 loc) · 4.73 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
import asyncio
import logging
import pickle
from copy import deepcopy
from enum import Enum
from enum import auto
import pytest
from statemachine.states import States
from statemachine import State
from statemachine import StateChart
logger = logging.getLogger(__name__)
def copy_pickle(obj):
return pickle.loads(pickle.dumps(obj))
@pytest.fixture(params=[deepcopy, copy_pickle], ids=["deepcopy", "pickle"])
def copy_method(request):
return request.param
class GameStates(str, Enum):
GAME_START = auto()
GAME_PLAYING = auto()
TURN_END = auto()
GAME_END = auto()
class GameStateMachine(StateChart):
s = States.from_enum(GameStates, initial=GameStates.GAME_START, final=GameStates.GAME_END)
play = s.GAME_START.to(s.GAME_PLAYING)
stop = s.GAME_PLAYING.to(s.TURN_END)
end_game = s.TURN_END.to(s.GAME_END)
@end_game.cond
def game_is_over(self) -> bool:
return True
advance_round = end_game | s.TURN_END.to(s.GAME_END)
class MyStateMachine(StateChart):
created = State(initial=True)
started = State(final=True)
start = created.to(started)
def __init__(self):
super().__init__()
self.custom = 1
self.value = [1, 2, 3]
class MySM(StateChart):
draft = State("Draft", initial=True, value="draft")
published = State("Published", value="published", final=True)
publish = draft.to(published, cond="let_me_be_visible")
def let_me_be_visible(self):
return True
class MyModel:
def __init__(self, name: str) -> None:
self.name = name
self._let_me_be_visible = False
def __repr__(self) -> str:
return f"{type(self).__name__}@{id(self)}({self.name!r})"
@property
def let_me_be_visible(self):
return self._let_me_be_visible
@let_me_be_visible.setter
def let_me_be_visible(self, value):
self._let_me_be_visible = value
def test_copy(copy_method):
sm = MySM(MyModel("main_model"))
sm2 = copy_method(sm)
assert sm.model is not sm2.model
assert sm.model.name == sm2.model.name
assert sm2.draft.is_active
sm2.model.let_me_be_visible = True
sm2.send("publish")
assert sm2.published.is_active
def test_copy_with_listeners(copy_method):
model1 = MyModel("main_model")
sm1 = MySM(model1)
listener_1 = MyModel("observer_1")
listener_2 = MyModel("observer_2")
sm1.add_listener(listener_1)
sm1.add_listener(listener_2)
sm2 = copy_method(sm1)
assert sm1.model is not sm2.model
assert len(sm1._listeners) == len(sm2._listeners)
assert all(
listener.name == copied_listener.name
for listener, copied_listener in zip(
sm1._listeners.values(), sm2._listeners.values(), strict=True
)
)
sm2.model.let_me_be_visible = True
for listener in sm2._listeners.values():
listener.let_me_be_visible = True
sm2.send("publish")
assert sm2.published.is_active
def test_copy_with_enum(copy_method):
sm = GameStateMachine()
sm.play()
assert GameStates.GAME_PLAYING in sm.configuration_values
sm2 = copy_method(sm)
assert GameStates.GAME_PLAYING in sm2.configuration_values
def test_copy_with_custom_init_and_vars(copy_method):
sm = MyStateMachine()
sm.start()
sm2 = copy_method(sm)
assert sm2.custom == 1
assert sm2.value == [1, 2, 3]
assert sm2.started.is_active
class AsyncTrafficLightMachine(StateChart):
green = State(initial=True)
yellow = State()
red = State()
cycle = green.to(yellow) | yellow.to(red) | red.to(green)
async def on_enter_state(self, target):
"""Async callback to ensure the SM uses AsyncEngine."""
def test_copy_async_statemachine_before_activation(copy_method):
"""Regression test for issue #544: async SM fails after pickle/deepcopy.
When an async SM is copied before activation, the copy must still be
activatable because ``__setstate__`` re-enqueues the ``__initial__`` event.
"""
sm = AsyncTrafficLightMachine()
sm_copy = copy_method(sm)
async def verify():
await sm_copy.activate_initial_state()
assert sm_copy.green.is_active
await sm_copy.cycle()
assert sm_copy.yellow.is_active
asyncio.run(verify())
def test_copy_async_statemachine_after_activation(copy_method):
"""Copying an async SM that is already activated preserves its current state."""
async def setup_and_verify():
sm = AsyncTrafficLightMachine()
await sm.activate_initial_state()
await sm.cycle()
assert sm.yellow.is_active
sm_copy = copy_method(sm)
await sm_copy.activate_initial_state()
assert sm_copy.yellow.is_active
await sm_copy.cycle()
assert sm_copy.red.is_active
asyncio.run(setup_and_verify())