File: test_workflow_execution.py

package info (click to toggle)
python-moto 5.1.18-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 116,520 kB
  • sloc: python: 636,725; javascript: 181; makefile: 39; sh: 3
file content (691 lines) | stat: -rw-r--r-- 24,608 bytes parent folder | download | duplicates (2)
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
import re
from threading import Timer as ThreadingTimer
from time import sleep
from unittest.mock import Mock, patch

import pytest
from freezegun import freeze_time

from moto.swf.exceptions import SWFDefaultUndefinedFault
from moto.swf.models import (
    ActivityType,
    Timeout,
    Timer,
    WorkflowExecution,
    WorkflowType,
)

from ..utils import (
    auto_start_decision_tasks,
    get_basic_domain,
    get_basic_workflow_type,
    make_workflow_execution,
)

VALID_ACTIVITY_TASK_ATTRIBUTES = {
    "activityId": "my-activity-001",
    "activityType": {"name": "test-activity", "version": "v1.1"},
    "taskList": {"name": "task-list-name"},
    "scheduleToStartTimeout": "600",
    "scheduleToCloseTimeout": "600",
    "startToCloseTimeout": "600",
    "heartbeatTimeout": "300",
}


def test_workflow_execution_creation():
    domain = get_basic_domain()
    wft = get_basic_workflow_type()
    wfe = WorkflowExecution(domain, wft, "ab1234", child_policy="TERMINATE")

    assert wfe.domain == domain
    assert wfe.workflow_type == wft
    assert wfe.child_policy == "TERMINATE"


def test_workflow_execution_creation_child_policy_logic():
    domain = get_basic_domain()

    assert (
        WorkflowExecution(
            domain,
            WorkflowType(
                "test-workflow",
                "v1.0",
                task_list="queue",
                default_child_policy="ABANDON",
                default_execution_start_to_close_timeout="300",
                default_task_start_to_close_timeout="300",
            ),
            "ab1234",
        ).child_policy
        == "ABANDON"
    )

    assert (
        WorkflowExecution(
            domain,
            WorkflowType(
                "test-workflow",
                "v1.0",
                task_list="queue",
                default_execution_start_to_close_timeout="300",
                default_task_start_to_close_timeout="300",
            ),
            "ab1234",
            child_policy="REQUEST_CANCEL",
        ).child_policy
        == "REQUEST_CANCEL"
    )

    with pytest.raises(SWFDefaultUndefinedFault):
        WorkflowExecution(domain, WorkflowType("test-workflow", "v1.0"), "ab1234")


def test_workflow_execution_string_representation():
    wfe = make_workflow_execution(child_policy="TERMINATE")
    assert re.match(r"^WorkflowExecution\(run_id: .*\)", str(wfe))


def test_workflow_execution_generates_a_random_run_id():
    domain = get_basic_domain()
    wft = get_basic_workflow_type()
    wfe1 = WorkflowExecution(domain, wft, "ab1234", child_policy="TERMINATE")
    wfe2 = WorkflowExecution(domain, wft, "ab1235", child_policy="TERMINATE")
    assert wfe1.run_id != wfe2.run_id


def test_workflow_execution_short_dict_representation():
    domain = get_basic_domain()
    wf_type = WorkflowType(
        "test-workflow",
        "v1.0",
        task_list="queue",
        default_child_policy="ABANDON",
        default_execution_start_to_close_timeout="300",
        default_task_start_to_close_timeout="300",
    )
    wfe = WorkflowExecution(domain, wf_type, "ab1234")

    sd = wfe.to_short_dict()
    assert sd["workflowId"] == "ab1234"
    assert "runId" in sd


