-
-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathtest_spec_parser.py
More file actions
357 lines (307 loc) · 11.6 KB
/
test_spec_parser.py
File metadata and controls
357 lines (307 loc) · 11.6 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
import asyncio
from typing import TYPE_CHECKING
import pytest
from statemachine.spec_parser import Functions
from statemachine.spec_parser import operator_mapping
from statemachine.spec_parser import parse_boolean_expr
if TYPE_CHECKING:
from collections.abc import Callable
def variable_hook(
var_name: str,
spy: "Callable[[str], None] | None" = None,
) -> "Callable":
values = {
"frodo_has_ring": True,
"sauron_alive": False,
"gandalf_present": True,
"sam_is_loyal": True,
"orc_army_ready": False,
"frodo_age": 50,
"height": 1.75,
"name": "Frodo",
"aragorn_age": 87,
"legolas_age": 2931,
"gimli_age": 139,
"ring_power": 100,
"sword_power": 80,
"bow_power": 75,
"axe_power": 85,
}
def decorated(*args, **kwargs):
if spy is not None:
spy(var_name)
return values.get(var_name, False)
decorated.__name__ = var_name
return decorated
@pytest.mark.parametrize(
("expression", "expected", "hooks_called"),
[
("frodo_has_ring", True, ["frodo_has_ring"]),
("frodo_has_ring or sauron_alive", True, ["frodo_has_ring"]),
(
"frodo_has_ring and gandalf_present",
True,
["frodo_has_ring", "gandalf_present"],
),
("sauron_alive", False, ["sauron_alive"]),
("not sauron_alive", True, ["sauron_alive"]),
(
"frodo_has_ring and (gandalf_present or sauron_alive)",
True,
["frodo_has_ring", "gandalf_present"],
),
(
"not sauron_alive and orc_army_ready",
False,
["sauron_alive", "orc_army_ready"],
),
(
"not (not sauron_alive and orc_army_ready)",
True,
["sauron_alive", "orc_army_ready"],
),
(
"(frodo_has_ring and sam_is_loyal) or (not sauron_alive and orc_army_ready)",
True,
["frodo_has_ring", "sam_is_loyal"],
),
(
"(frodo_has_ring ^ sam_is_loyal) v (!sauron_alive ^ orc_army_ready)",
True,
["frodo_has_ring", "sam_is_loyal"],
),
("not (not frodo_has_ring)", True, ["frodo_has_ring"]),
("!(!frodo_has_ring)", True, ["frodo_has_ring"]),
(
"frodo_has_ring and orc_army_ready",
False,
["frodo_has_ring", "orc_army_ready"],
),
(
"frodo_has_ring ^ orc_army_ready",
False,
["frodo_has_ring", "orc_army_ready"],
),
(
"frodo_has_ring and not orc_army_ready",
True,
["frodo_has_ring", "orc_army_ready"],
),
(
"frodo_has_ring ^ !orc_army_ready",
True,
["frodo_has_ring", "orc_army_ready"],
),
(
"frodo_has_ring and (sam_is_loyal or (gandalf_present and not sauron_alive))",
True,
["frodo_has_ring", "sam_is_loyal"],
),
(
"frodo_has_ring ^ (sam_is_loyal v (gandalf_present ^ !sauron_alive))",
True,
["frodo_has_ring", "sam_is_loyal"],
),
("sauron_alive or orc_army_ready", False, ["sauron_alive", "orc_army_ready"]),
("sauron_alive v orc_army_ready", False, ["sauron_alive", "orc_army_ready"]),
(
"(frodo_has_ring and gandalf_present) or orc_army_ready",
True,
["frodo_has_ring", "gandalf_present"],
),
(
"orc_army_ready or (frodo_has_ring and gandalf_present)",
True,
["orc_army_ready", "frodo_has_ring", "gandalf_present"],
),
(
"orc_army_ready and (frodo_has_ring and gandalf_present)",
False,
["orc_army_ready"],
),
(
"!orc_army_ready and (frodo_has_ring and gandalf_present)",
True,
["orc_army_ready", "frodo_has_ring", "gandalf_present"],
),
(
"!orc_army_ready and !(frodo_has_ring and gandalf_present)",
False,
["orc_army_ready", "frodo_has_ring", "gandalf_present"],
),
("frodo_has_ring or True", True, ["frodo_has_ring"]),
("sauron_alive or True", True, ["sauron_alive"]),
("frodo_age >= 50", True, ["frodo_age"]),
("50 <= frodo_age", True, ["frodo_age"]),
("frodo_age <= 50", True, ["frodo_age"]),
("frodo_age == 50", True, ["frodo_age"]),
("frodo_age > 50", False, ["frodo_age"]),
("frodo_age < 50", False, ["frodo_age"]),
("frodo_age != 50", False, ["frodo_age"]),
("frodo_age != 49", True, ["frodo_age"]),
("49 < frodo_age < 51", True, ["frodo_age", "frodo_age"]),
("49 < frodo_age > 50", False, ["frodo_age", "frodo_age"]),
(
"aragorn_age < legolas_age < gimli_age",
False,
["aragorn_age", "legolas_age", "legolas_age", "gimli_age"],
), # 87 < 2931 and 2931 < 139
(
"gimli_age > aragorn_age < legolas_age",
True,
["gimli_age", "aragorn_age", "aragorn_age", "legolas_age"],
), # 139 > 87 and 87 < 2931
(
"sword_power < ring_power > bow_power",
True,
["sword_power", "ring_power", "ring_power", "bow_power"],
), # 80 < 100 and 100 > 75
(
"axe_power > sword_power == bow_power",
False,
["axe_power", "sword_power", "sword_power", "bow_power"],
), # 85 > 80 and 80 == 75
("name == 'Frodo'", True, ["name"]),
("name != 'Sam'", True, ["name"]),
("height == 1.75", True, ["height"]),
("height > 1 and height < 2", True, ["height", "height"]),
],
)
def test_expressions(expression, expected, hooks_called):
calls: list[str] = []
def hook(name):
return variable_hook(name, spy=calls.append)
parsed_expr = parse_boolean_expr(expression, hook, operator_mapping)
assert parsed_expr() is expected, expression
assert calls == hooks_called
def test_negating_compound_false_expression():
expr = "not (not sauron_alive and orc_army_ready)"
parsed_expr = parse_boolean_expr(expr, variable_hook, operator_mapping)
assert parsed_expr() is True
assert parsed_expr.__name__ == "not((not(sauron_alive) and orc_army_ready))"
def test_expression_name_uniqueness():
expr = "frodo_has_ring or not orc_army_ready"
parsed_expr = parse_boolean_expr(expr, variable_hook, operator_mapping)
assert (
parsed_expr.__name__ == "(frodo_has_ring or not(orc_army_ready))"
) # name reflects expression structure
def test_classical_operators_name():
expr = "frodo_has_ring ^ !orc_army_ready"
parsed_expr = parse_boolean_expr(expr, variable_hook, operator_mapping)
assert parsed_expr() is True # both parts are True
assert (
parsed_expr.__name__ == "(frodo_has_ring and not(orc_army_ready))"
) # name reflects expression structure
def test_empty_expression():
expr = ""
with pytest.raises(SyntaxError):
parse_boolean_expr(expr, variable_hook, operator_mapping)
def test_whitespace_expression():
expr = " "
with pytest.raises(SyntaxError):
parse_boolean_expr(expr, variable_hook, operator_mapping)
def test_missing_operator_expression():
expr = "frodo_has_ring orc_army_ready"
with pytest.raises(SyntaxError):
parse_boolean_expr(expr, variable_hook, operator_mapping)
def test_dict_usage_expression():
expr = "frodo_has_ring or {}"
with pytest.raises(ValueError, match="Unsupported expression structure"):
parse_boolean_expr(expr, variable_hook, operator_mapping)
def test_unsupported_operator():
# Define an unsupported operator like MUL
expr = "frodo_has_ring * gandalf_present"
with pytest.raises(ValueError, match="Unsupported expression structure"):
parse_boolean_expr(expr, variable_hook, operator_mapping)
def test_simple_variable_returns_the_original_callback():
def original_callback(*args, **kwargs):
return True
mapping = {"original": original_callback}
def variable_hook(var_name):
return mapping.get(var_name, None)
expr = "original"
parsed_expr = parse_boolean_expr(expr, variable_hook, operator_mapping)
assert parsed_expr is original_callback
def async_variable_hook(var_name):
"""Variable hook that returns async callables, for testing issue #535."""
values = {
"cond_true": True,
"cond_false": False,
"val_10": 10,
"val_20": 20,
}
value = values.get(var_name, False)
async def decorated(*args, **kwargs):
await asyncio.sleep(0)
return value
decorated.__name__ = var_name
return decorated
@pytest.mark.parametrize(
("expression", "expected"),
[
("not cond_false", True),
("not cond_true", False),
("cond_true and cond_true", True),
("cond_true and cond_false", False),
("cond_false and cond_true", False),
("cond_false or cond_true", True),
("cond_true or cond_false", True),
("cond_false or cond_false", False),
("not cond_false and cond_true", True),
("not (cond_true and cond_false)", True),
("not (cond_false or cond_false)", True),
("cond_true and not cond_false", True),
("val_10 == 10", True),
("val_10 != 20", True),
("val_10 < val_20", True),
("val_20 > val_10", True),
("val_10 >= 10", True),
("val_10 <= val_20", True),
],
)
def test_async_expressions(expression, expected):
"""Issue #535: condition expressions with async predicates must await results."""
parsed_expr = parse_boolean_expr(expression, async_variable_hook, operator_mapping)
result = parsed_expr()
assert asyncio.iscoroutine(result), f"Expected coroutine for async expression: {expression}"
assert asyncio.run(result) is expected, expression
def mixed_variable_hook(var_name):
"""Variable hook where some vars are sync and some are async."""
sync_values = {"sync_true": True, "sync_false": False, "sync_10": 10}
async_values = {"async_true": True, "async_false": False, "async_20": 20}
if var_name in async_values:
value = async_values[var_name]
async def async_decorated(*args, **kwargs):
await asyncio.sleep(0)
return value
async_decorated.__name__ = var_name
return async_decorated
def sync_decorated(*args, **kwargs):
return sync_values.get(var_name, False)
sync_decorated.__name__ = var_name
return sync_decorated
@pytest.mark.parametrize(
("expression", "expected"),
[
# async left, sync right
("async_true and sync_true", True),
("async_false or sync_true", True),
# sync left, async right
("sync_true and async_true", True),
("sync_false or async_true", True),
("sync_true and async_false", False),
("sync_false or async_false", False),
],
)
def test_mixed_sync_async_expressions(expression, expected):
"""Expressions mixing sync and async predicates must handle both correctly."""
parsed_expr = parse_boolean_expr(expression, mixed_variable_hook, operator_mapping)
result = parsed_expr()
if asyncio.iscoroutine(result):
assert asyncio.run(result) is expected, expression
else:
assert result is expected, expression
def test_functions_get_unknown_raises():
"""Functions.get raises ValueError for unknown functions."""
with pytest.raises(ValueError, match="Unsupported function"):
Functions.get("nonexistent_function")