forked from temporalio/sdk-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_workflow.py
More file actions
590 lines (462 loc) · 16.9 KB
/
Copy pathtest_workflow.py
File metadata and controls
590 lines (462 loc) · 16.9 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
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
import inspect
import itertools
import typing
from collections.abc import Callable, Sequence
from typing import Any, get_type_hints
import pytest
from temporalio import workflow
from temporalio.common import RawValue, VersioningBehavior
class GoodDefnBase:
@workflow.run
async def run(self, _name: str) -> str:
raise NotImplementedError
@workflow.signal
def base_signal(self):
pass
@workflow.query
def base_query(self):
pass
@workflow.update
def base_update(self):
pass
@workflow.defn(name="workflow-custom")
class GoodDefn(GoodDefnBase):
@workflow.run
async def run(self, _name: str) -> str:
raise NotImplementedError
@workflow.signal
def signal1(self):
pass
@workflow.signal(name="signal-custom", description="fun")
def signal2(self):
pass
@workflow.signal(dynamic=True, description="boo")
def signal3(self, _name: str, _args: Sequence[RawValue]):
pass
@workflow.query
def query1(self):
pass
@workflow.query(name="query-custom", description="qd")
def query2(self):
pass
@workflow.query(dynamic=True, description="dqd")
def query3(self, _name: str, _args: Sequence[RawValue]):
pass
@workflow.update
def update1(self):
pass
@workflow.update(name="update-custom", description="ud")
def update2(self):
pass
@workflow.update(dynamic=True, description="dud")
def update3(self, _name: str, _args: Sequence[RawValue]):
pass
@workflow.defn()
class GoodDefnDeprecatedTypes(GoodDefnBase):
# Just having the definition here is enough to confirm the signatures
# do not trigger a RuntimeError
@workflow.run
async def run(self, _name: str) -> str:
raise NotImplementedError
@workflow.signal(dynamic=True)
def signal(self, _name: str, _args: typing.Sequence[RawValue]): # type: ignore[reportDeprecated]
pass
@workflow.query(dynamic=True)
def query(self, _name: str, _args: typing.Sequence[RawValue]): # type: ignore[reportDeprecated]
pass
@workflow.update(dynamic=True)
def update(self, _name: str, _args: typing.Sequence[RawValue]): # type: ignore[reportDeprecated]
pass
def test_workflow_defn_good():
# Although the API is internal, we want to check the literal definition just
# in case
defn = workflow._Definition.from_class(GoodDefn)
assert defn == workflow._Definition(
name="workflow-custom",
cls=GoodDefn,
run_fn=GoodDefn.run,
signals={
"signal1": workflow._SignalDefinition(
name="signal1", fn=GoodDefn.signal1, is_method=True
),
"signal-custom": workflow._SignalDefinition(
name="signal-custom",
fn=GoodDefn.signal2,
is_method=True,
description="fun",
),
None: workflow._SignalDefinition(
name=None, fn=GoodDefn.signal3, is_method=True, description="boo"
),
"base_signal": workflow._SignalDefinition(
name="base_signal", fn=GoodDefnBase.base_signal, is_method=True
),
},
queries={
"query1": workflow._QueryDefinition(
name="query1", fn=GoodDefn.query1, is_method=True
),
"query-custom": workflow._QueryDefinition(
name="query-custom",
fn=GoodDefn.query2,
is_method=True,
description="qd",
),
None: workflow._QueryDefinition(
name=None, fn=GoodDefn.query3, is_method=True, description="dqd"
),
"base_query": workflow._QueryDefinition(
name="base_query", fn=GoodDefnBase.base_query, is_method=True
),
},
updates={
"update1": workflow._UpdateDefinition(
name="update1", fn=GoodDefn.update1, is_method=True
),
"update-custom": workflow._UpdateDefinition(
name="update-custom",
fn=GoodDefn.update2,
is_method=True,
description="ud",
),
None: workflow._UpdateDefinition(
name=None, fn=GoodDefn.update3, is_method=True, description="dud"
),
"base_update": workflow._UpdateDefinition(
name="base_update", fn=GoodDefnBase.base_update, is_method=True
),
},
sandboxed=True,
failure_exception_types=[],
versioning_behavior=VersioningBehavior.UNSPECIFIED,
)
@workflow.defn(versioning_behavior=VersioningBehavior.PINNED)
class VersioningBehaviorDefn:
@workflow.run
async def run(self, _name: str) -> str:
raise NotImplementedError
def test_workflow_definition_with_versioning_behavior():
defn = workflow._Definition.from_class(VersioningBehaviorDefn)
assert defn == workflow._Definition(
name="VersioningBehaviorDefn",
cls=VersioningBehaviorDefn,
run_fn=VersioningBehaviorDefn.run,
signals={},
queries={},
updates={},
sandboxed=True,
failure_exception_types=[],
versioning_behavior=VersioningBehavior.PINNED,
)
class BadDefnBase:
@workflow.signal
def base_signal(self):
pass
@workflow.query
def base_query(self):
pass
@workflow.update
def base_update(self):
pass
class BadDefn(BadDefnBase):
# Intentionally missing @workflow.run
@workflow.signal
def signal1(self):
pass
@workflow.signal(name="signal1")
def signal2(self):
pass
@workflow.signal(dynamic=True)
def signal3(self, _name: str, _args: Sequence[RawValue]):
pass
@workflow.signal(dynamic=True)
def signal4(self, _name: str, _args: Sequence[RawValue]):
pass
# Intentionally missing decorator
def base_signal(self):
pass
@workflow.query
def query1(self):
pass
@workflow.query(name="query1")
def query2(self):
pass
@workflow.query(dynamic=True)
def query3(self, _name: str, _args: Sequence[RawValue]):
pass
@workflow.query(dynamic=True)
def query4(self, _name: str, _args: Sequence[RawValue]):
pass
# Intentionally missing decorator
def base_query(self):
pass
@workflow.update
def update1(self, _arg1: str):
pass
@workflow.update(name="update1")
def update2(self, _arg1: str):
pass
# Intentionally missing decorator
def base_update(self): # type: ignore[override]
pass
def test_workflow_defn_bad():
with pytest.raises(ValueError) as err:
workflow.defn(BadDefn)
assert "Invalid workflow class for 9 reasons" in str(err.value)
assert "Missing @workflow.run method" in str(err.value)
assert (
"Multiple signal methods found for signal1 (at least on signal2 and signal1)"
in str(err.value)
)
assert (
"Multiple signal methods found for <dynamic> (at least on signal4 and signal3)"
in str(err.value)
)
assert (
"@workflow.signal defined on BadDefnBase.base_signal but not on the override"
in str(err.value)
)
assert (
"Multiple query methods found for query1 (at least on query2 and query1)"
in str(err.value)
)
assert (
"Multiple query methods found for <dynamic> (at least on query4 and query3)"
in str(err.value)
)
assert (
"@workflow.query defined on BadDefnBase.base_query but not on the override"
in str(err.value)
)
assert (
"Multiple update methods found for update1 (at least on update2 and update1)"
in str(err.value)
)
assert (
"@workflow.update defined on BadDefnBase.base_update but not on the override"
in str(err.value)
)
def test_workflow_defn_local_class():
with pytest.raises(ValueError) as err:
@workflow.defn
class LocalClass: # type:ignore[reportUnusedClass]
@workflow.run
async def run(self):
pass
assert "Local classes unsupported" in str(err.value)
class NonAsyncRun:
def run(self):
pass
def test_workflow_defn_non_async_run():
with pytest.raises(ValueError) as err:
# assert-type-error-pyright: 'Argument .+ cannot be assigned to parameter "fn"'
workflow.run(NonAsyncRun.run) # type: ignore
assert "must be an async function" in str(err.value)
class BaseWithRun:
@workflow.run
async def run(self):
pass
class RunOnlyOnBase(BaseWithRun):
pass
def test_workflow_defn_run_only_on_base():
with pytest.raises(ValueError) as err:
workflow.defn(RunOnlyOnBase)
assert "@workflow.run method run must be defined on RunOnlyOnBase" in str(err.value)
class RunWithoutDecoratorOnOverride(BaseWithRun):
async def run(self):
pass
def test_workflow_defn_run_override_without_decorator():
with pytest.raises(ValueError) as err:
workflow.defn(RunWithoutDecoratorOnOverride)
assert "@workflow.run defined on BaseWithRun.run but not on the override" in str(
err.value
)
class MultipleRun:
@workflow.run
async def run1(self):
pass
@workflow.run
async def run2(self):
pass
def test_workflow_defn_multiple_run():
with pytest.raises(ValueError) as err:
workflow.defn(MultipleRun)
assert "Multiple @workflow.run methods found (at least on run2 and run1" in str(
err.value
)
@workflow.defn
class BadDynamic:
@workflow.run
async def run(self):
pass
# We intentionally don't decorate these here since they throw
def some_dynamic1(self):
pass
def some_dynamic2(self, no_vararg): # type: ignore[reportMissingParameterType]
pass
def old_dynamic(self, name, *args): # type: ignore[reportMissingParameterType]
pass
def test_workflow_defn_bad_dynamic():
with pytest.raises(RuntimeError) as err:
workflow.signal(dynamic=True)(BadDynamic.some_dynamic1)
assert "must have 3 arguments" in str(err.value)
with pytest.raises(RuntimeError) as err:
workflow.signal(dynamic=True)(BadDynamic.some_dynamic2)
assert "must have 3 arguments" in str(err.value)
with pytest.raises(RuntimeError) as err:
workflow.query(dynamic=True)(BadDynamic.some_dynamic1)
assert "must have 3 arguments" in str(err.value)
with pytest.raises(RuntimeError) as err:
workflow.query(dynamic=True)(BadDynamic.some_dynamic2)
assert "must have 3 arguments" in str(err.value)
def test_workflow_defn_dynamic_handler_warnings():
with pytest.deprecated_call() as warnings:
workflow.signal(dynamic=True)(BadDynamic.old_dynamic)
workflow.query(dynamic=True)(BadDynamic.old_dynamic)
assert len(warnings) == 2
# We want to make sure they are reporting the right stacklevel
warnings[0].filename.endswith("test_workflow.py")
warnings[1].filename.endswith("test_workflow.py")
class _TestParametersIdenticalUpToNaming:
def a1(self, a): # type: ignore[reportMissingParameterType]
pass
def a2(self, b): # type: ignore[reportMissingParameterType]
pass
def b1(self, _a: int):
pass
def b2(self, _b: int) -> str:
return ""
def c1(self, _a1: int, _a2: str) -> str:
return ""
def c2(self, _b1: int, _b2: str) -> int:
return 0
def d1(self, _a1, _a2: str) -> None: # type: ignore[reportMissingParameterType]
pass
def d2(self, _b1, _b2: str) -> str: # type: ignore[reportMissingParameterType]
return ""
def e1(self, _a1, _a2: str = "") -> None: # type: ignore[reportMissingParameterType]
return None
def e2(self, _b1, _b2: str = "") -> str: # type: ignore[reportMissingParameterType]
return ""
def f1(self, _a1, _a2: str = "a") -> None: # type: ignore[reportMissingParameterType]
return None
def test_parameters_identical_up_to_naming():
fns = [
f
for _, f in inspect.getmembers(_TestParametersIdenticalUpToNaming)
if inspect.isfunction(f)
]
for f1, f2 in itertools.combinations(fns, 2):
name1, name2 = f1.__name__, f2.__name__
expect_equal = name1[0] == name2[0]
assert workflow._parameters_identical_up_to_naming(f1, f2) == (expect_equal), (
f"expected {name1} and {name2} parameters{' ' if expect_equal else ' not '}to compare equal"
)
@workflow.defn
class BadWorkflowInit:
def not__init__(self):
pass
@workflow.run
async def run(self):
pass
def test_workflow_init_not__init__():
with pytest.raises(ValueError) as err:
workflow.init(BadWorkflowInit.not__init__)
assert "@workflow.init may only be used on the __init__ method" in str(err.value)
class BadUpdateValidator:
@workflow.update
def my_update(self, _a: str):
pass
# assert-type-error-pyright: "Argument of type .+ cannot be assigned to parameter"
@my_update.validator # type: ignore
def my_validator(self, _a: int):
pass
@workflow.run
async def run(self):
pass
def test_workflow_update_validator_not_update():
with pytest.raises(ValueError) as err:
workflow.defn(BadUpdateValidator)
assert (
"Update validator method my_validator parameters do not match update method my_update parameters"
in str(err.value)
)
def _assert_config_function_parity(
function_obj: Callable[..., Any],
config_class: type[Any],
excluded_params: set[str],
) -> None:
config_name = config_class.__name__
# Get the signature and type hints
function_sig = inspect.signature(function_obj)
config_hints = get_type_hints(config_class)
# Get parameter names from function (excluding excluded ones and applying mappings)
expected_config_params = {
name for name in function_sig.parameters.keys() if name not in excluded_params
}
# Get parameter names from config
actual_config_params = {
name for name in config_hints.keys() if name not in excluded_params
}
# Check for missing and extra parameters
missing_in_config = expected_config_params - actual_config_params
extra_in_config = actual_config_params - expected_config_params
# Build detailed error message if there are mismatches
if missing_in_config or extra_in_config:
error_parts = []
if missing_in_config:
error_parts.append(
f"{config_name} is missing parameters: {sorted(missing_in_config)}"
)
if extra_in_config:
error_parts.append(
f"{config_name} has extra parameters: {sorted(extra_in_config)}"
)
error_message = "; ".join(error_parts)
error_message += f"\nExpected: {sorted(expected_config_params)}\nActual: {sorted(actual_config_params)}"
assert False, error_message
async def test_activity_config_parity_with_execute_activity():
"""Test that ActivityConfig has all the same parameters as execute_activity."""
_assert_config_function_parity(
workflow.execute_activity,
workflow.ActivityConfig,
excluded_params={"activity", "arg", "args", "result_type"},
)
with pytest.raises(workflow._NotInWorkflowEventLoopError):
await workflow.execute_activity("activity", **workflow.ActivityConfig())
def test_activity_config_parity_with_start_activity():
"""Test that ActivityConfig has all the same parameters as start_activity."""
_assert_config_function_parity(
workflow.start_activity,
workflow.ActivityConfig,
excluded_params={"activity", "arg", "args", "result_type"},
)
with pytest.raises(workflow._NotInWorkflowEventLoopError):
workflow.start_activity("workflow", **workflow.ActivityConfig())
async def test_child_workflow_config_parity_with_execute_child_workflow():
"""Test that ChildWorkflowConfig has all the same parameters as execute_child_workflow."""
_assert_config_function_parity(
workflow.execute_child_workflow,
workflow.ChildWorkflowConfig,
excluded_params={"workflow", "arg", "args", "result_type"},
)
with pytest.raises(workflow._NotInWorkflowEventLoopError):
await workflow.execute_child_workflow(
"workflow", **workflow.ChildWorkflowConfig()
)
async def test_child_workflow_config_parity_with_start_child_workflow():
"""Test that ChildWorkflowConfig has all the same parameters as start_child_workflow."""
_assert_config_function_parity(
workflow.start_child_workflow,
workflow.ChildWorkflowConfig,
excluded_params={
"workflow",
"arg",
"args",
"result_type",
},
)
with pytest.raises(workflow._NotInWorkflowEventLoopError):
await workflow.start_child_workflow(
"workflow", **workflow.ChildWorkflowConfig()
)