def test_workflow_execution_medium_dict_representation():
    domain = get_basic_domain()
    wf_type = WorkflowType(
        "test-workflow",
        "v1.0",
        task_list="queue",
        default_child_policy="ABANDON",
        default_execution_start_to_close_timeout="300",
        default_task_start_to_close_timeout="300",
    )
    wfe = WorkflowExecution(domain, wf_type, "ab1234")

    md = wfe.to_medium_dict()
    assert md["execution"] == wfe.to_short_dict()
    assert md["workflowType"] == wf_type.to_short_dict()
    assert isinstance(md["startTimestamp"], float)
    assert md["executionStatus"] == "OPEN"
    assert md["cancelRequested"] is False
    assert "tagList" not in md

    wfe.tag_list = ["foo", "bar", "baz"]
    md = wfe.to_medium_dict()
    assert md["tagList"] == ["foo", "bar", "baz"]


def test_workflow_execution_full_dict_representation():
    domain = get_basic_domain()
    wf_type = WorkflowType(
        "test-workflow",
        "v1.0",
        task_list="queue",
        default_child_policy="ABANDON",
        default_execution_start_to_close_timeout="300",
        default_task_start_to_close_timeout="300",
    )
    wfe = WorkflowExecution(domain, wf_type, "ab1234")

    fd = wfe.to_full_dict()
    assert fd["executionInfo"] == wfe.to_medium_dict()
    assert fd["openCounts"]["openTimers"] == 0
    assert fd["openCounts"]["openDecisionTasks"] == 0
    assert fd["openCounts"]["openActivityTasks"] == 0
    assert fd["executionConfiguration"] == {
        "childPolicy": "ABANDON",
        "executionStartToCloseTimeout": "300",
        "taskList": {"name": "queue"},
        "taskStartToCloseTimeout": "300",
    }


def test_closed_workflow_execution_full_dict_representation():
    domain = get_basic_domain()
    wf_type = WorkflowType(
        "test-workflow",
        "v1.0",
        task_list="queue",
        default_child_policy="ABANDON",
        default_execution_start_to_close_timeout="300",
        default_task_start_to_close_timeout="300",
    )
    wfe = WorkflowExecution(domain, wf_type, "ab1234")
    wfe.execution_status = "CLOSED"
    wfe.close_status = "CANCELED"
    wfe.close_timestamp = 1420066801.123

    fd = wfe.to_full_dict()
    medium_dict = wfe.to_medium_dict()
    medium_dict["closeStatus"] = "CANCELED"
    medium_dict["closeTimestamp"] = 1420066801.123
    assert fd["executionInfo"] == medium_dict
    assert fd["openCounts"]["openTimers"] == 0
    assert fd["openCounts"]["openDecisionTasks"] == 0
    assert fd["openCounts"]["openActivityTasks"] == 0
    assert fd["executionConfiguration"] == {
        "childPolicy": "ABANDON",
        "executionStartToCloseTimeout": "300",
        "taskList": {"name": "queue"},
        "taskStartToCloseTimeout": "300",
    }


def test_workflow_execution_list_dict_representation():
    domain = get_basic_domain()
    wf_type = WorkflowType(
        "test-workflow",
        "v1.0",
        task_list="queue",
        default_child_policy="ABANDON",
        default_execution_start_to_close_timeout="300",
        default_task_start_to_close_timeout="300",
    )
    wfe = WorkflowExecution(domain, wf_type, "ab1234")

    ld = wfe.to_list_dict()
    assert ld["workflowType"]["version"] == "v1.0"
    assert ld["workflowType"]["name"] == "test-workflow"
    assert ld["executionStatus"] == "OPEN"
    assert ld["execution"]["workflowId"] == "ab1234"
    assert "runId" in ld["execution"]
    assert ld["cancelRequested"] is False
    assert "startTimestamp" in ld


def test_workflow_execution_schedule_decision_task():
    wfe = make_workflow_execution()
    assert wfe.open_counts["openDecisionTasks"] == 0
    wfe.schedule_decision_task()
    assert wfe.open_counts["openDecisionTasks"] == 1


def test_workflow_execution_dont_schedule_decision_if_existing_started_and_other_scheduled():
    wfe = make_workflow_execution()
    assert wfe.open_counts["openDecisionTasks"] == 0

    wfe.schedule_decision_task()
    assert wfe.open_counts["openDecisionTasks"] == 1

    wfe.decision_tasks[0].start("evt_id")

    wfe.schedule_decision_task()
    wfe.schedule_decision_task()
    assert wfe.open_counts["openDecisionTasks"] == 2


def test_workflow_execution_schedule_decision_if_existing_started_and_no_other_scheduled():
    wfe = make_workflow_execution()
    assert wfe.open_counts["openDecisionTasks"] == 0

    wfe.schedule_decision_task()
    assert wfe.open_counts["openDecisionTasks"] == 1

    wfe.decision_tasks[0].start("evt_id")

    wfe.schedule_decision_task()
    assert wfe.open_counts["openDecisionTasks"] == 2


def test_workflow_execution_start_decision_task():
    wfe = make_workflow_execution()
    wfe.schedule_decision_task()
    dt = wfe.decision_tasks[0]
    wfe.start_decision_task(dt.task_token, identity="srv01")
    dt = wfe.decision_tasks[0]
    assert dt.state == "STARTED"
    assert wfe.events()[-1].event_type == "DecisionTaskStarted"
    assert wfe.events()[-1].event_attributes["identity"] == "srv01"


def test_workflow_execution_history_events_ids():
    wfe = make_workflow_execution()
    wfe._add_event("WorkflowExecutionStarted")
    wfe._add_event("DecisionTaskScheduled")
    wfe._add_event("DecisionTaskStarted")
    ids = [evt.event_id for evt in wfe.events()]
    assert ids == [1, 2, 3]


@freeze_time("2015-01-01 12:00:00")
def test_workflow_execution_start():
    wfe = make_workflow_execution()
    assert wfe.events() == []

    wfe.start()
    assert wfe.start_timestamp == 1420113600.0
    assert len(wfe.events()) == 2
    assert wfe.events()[0].event_type == "WorkflowExecutionStarted"
    assert wfe.events()[1].event_type == "DecisionTaskScheduled"


@freeze_time("2015-01-02 12:00:00")
def test_workflow_execution_complete():
    wfe = make_workflow_execution()
    wfe.complete(123, result="foo")

    assert wfe.execution_status == "CLOSED"
    assert wfe.close_status == "COMPLETED"
    assert wfe.close_timestamp == 1420200000.0
    assert wfe.events()[-1].event_type == "WorkflowExecutionCompleted"
    assert wfe.events()[-1].event_attributes["decisionTaskCompletedEventId"] == 123
    assert wfe.events()[-1].event_attributes["result"] == "foo"


@freeze_time("2015-01-02 12:00:00")
def test_workflow_execution_fail():
    wfe = make_workflow_execution()
    wfe.fail(123, details="some details", reason="my rules")

    assert wfe.execution_status == "CLOSED"
    assert wfe.close_status == "FAILED"
    assert wfe.close_timestamp == 1420200000.0
    assert wfe.events()[-1].event_type == "WorkflowExecutionFailed"
    assert wfe.events()[-1].event_attributes["decisionTaskCompletedEventId"] == 123
    assert wfe.events()[-1].event_attributes["details"] == "some details"
    assert wfe.events()[-1].event_attributes["reason"] == "my rules"


@freeze_time("2015-01-01 12:00:00")
def test_workflow_execution_schedule_activity_task():
    wfe = make_workflow_execution()
    assert wfe.latest_activity_task_timestamp is None

    wfe.schedule_activity_task(123, VALID_ACTIVITY_TASK_ATTRIBUTES)

    assert wfe.latest_activity_task_timestamp == 1420113600.0

    assert wfe.open_counts["openActivityTasks"] == 1
    last_event = wfe.events()[-1]
    assert last_event.event_type == "ActivityTaskScheduled"
    assert last_event.event_attributes["decisionTaskCompletedEventId"] == 123
    assert last_event.event_attributes["taskList"]["name"] == "task-list-name"

    assert len(wfe.activity_tasks) == 1
    task = wfe.activity_tasks[0]
    assert task.activity_id == "my-activity-001"
    assert task.activity_type.name == "test-activity"
    assert task in wfe.domain.activity_task_lists["task-list-name"]


def test_workflow_execution_schedule_activity_task_without_task_list_should_take_default():
    wfe = make_workflow_execution()
    wfe.domain.add_type(ActivityType("test-activity", "v1.2", task_list="foobar"))
    wfe.schedule_activity_task(
        123,
        {
            "activityId": "my-activity-001",
            "activityType": {"name": "test-activity", "version": "v1.2"},
            "scheduleToStartTimeout": "600",
            "scheduleToCloseTimeout": "600",
            "startToCloseTimeout": "600",
            "heartbeatTimeout": "300",
        },
    )

    assert wfe.open_counts["openActivityTasks"] == 1
    last_event = wfe.events()[-1]
    assert last_event.event_type == "ActivityTaskScheduled"
    assert last_event.event_attributes["taskList"]["name"] == "foobar"

    task = wfe.activity_tasks[0]
    assert task in wfe.domain.activity_task_lists["foobar"]


def test_workflow_execution_schedule_activity_task_should_fail_if_wrong_attributes():
    wfe = make_workflow_execution()
    at = ActivityType("test-activity", "v1.1")
    at.status = "DEPRECATED"
    wfe.domain.add_type(at)
    wfe.domain.add_type(ActivityType("test-activity", "v1.2"))

    hsh = {
        "activityId": "my-activity-001",
        "activityType": {"name": "test-activity-does-not-exists", "version": "v1.1"},
    }

    wfe.schedule_activity_task(123, hsh)
    last_event = wfe.events()[-1]
    assert last_event.event_type == "ScheduleActivityTaskFailed"
    assert last_event.event_attributes["cause"] == "ACTIVITY_TYPE_DOES_NOT_EXIST"

    hsh["activityType"]["name"] = "test-activity"
    wfe.schedule_activity_task(123, hsh)
    last_event = wfe.events()[-1]
    assert last_event.event_type == "ScheduleActivityTaskFailed"
    assert last_event.event_attributes["cause"] == "ACTIVITY_TYPE_DEPRECATED"

    hsh["activityType"]["version"] = "v1.2"
    wfe.schedule_activity_task(123, hsh)
    last_event = wfe.events()[-1]
    assert last_event.event_type == "ScheduleActivityTaskFailed"
    assert last_event.event_attributes["cause"] == "DEFAULT_TASK_LIST_UNDEFINED"

    hsh["taskList"] = {"name": "foobar"}
    wfe.schedule_activity_task(123, hsh)
    last_event = wfe.events()[-1]
    assert last_event.event_type == "ScheduleActivityTaskFailed"
    assert last_event.event_attributes["cause"] == (
        "DEFAULT_SCHEDULE_TO_START_TIMEOUT_UNDEFINED"
    )

    hsh["scheduleToStartTimeout"] = "600"
    wfe.schedule_activity_task(123, hsh)
    last_event = wfe.events()[-1]
    assert last_event.event_type == "ScheduleActivityTaskFailed"
    assert last_event.event_attributes["cause"] == (
        "DEFAULT_SCHEDULE_TO_CLOSE_TIMEOUT_UNDEFINED"
    )

    hsh["scheduleToCloseTimeout"] = "600"
    wfe.schedule_activity_task(123, hsh)
    last_event = wfe.events()[-1]
    assert last_event.event_type == "ScheduleActivityTaskFailed"
    assert last_event.event_attributes["cause"] == (
        "DEFAULT_START_TO_CLOSE_TIMEOUT_UNDEFINED"
    )

    hsh["startToCloseTimeout"] = "600"
    wfe.schedule_activity_task(123, hsh)
    last_event = wfe.events()[-1]
    assert last_event.event_type == "ScheduleActivityTaskFailed"
    assert last_event.event_attributes["cause"] == (
        "DEFAULT_HEARTBEAT_TIMEOUT_UNDEFINED"
    )

    assert wfe.open_counts["openActivityTasks"] == 0
    assert len(wfe.activity_tasks) == 0
    assert len(wfe.domain.activity_task_lists) == 0

    hsh["heartbeatTimeout"] = "300"
    wfe.schedule_activity_task(123, hsh)
    last_event = wfe.events()[-1]
    assert last_event.event_type == "ActivityTaskScheduled"

    task = wfe.activity_tasks[0]
    assert task in wfe.domain.activity_task_lists["foobar"]
    assert wfe.open_counts["openDecisionTasks"] == 0
    assert wfe.open_counts["openActivityTasks"] == 1


def test_workflow_execution_schedule_activity_task_failure_triggers_new_decision():
    wfe = make_workflow_execution()
    wfe.start()
    task_token = wfe.decision_tasks[-1].task_token
    wfe.start_decision_task(task_token)
    wfe.complete_decision_task(
        task_token,
        execution_context="free-form execution context",
        decisions=[
            {
                "decisionType": "ScheduleActivityTask",
                "scheduleActivityTaskDecisionAttributes": {
                    "activityId": "my-activity-001",
                    "activityType": {
                        "name": "test-activity-does-not-exist",
                        "version": "v1.2",
                    },
                },
            },
            {
                "decisionType": "ScheduleActivityTask",
                "scheduleActivityTaskDecisionAttributes": {
                    "activityId": "my-activity-001",
                    "activityType": {
                        "name": "test-activity-does-not-exist",
                        "version": "v1.2",
                    },
                },
            },
        ],
    )

    assert wfe.latest_execution_context == "free-form execution context"
    assert wfe.open_counts["openActivityTasks"] == 0
    assert wfe.open_counts["openDecisionTasks"] == 1
    last_events = wfe.events()[-3:]
    assert last_events[0].event_type == "ScheduleActivityTaskFailed"
    assert last_events[1].event_type == "ScheduleActivityTaskFailed"
    assert last_events[2].event_type == "DecisionTaskScheduled"


def test_workflow_execution_schedule_activity_task_with_same_activity_id():
    wfe = make_workflow_execution()

    wfe.schedule_activity_task(123, VALID_ACTIVITY_TASK_ATTRIBUTES)
    assert wfe.open_counts["openActivityTasks"] == 1
    last_event = wfe.events()[-1]
    assert last_event.event_type == "ActivityTaskScheduled"

    wfe.schedule_activity_task(123, VALID_ACTIVITY_TASK_ATTRIBUTES)
    assert wfe.open_counts["openActivityTasks"] == 1
    last_event = wfe.events()[-1]
    assert last_event.event_type == "ScheduleActivityTaskFailed"
    assert last_event.event_attributes["cause"] == "ACTIVITY_ID_ALREADY_IN_USE"


def test_workflow_execution_start_activity_task():
    wfe = make_workflow_execution()
    wfe.schedule_activity_task(123, VALID_ACTIVITY_TASK_ATTRIBUTES)
    task_token = wfe.activity_tasks[-1].task_token
    wfe.start_activity_task(task_token, identity="worker01")
    task = wfe.activity_tasks[-1]
    assert task.state == "STARTED"
    assert wfe.events()[-1].event_type == "ActivityTaskStarted"
    assert wfe.events()[-1].event_attributes["identity"] == "worker01"


def test_complete_activity_task():
    wfe = make_workflow_execution()
    wfe.schedule_activity_task(123, VALID_ACTIVITY_TASK_ATTRIBUTES)
    task_token = wfe.activity_tasks[-1].task_token

    assert wfe.open_counts["openActivityTasks"] == 1
    assert wfe.open_counts["openDecisionTasks"] == 0

    wfe.start_activity_task(task_token, identity="worker01")
    wfe.complete_activity_task(task_token, result="a superb result")

    task = wfe.activity_tasks[-1]
    assert task.state == "COMPLETED"
    assert wfe.events()[-2].event_type == "ActivityTaskCompleted"
    assert wfe.events()[-1].event_type == "DecisionTaskScheduled"

    assert wfe.open_counts["openActivityTasks"] == 0
    assert wfe.open_counts["openDecisionTasks"] == 1


def test_terminate():
    wfe = make_workflow_execution()
    wfe.schedule_decision_task()
    wfe.terminate()

    assert wfe.execution_status == "CLOSED"
    assert wfe.close_status == "TERMINATED"
    assert wfe.close_cause == "OPERATOR_INITIATED"
    assert wfe.open_counts["openDecisionTasks"] == 1

    last_event = wfe.events()[-1]
    assert last_event.event_type == "WorkflowExecutionTerminated"
    # take default child_policy if not provided (as here)
    assert last_event.event_attributes["childPolicy"] == "ABANDON"


def test_first_timeout():
    wfe = make_workflow_execution()
    assert wfe.first_timeout() is None

    with freeze_time("2015-01-01 12:00:00"):
        wfe.start()
        assert wfe.first_timeout() is None

    with freeze_time("2015-01-01 14:01"):
        # 2 hours timeout reached
        assert isinstance(wfe.first_timeout(), Timeout)


# See moto/swf/models/workflow_execution.py "_process_timeouts()" for more
# details
def test_timeouts_are_processed_in_order_and_reevaluated():
    # Let's make a Workflow Execution with the following properties:
    # - execution start to close timeout of 8 mins
    # - (decision) task start to close timeout of 5 mins
    #
    # Now start the workflow execution, and look at the history 15 mins later:
    # - a first decision task is fired just after workflow execution start
    # - the first decision task should have timed out after 5 mins
    # - that fires a new decision task (which we hack to start automatically)
    # - then the workflow timeouts after 8 mins (shows gradual reevaluation)
    # - but the last scheduled decision task should *not* timeout (workflow closed)
    with freeze_time("2015-01-01 12:00:00"):
        wfe = make_workflow_execution(
            execution_start_to_close_timeout=8 * 60, task_start_to_close_timeout=5 * 60
        )
        # decision will automatically start
        wfe = auto_start_decision_tasks(wfe)
        wfe.start()
        event_idx = len(wfe.events())

    with freeze_time("2015-01-01 12:08:00"):
        wfe._process_timeouts()

        event_types = [e.event_type for e in wfe.events()[event_idx:]]
        assert event_types == [
            "DecisionTaskTimedOut",
            "DecisionTaskScheduled",
            "DecisionTaskStarted",
            "WorkflowExecutionTimedOut",
        ]


def test_record_marker():
    wfe = make_workflow_execution()
    MARKER_EVENT_ATTRIBUTES = {"markerName": "example_marker"}

    wfe.record_marker(123, MARKER_EVENT_ATTRIBUTES)

    last_event = wfe.events()[-1]
    assert last_event.event_type == "MarkerRecorded"
    assert last_event.event_attributes["markerName"] == "example_marker"
    assert last_event.event_attributes["decisionTaskCompletedEventId"] == 123


def test_start_timer():
    wfe = make_workflow_execution()
    START_TIMER_EVENT_ATTRIBUTES = {"startToFireTimeout": "10", "timerId": "abc123"}
    with patch("moto.swf.models.workflow_execution.ThreadingTimer"):
        wfe.start_timer(123, START_TIMER_EVENT_ATTRIBUTES)

        last_event = wfe.events()[-1]
        assert last_event.event_type == "TimerStarted"
        assert last_event.event_attributes["startToFireTimeout"] == "10"
        assert last_event.event_attributes["timerId"] == "abc123"
        assert last_event.event_attributes["decisionTaskCompletedEventId"] == 123


def test_start_timer_correctly_fires_timer_later():
    wfe = make_workflow_execution()
    START_TIMER_EVENT_ATTRIBUTES = {"startToFireTimeout": "60", "timerId": "abc123"}

    # Patch thread's event with one that immediately resolves
    with patch("threading.Event.wait"):
        wfe.start_timer(123, START_TIMER_EVENT_ATTRIBUTES)
        # Small wait to let both events populate
        sleep(0.5)

        second_to_last_event = wfe.events()[-2]
        last_event = wfe.events()[-1]
        assert second_to_last_event.event_type == "TimerFired"
        assert second_to_last_event.event_attributes["timerId"] == "abc123"
        assert second_to_last_event.event_attributes["startedEventId"] == 1
        assert last_event.event_type == "DecisionTaskScheduled"


def test_start_timer_fails_if_timer_already_started():
    wfe = make_workflow_execution()
    existing_timer = Mock(spec=ThreadingTimer)
    existing_timer.is_alive.return_value = True
    wfe._timers["abc123"] = Timer(existing_timer, 1)
    START_TIMER_EVENT_ATTRIBUTES = {"startToFireTimeout": "10", "timerId": "abc123"}

    wfe.start_timer(123, START_TIMER_EVENT_ATTRIBUTES)

    last_event = wfe.events()[-1]
    assert last_event.event_type == "StartTimerFailed"
    assert last_event.event_attributes["cause"] == "TIMER_ID_ALREADY_IN_USE"
    assert last_event.event_attributes["timerId"] == "abc123"
    assert last_event.event_attributes["decisionTaskCompletedEventId"] == 123


def test_cancel_timer():
    wfe = make_workflow_execution()
    existing_timer = Mock(spec=ThreadingTimer)
    existing_timer.is_alive.return_value = True
    wfe._timers["abc123"] = Timer(existing_timer, 1)

    wfe.cancel_timer(123, "abc123")

    last_event = wfe.events()[-1]
    assert last_event.event_type == "TimerCancelled"
    assert last_event.event_attributes["startedEventId"] == 1
    assert last_event.event_attributes["timerId"] == "abc123"
    assert last_event.event_attributes["decisionTaskCompletedEventId"] == 123
    existing_timer.cancel.assert_called_once()
    assert not wfe._timers.get("abc123")


def test_cancel_timer_fails_if_timer_not_found():
    wfe = make_workflow_execution()

    wfe.cancel_timer(123, "abc123")

    last_event = wfe.events()[-1]
    assert last_event.event_type == "CancelTimerFailed"
    assert last_event.event_attributes["cause"] == "TIMER_ID_UNKNOWN"
    assert last_event.event_attributes["decisionTaskCompletedEventId"] == 123


def test_cancel_workflow():
    wfe = make_workflow_execution()
    wfe.open_counts["openDecisionTasks"] = 1

    wfe.cancel(123, "I want to cancel")

    last_event = wfe.events()[-1]
    assert last_event.event_type == "WorkflowExecutionCanceled"
    assert last_event.event_attributes["details"] == "I want to cancel"
    assert last_event.event_attributes["decisionTaskCompletedEventId"] == 123


def test_cancel_workflow_fails_if_open_decision():
    wfe = make_workflow_execution()
    wfe.open_counts["openDecisionTasks"] = 2

    wfe.cancel(123, "I want to cancel")

    last_event = wfe.events()[-1]
    assert last_event.event_type == "CancelWorkflowExecutionFailed"
    assert last_event.event_attributes["cause"] == "UNHANDLED_DECISION"
    assert last_event.event_attributes["decisionTaskCompletedEventId"] == 123