Techdebt: Replace sure with regular assertions in SWF (#6638)

This commit is contained in:
kbalk 2023-08-12 03:59:33 -04:00 committed by GitHub
parent 1626c35ac5
commit c8b5470e25
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 1068 additions and 1100 deletions

View File

@ -1,5 +1,7 @@
import re
from freezegun import freeze_time from freezegun import freeze_time
import sure # noqa # pylint: disable=unused-import import pytest
from moto.swf.exceptions import SWFWorkflowExecutionClosedError from moto.swf.exceptions import SWFWorkflowExecutionClosedError
from moto.swf.models import ActivityTask, ActivityType, Timeout from moto.swf.models import ActivityTask, ActivityType, Timeout
@ -21,23 +23,23 @@ def test_activity_task_creation():
workflow_execution=wfe, workflow_execution=wfe,
timeouts=ACTIVITY_TASK_TIMEOUTS, timeouts=ACTIVITY_TASK_TIMEOUTS,
) )
task.workflow_execution.should.equal(wfe) assert task.workflow_execution == wfe
task.state.should.equal("SCHEDULED") assert task.state == "SCHEDULED"
task.task_token.should.match("[-a-z0-9]+") assert re.match("[-a-z0-9]+", task.task_token)
task.started_event_id.should.equal(None) assert task.started_event_id is None
task.start(123) task.start(123)
task.state.should.equal("STARTED") assert task.state == "STARTED"
task.started_event_id.should.equal(123) assert task.started_event_id == 123
task.complete() task.complete()
task.state.should.equal("COMPLETED") assert task.state == "COMPLETED"
# NB: this doesn't make any sense for SWF, a task shouldn't go from a # NB: this doesn't make any sense for SWF, a task shouldn't go from a
# "COMPLETED" state to a "FAILED" one, but this is an internal state on our # "COMPLETED" state to a "FAILED" one, but this is an internal state on our
# side and we don't care about invalid state transitions for now. # side and we don't care about invalid state transitions for now.
task.fail() task.fail()
task.state.should.equal("FAILED") assert task.state == "FAILED"
def test_activity_task_full_dict_representation(): def test_activity_task_full_dict_representation():
@ -53,16 +55,16 @@ def test_activity_task_full_dict_representation():
at.start(1234) at.start(1234)
fd = at.to_full_dict() fd = at.to_full_dict()
fd["activityId"].should.equal("my-activity-123") assert fd["activityId"] == "my-activity-123"
fd["activityType"]["version"].should.equal("v1.0") assert fd["activityType"]["version"] == "v1.0"
fd["input"].should.equal("optional") assert fd["input"] == "optional"
fd["startedEventId"].should.equal(1234) assert fd["startedEventId"] == 1234
fd.should.contain("taskToken") assert "taskToken" in fd
fd["workflowExecution"].should.equal(wfe.to_short_dict()) assert fd["workflowExecution"] == wfe.to_short_dict()
at.start(1234) at.start(1234)
fd = at.to_full_dict() fd = at.to_full_dict()
fd["startedEventId"].should.equal(1234) assert fd["startedEventId"] == 1234
def test_activity_task_reset_heartbeat_clock(): def test_activity_task_reset_heartbeat_clock():
@ -78,12 +80,12 @@ def test_activity_task_reset_heartbeat_clock():
workflow_execution=wfe, workflow_execution=wfe,
) )
task.last_heartbeat_timestamp.should.equal(1420113600.0) assert task.last_heartbeat_timestamp == 1420113600.0
with freeze_time("2015-01-01 13:00:00"): with freeze_time("2015-01-01 13:00:00"):
task.reset_heartbeat_clock() task.reset_heartbeat_clock()
task.last_heartbeat_timestamp.should.equal(1420117200.0) assert task.last_heartbeat_timestamp == 1420117200.0
def test_activity_task_first_timeout(): def test_activity_task_first_timeout():
@ -98,14 +100,14 @@ def test_activity_task_first_timeout():
timeouts=ACTIVITY_TASK_TIMEOUTS, timeouts=ACTIVITY_TASK_TIMEOUTS,
workflow_execution=wfe, workflow_execution=wfe,
) )
task.first_timeout().should.be.none assert task.first_timeout() is None
# activity task timeout is 300s == 5mins # activity task timeout is 300s == 5mins
with freeze_time("2015-01-01 12:06:00"): with freeze_time("2015-01-01 12:06:00"):
task.first_timeout().should.be.a(Timeout) assert isinstance(task.first_timeout(), Timeout)
process_first_timeout(task) process_first_timeout(task)
task.state.should.equal("TIMED_OUT") assert task.state == "TIMED_OUT"
task.timeout_type.should.equal("HEARTBEAT") assert task.timeout_type == "HEARTBEAT"
def test_activity_task_first_timeout_with_heartbeat_timeout_none(): def test_activity_task_first_timeout_with_heartbeat_timeout_none():
@ -123,7 +125,7 @@ def test_activity_task_first_timeout_with_heartbeat_timeout_none():
timeouts=activity_task_timeouts, timeouts=activity_task_timeouts,
workflow_execution=wfe, workflow_execution=wfe,
) )
task.first_timeout().should.be.none assert task.first_timeout() is None
def test_activity_task_cannot_timeout_on_closed_workflow_execution(): def test_activity_task_cannot_timeout_on_closed_workflow_execution():
@ -142,10 +144,10 @@ def test_activity_task_cannot_timeout_on_closed_workflow_execution():
) )
with freeze_time("2015-01-01 14:10:00"): with freeze_time("2015-01-01 14:10:00"):
task.first_timeout().should.be.a(Timeout) assert isinstance(task.first_timeout(), Timeout)
wfe.first_timeout().should.be.a(Timeout) assert isinstance(wfe.first_timeout(), Timeout)
process_first_timeout(wfe) process_first_timeout(wfe)
task.first_timeout().should.be.none assert task.first_timeout() is None
def test_activity_task_cannot_change_state_on_closed_workflow_execution(): def test_activity_task_cannot_change_state_on_closed_workflow_execution():
@ -162,8 +164,9 @@ def test_activity_task_cannot_change_state_on_closed_workflow_execution():
) )
wfe.complete(123) wfe.complete(123)
task.timeout.when.called_with(Timeout(task, 0, "foo")).should.throw( with pytest.raises(SWFWorkflowExecutionClosedError):
SWFWorkflowExecutionClosedError task.timeout(Timeout(task, 0, "foo"))
) with pytest.raises(SWFWorkflowExecutionClosedError):
task.complete.when.called_with().should.throw(SWFWorkflowExecutionClosedError) task.complete()
task.fail.when.called_with().should.throw(SWFWorkflowExecutionClosedError) with pytest.raises(SWFWorkflowExecutionClosedError):
task.fail()

View File

@ -1,4 +1,7 @@
import re
from freezegun import freeze_time from freezegun import freeze_time
import pytest
from moto.swf.models import DecisionTask, Timeout from moto.swf.models import DecisionTask, Timeout
from moto.swf.exceptions import SWFWorkflowExecutionClosedError from moto.swf.exceptions import SWFWorkflowExecutionClosedError
@ -9,10 +12,10 @@ from ..utils import make_workflow_execution, process_first_timeout
def test_decision_task_creation(): def test_decision_task_creation():
wfe = make_workflow_execution() wfe = make_workflow_execution()
dt = DecisionTask(wfe, 123) dt = DecisionTask(wfe, 123)
dt.workflow_execution.should.equal(wfe) assert dt.workflow_execution == wfe
dt.state.should.equal("SCHEDULED") assert dt.state == "SCHEDULED"
dt.task_token.should.match("[-a-z0-9]+") assert re.match("[-a-z0-9]+", dt.task_token)
dt.started_event_id.should.equal(None) assert dt.started_event_id is None
def test_decision_task_full_dict_representation(): def test_decision_task_full_dict_representation():
@ -21,34 +24,34 @@ def test_decision_task_full_dict_representation():
dt = DecisionTask(wfe, 123) dt = DecisionTask(wfe, 123)
fd = dt.to_full_dict() fd = dt.to_full_dict()
fd["events"].should.be.a("list") assert isinstance(fd["events"], list)
fd.should_not.contain("previousStartedEventId") assert "previousStartedEventId" not in fd
fd.should_not.contain("startedEventId") assert "startedEventId" not in fd
fd.should.contain("taskToken") assert "taskToken" in fd
fd["workflowExecution"].should.equal(wfe.to_short_dict()) assert fd["workflowExecution"] == wfe.to_short_dict()
fd["workflowType"].should.equal(wft.to_short_dict()) assert fd["workflowType"] == wft.to_short_dict()
dt.start(1234, 1230) dt.start(1234, 1230)
fd = dt.to_full_dict() fd = dt.to_full_dict()
fd["startedEventId"].should.equal(1234) assert fd["startedEventId"] == 1234
fd["previousStartedEventId"].should.equal(1230) assert fd["previousStartedEventId"] == 1230
def test_decision_task_first_timeout(): def test_decision_task_first_timeout():
wfe = make_workflow_execution() wfe = make_workflow_execution()
dt = DecisionTask(wfe, 123) dt = DecisionTask(wfe, 123)
dt.first_timeout().should.be.none assert dt.first_timeout() is None
with freeze_time("2015-01-01 12:00:00"): with freeze_time("2015-01-01 12:00:00"):
dt.start(1234) dt.start(1234)
dt.first_timeout().should.be.none assert dt.first_timeout() is None
# activity task timeout is 300s == 5mins # activity task timeout is 300s == 5mins
with freeze_time("2015-01-01 12:06:00"): with freeze_time("2015-01-01 12:06:00"):
dt.first_timeout().should.be.a(Timeout) assert isinstance(dt.first_timeout(), Timeout)
dt.complete() dt.complete()
dt.first_timeout().should.be.none assert dt.first_timeout() is None
def test_decision_task_cannot_timeout_on_closed_workflow_execution(): def test_decision_task_cannot_timeout_on_closed_workflow_execution():
@ -61,10 +64,10 @@ def test_decision_task_cannot_timeout_on_closed_workflow_execution():
dt.start(1234) dt.start(1234)
with freeze_time("2015-01-01 14:10:00"): with freeze_time("2015-01-01 14:10:00"):
dt.first_timeout().should.be.a(Timeout) assert isinstance(dt.first_timeout(), Timeout)
wfe.first_timeout().should.be.a(Timeout) assert isinstance(wfe.first_timeout(), Timeout)
process_first_timeout(wfe) process_first_timeout(wfe)
dt.first_timeout().should.be.none assert dt.first_timeout() is None
def test_decision_task_cannot_change_state_on_closed_workflow_execution(): def test_decision_task_cannot_change_state_on_closed_workflow_execution():
@ -74,7 +77,7 @@ def test_decision_task_cannot_change_state_on_closed_workflow_execution():
wfe.complete(123) wfe.complete(123)
task.timeout.when.called_with(Timeout(task, 0, "foo")).should.throw( with pytest.raises(SWFWorkflowExecutionClosedError):
SWFWorkflowExecutionClosedError task.timeout(Timeout(task, 0, "foo"))
) with pytest.raises(SWFWorkflowExecutionClosedError):
task.complete.when.called_with().should.throw(SWFWorkflowExecutionClosedError) task.complete()

View File

@ -1,112 +1,112 @@
from collections import namedtuple from collections import namedtuple
import sure # noqa # pylint: disable=unused-import
import pytest
from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID
from moto.swf.exceptions import SWFUnknownResourceFault from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID
from moto.swf.models import Domain from moto.swf.exceptions import SWFUnknownResourceFault
from moto.swf.models import Domain
TEST_REGION = "us-east-1"
# Fake WorkflowExecution for tests purposes TEST_REGION = "us-east-1"
WorkflowExecution = namedtuple( # Fake WorkflowExecution for tests purposes
"WorkflowExecution", ["workflow_id", "run_id", "execution_status", "open"] WorkflowExecution = namedtuple(
) "WorkflowExecution", ["workflow_id", "run_id", "execution_status", "open"]
)
def test_domain_short_dict_representation():
domain = Domain("foo", "52", ACCOUNT_ID, TEST_REGION) def test_domain_short_dict_representation():
domain.to_short_dict().should.equal( domain = Domain("foo", "52", ACCOUNT_ID, TEST_REGION)
{ assert domain.to_short_dict() == {
"name": "foo", "name": "foo",
"status": "REGISTERED", "status": "REGISTERED",
"arn": f"arn:aws:swf:{TEST_REGION}:{ACCOUNT_ID}:/domain/foo", "arn": f"arn:aws:swf:{TEST_REGION}:{ACCOUNT_ID}:/domain/foo",
} }
)
domain.description = "foo bar"
domain.description = "foo bar" assert domain.to_short_dict()["description"] == "foo bar"
domain.to_short_dict()["description"].should.equal("foo bar")
def test_domain_full_dict_representation():
def test_domain_full_dict_representation(): domain = Domain("foo", "52", ACCOUNT_ID, TEST_REGION)
domain = Domain("foo", "52", ACCOUNT_ID, TEST_REGION)
assert domain.to_full_dict()["domainInfo"] == domain.to_short_dict()
domain.to_full_dict()["domainInfo"].should.equal(domain.to_short_dict()) _config = domain.to_full_dict()["configuration"]
_config = domain.to_full_dict()["configuration"] assert _config["workflowExecutionRetentionPeriodInDays"] == "52"
_config["workflowExecutionRetentionPeriodInDays"].should.equal("52")
def test_domain_string_representation():
def test_domain_string_representation(): domain = Domain("my-domain", "60", ACCOUNT_ID, TEST_REGION)
domain = Domain("my-domain", "60", ACCOUNT_ID, TEST_REGION) assert str(domain) == "Domain(name: my-domain, status: REGISTERED)"
str(domain).should.equal("Domain(name: my-domain, status: REGISTERED)")
def test_domain_add_to_activity_task_list():
def test_domain_add_to_activity_task_list(): domain = Domain("my-domain", "60", ACCOUNT_ID, TEST_REGION)
domain = Domain("my-domain", "60", ACCOUNT_ID, TEST_REGION) domain.add_to_activity_task_list("foo", "bar")
domain.add_to_activity_task_list("foo", "bar") assert domain.activity_task_lists == {"foo": ["bar"]}
domain.activity_task_lists.should.equal({"foo": ["bar"]})
def test_domain_activity_tasks():
def test_domain_activity_tasks(): domain = Domain("my-domain", "60", ACCOUNT_ID, TEST_REGION)
domain = Domain("my-domain", "60", ACCOUNT_ID, TEST_REGION) domain.add_to_activity_task_list("foo", "bar")
domain.add_to_activity_task_list("foo", "bar") domain.add_to_activity_task_list("other", "baz")
domain.add_to_activity_task_list("other", "baz") assert sorted(domain.activity_tasks) == ["bar", "baz"]
sorted(domain.activity_tasks).should.equal(["bar", "baz"])
def test_domain_add_to_decision_task_list():
def test_domain_add_to_decision_task_list(): domain = Domain("my-domain", "60", ACCOUNT_ID, TEST_REGION)
domain = Domain("my-domain", "60", ACCOUNT_ID, TEST_REGION) domain.add_to_decision_task_list("foo", "bar")
domain.add_to_decision_task_list("foo", "bar") assert domain.decision_task_lists == {"foo": ["bar"]}
domain.decision_task_lists.should.equal({"foo": ["bar"]})
def test_domain_decision_tasks():
def test_domain_decision_tasks(): domain = Domain("my-domain", "60", ACCOUNT_ID, TEST_REGION)
domain = Domain("my-domain", "60", ACCOUNT_ID, TEST_REGION) domain.add_to_decision_task_list("foo", "bar")
domain.add_to_decision_task_list("foo", "bar") domain.add_to_decision_task_list("other", "baz")
domain.add_to_decision_task_list("other", "baz") assert sorted(domain.decision_tasks) == ["bar", "baz"]
sorted(domain.decision_tasks).should.equal(["bar", "baz"])
def test_domain_get_workflow_execution():
def test_domain_get_workflow_execution(): domain = Domain("my-domain", "60", ACCOUNT_ID, TEST_REGION)
domain = Domain("my-domain", "60", ACCOUNT_ID, TEST_REGION)
wfe1 = WorkflowExecution(
wfe1 = WorkflowExecution( workflow_id="wf-id-1", run_id="run-id-1", execution_status="OPEN", open=True
workflow_id="wf-id-1", run_id="run-id-1", execution_status="OPEN", open=True )
) wfe2 = WorkflowExecution(
wfe2 = WorkflowExecution( workflow_id="wf-id-1", run_id="run-id-2", execution_status="CLOSED", open=False
workflow_id="wf-id-1", run_id="run-id-2", execution_status="CLOSED", open=False )
) wfe3 = WorkflowExecution(
wfe3 = WorkflowExecution( workflow_id="wf-id-2", run_id="run-id-3", execution_status="OPEN", open=True
workflow_id="wf-id-2", run_id="run-id-3", execution_status="OPEN", open=True )
) wfe4 = WorkflowExecution(
wfe4 = WorkflowExecution( workflow_id="wf-id-3", run_id="run-id-4", execution_status="CLOSED", open=False
workflow_id="wf-id-3", run_id="run-id-4", execution_status="CLOSED", open=False )
) domain.workflow_executions = [wfe1, wfe2, wfe3, wfe4]
domain.workflow_executions = [wfe1, wfe2, wfe3, wfe4]
# get workflow execution through workflow_id and run_id
# get workflow execution through workflow_id and run_id assert domain.get_workflow_execution("wf-id-1", run_id="run-id-1") == wfe1
domain.get_workflow_execution("wf-id-1", run_id="run-id-1").should.equal(wfe1) assert domain.get_workflow_execution("wf-id-1", run_id="run-id-2") == wfe2
domain.get_workflow_execution("wf-id-1", run_id="run-id-2").should.equal(wfe2) assert domain.get_workflow_execution("wf-id-3", run_id="run-id-4") == wfe4
domain.get_workflow_execution("wf-id-3", run_id="run-id-4").should.equal(wfe4)
with pytest.raises(SWFUnknownResourceFault):
domain.get_workflow_execution.when.called_with( domain.get_workflow_execution("wf-id-1", run_id="non-existent")
"wf-id-1", run_id="non-existent"
).should.throw(SWFUnknownResourceFault) # get OPEN workflow execution by default if no run_id
assert domain.get_workflow_execution("wf-id-1") == wfe1
# get OPEN workflow execution by default if no run_id with pytest.raises(SWFUnknownResourceFault):
domain.get_workflow_execution("wf-id-1").should.equal(wfe1) domain.get_workflow_execution("wf-id-3")
domain.get_workflow_execution.when.called_with("wf-id-3").should.throw( with pytest.raises(SWFUnknownResourceFault):
SWFUnknownResourceFault domain.get_workflow_execution("wf-id-non-existent")
)
domain.get_workflow_execution.when.called_with("wf-id-non-existent").should.throw( # raise_if_closed attribute
SWFUnknownResourceFault assert (
) domain.get_workflow_execution(
"wf-id-1", run_id="run-id-1", raise_if_closed=True
# raise_if_closed attribute )
domain.get_workflow_execution( == wfe1
"wf-id-1", run_id="run-id-1", raise_if_closed=True )
).should.equal(wfe1) with pytest.raises(SWFUnknownResourceFault):
domain.get_workflow_execution.when.called_with( domain.get_workflow_execution(
"wf-id-3", run_id="run-id-4", raise_if_closed=True "wf-id-3", run_id="run-id-4", raise_if_closed=True
).should.throw(SWFUnknownResourceFault) )
# raise_if_none attribute # raise_if_none attribute
domain.get_workflow_execution("foo", raise_if_none=False).should.be.none assert domain.get_workflow_execution("foo", raise_if_none=False) is None

View File

@ -1,5 +1,4 @@
from moto.swf.models import GenericType from moto.swf.models import GenericType
import sure # noqa # pylint: disable=unused-import
# Tests for GenericType (ActivityType, WorkflowType) # Tests for GenericType (ActivityType, WorkflowType)
@ -15,44 +14,40 @@ class FooType(GenericType):
def test_type_short_dict_representation(): def test_type_short_dict_representation():
_type = FooType("test-foo", "v1.0") _type = FooType("test-foo", "v1.0")
_type.to_short_dict().should.equal({"name": "test-foo", "version": "v1.0"}) assert _type.to_short_dict() == {"name": "test-foo", "version": "v1.0"}
def test_type_medium_dict_representation(): def test_type_medium_dict_representation():
_type = FooType("test-foo", "v1.0") _type = FooType("test-foo", "v1.0")
_type.to_medium_dict()["fooType"].should.equal(_type.to_short_dict()) assert _type.to_medium_dict()["fooType"] == _type.to_short_dict()
_type.to_medium_dict()["status"].should.equal("REGISTERED") assert _type.to_medium_dict()["status"] == "REGISTERED"
_type.to_medium_dict().should.contain("creationDate") assert "creationDate" in _type.to_medium_dict()
_type.to_medium_dict().should_not.contain("deprecationDate") assert "deprecationDate" not in _type.to_medium_dict()
_type.to_medium_dict().should_not.contain("description") assert "description" not in _type.to_medium_dict()
_type.description = "foo bar" _type.description = "foo bar"
_type.to_medium_dict()["description"].should.equal("foo bar") assert _type.to_medium_dict()["description"] == "foo bar"
_type.status = "DEPRECATED" _type.status = "DEPRECATED"
_type.to_medium_dict().should.contain("deprecationDate") assert "deprecationDate" in _type.to_medium_dict()
def test_type_full_dict_representation(): def test_type_full_dict_representation():
_type = FooType("test-foo", "v1.0") _type = FooType("test-foo", "v1.0")
_type.to_full_dict()["typeInfo"].should.equal(_type.to_medium_dict()) assert _type.to_full_dict()["typeInfo"] == _type.to_medium_dict()
_type.to_full_dict()["configuration"].should.equal({}) assert not _type.to_full_dict()["configuration"]
_type.task_list = "foo" _type.task_list = "foo"
_type.to_full_dict()["configuration"]["defaultTaskList"].should.equal( assert _type.to_full_dict()["configuration"]["defaultTaskList"] == {"name": "foo"}
{"name": "foo"}
)
_type.just_an_example_timeout = "60" _type.just_an_example_timeout = "60"
_type.to_full_dict()["configuration"]["justAnExampleTimeout"].should.equal("60") assert _type.to_full_dict()["configuration"]["justAnExampleTimeout"] == "60"
_type.non_whitelisted_property = "34" _type.non_whitelisted_property = "34"
keys = _type.to_full_dict()["configuration"].keys() keys = _type.to_full_dict()["configuration"].keys()
sorted(keys).should.equal(["defaultTaskList", "justAnExampleTimeout"]) assert sorted(keys) == ["defaultTaskList", "justAnExampleTimeout"]
def test_type_string_representation(): def test_type_string_representation():
_type = FooType("test-foo", "v1.0") _type = FooType("test-foo", "v1.0")
str(_type).should.equal( assert str(_type) == "FooType(name: test-foo, version: v1.0, status: REGISTERED)"
"FooType(name: test-foo, version: v1.0, status: REGISTERED)"
)

View File

@ -1,5 +1,5 @@
from freezegun import freeze_time from freezegun import freeze_time
import sure # noqa # pylint: disable=unused-import import pytest
from moto.swf.models import HistoryEvent from moto.swf.models import HistoryEvent
@ -7,25 +7,22 @@ from moto.swf.models import HistoryEvent
@freeze_time("2015-01-01 12:00:00") @freeze_time("2015-01-01 12:00:00")
def test_history_event_creation(): def test_history_event_creation():
he = HistoryEvent(123, "DecisionTaskStarted", scheduled_event_id=2) he = HistoryEvent(123, "DecisionTaskStarted", scheduled_event_id=2)
he.event_id.should.equal(123) assert he.event_id == 123
he.event_type.should.equal("DecisionTaskStarted") assert he.event_type == "DecisionTaskStarted"
he.event_timestamp.should.equal(1420113600.0) assert he.event_timestamp == 1420113600.0
@freeze_time("2015-01-01 12:00:00") @freeze_time("2015-01-01 12:00:00")
def test_history_event_to_dict_representation(): def test_history_event_to_dict_representation():
he = HistoryEvent(123, "DecisionTaskStarted", scheduled_event_id=2) he = HistoryEvent(123, "DecisionTaskStarted", scheduled_event_id=2)
he.to_dict().should.equal( assert he.to_dict() == {
{ "eventId": 123,
"eventId": 123, "eventType": "DecisionTaskStarted",
"eventType": "DecisionTaskStarted", "eventTimestamp": 1420113600.0,
"eventTimestamp": 1420113600.0, "decisionTaskStartedEventAttributes": {"scheduledEventId": 2},
"decisionTaskStartedEventAttributes": {"scheduledEventId": 2}, }
}
)
def test_history_event_breaks_on_initialization_if_not_implemented(): def test_history_event_breaks_on_initialization_if_not_implemented():
HistoryEvent.when.called_with(123, "UnknownHistoryEvent").should.throw( with pytest.raises(NotImplementedError):
NotImplementedError HistoryEvent(123, "UnknownHistoryEvent")
)

View File

@ -1,5 +1,4 @@
from freezegun import freeze_time from freezegun import freeze_time
import sure # noqa # pylint: disable=unused-import
from moto.swf.models import Timeout from moto.swf.models import Timeout
@ -13,7 +12,7 @@ def test_timeout_creation():
timeout = Timeout(wfe, 1420117200, "START_TO_CLOSE") timeout = Timeout(wfe, 1420117200, "START_TO_CLOSE")
with freeze_time("2015-01-01 12:00:00"): with freeze_time("2015-01-01 12:00:00"):
timeout.reached.should.equal(False) assert timeout.reached is False
with freeze_time("2015-01-01 13:00:00"): with freeze_time("2015-01-01 13:00:00"):
timeout.reached.should.equal(True) assert timeout.reached is True

View File

@ -1,10 +1,12 @@
import re
from threading import Timer as ThreadingTimer from threading import Timer as ThreadingTimer
from time import sleep from time import sleep
from unittest.mock import Mock, patch
from freezegun import freeze_time from freezegun import freeze_time
from unittest.mock import Mock, patch import pytest
import sure # noqa # pylint: disable=unused-import
from moto.swf.exceptions import SWFDefaultUndefinedFault
from moto.swf.models import ( from moto.swf.models import (
ActivityType, ActivityType,
Timeout, Timeout,
@ -12,7 +14,6 @@ from moto.swf.models import (
WorkflowType, WorkflowType,
WorkflowExecution, WorkflowExecution,
) )
from moto.swf.exceptions import SWFDefaultUndefinedFault
from ..utils import ( from ..utils import (
auto_start_decision_tasks, auto_start_decision_tasks,
get_basic_domain, get_basic_domain,
@ -37,48 +38,53 @@ def test_workflow_execution_creation():
wft = get_basic_workflow_type() wft = get_basic_workflow_type()
wfe = WorkflowExecution(domain, wft, "ab1234", child_policy="TERMINATE") wfe = WorkflowExecution(domain, wft, "ab1234", child_policy="TERMINATE")
wfe.domain.should.equal(domain) assert wfe.domain == domain
wfe.workflow_type.should.equal(wft) assert wfe.workflow_type == wft
wfe.child_policy.should.equal("TERMINATE") assert wfe.child_policy == "TERMINATE"
def test_workflow_execution_creation_child_policy_logic(): def test_workflow_execution_creation_child_policy_logic():
domain = get_basic_domain() domain = get_basic_domain()
WorkflowExecution( assert (
domain, WorkflowExecution(
WorkflowType( domain,
"test-workflow", WorkflowType(
"v1.0", "test-workflow",
task_list="queue", "v1.0",
default_child_policy="ABANDON", task_list="queue",
default_execution_start_to_close_timeout="300", default_child_policy="ABANDON",
default_task_start_to_close_timeout="300", default_execution_start_to_close_timeout="300",
), default_task_start_to_close_timeout="300",
"ab1234", ),
).child_policy.should.equal("ABANDON") "ab1234",
).child_policy
== "ABANDON"
)
WorkflowExecution( assert (
domain, WorkflowExecution(
WorkflowType( domain,
"test-workflow", WorkflowType(
"v1.0", "test-workflow",
task_list="queue", "v1.0",
default_execution_start_to_close_timeout="300", task_list="queue",
default_task_start_to_close_timeout="300", default_execution_start_to_close_timeout="300",
), default_task_start_to_close_timeout="300",
"ab1234", ),
child_policy="REQUEST_CANCEL", "ab1234",
).child_policy.should.equal("REQUEST_CANCEL") child_policy="REQUEST_CANCEL",
).child_policy
== "REQUEST_CANCEL"
)
WorkflowExecution.when.called_with( with pytest.raises(SWFDefaultUndefinedFault):
domain, WorkflowType("test-workflow", "v1.0"), "ab1234" WorkflowExecution(domain, WorkflowType("test-workflow", "v1.0"), "ab1234")
).should.throw(SWFDefaultUndefinedFault)
def test_workflow_execution_string_representation(): def test_workflow_execution_string_representation():
wfe = make_workflow_execution(child_policy="TERMINATE") wfe = make_workflow_execution(child_policy="TERMINATE")
str(wfe).should.match(r"^WorkflowExecution\(run_id: .*\)") assert re.match(r"^WorkflowExecution\(run_id: .*\)", str(wfe))
def test_workflow_execution_generates_a_random_run_id(): def test_workflow_execution_generates_a_random_run_id():
@ -86,7 +92,7 @@ def test_workflow_execution_generates_a_random_run_id():
wft = get_basic_workflow_type() wft = get_basic_workflow_type()
wfe1 = WorkflowExecution(domain, wft, "ab1234", child_policy="TERMINATE") wfe1 = WorkflowExecution(domain, wft, "ab1234", child_policy="TERMINATE")
wfe2 = WorkflowExecution(domain, wft, "ab1235", child_policy="TERMINATE") wfe2 = WorkflowExecution(domain, wft, "ab1235", child_policy="TERMINATE")
wfe1.run_id.should_not.equal(wfe2.run_id) assert wfe1.run_id != wfe2.run_id
def test_workflow_execution_short_dict_representation(): def test_workflow_execution_short_dict_representation():
@ -102,8 +108,8 @@ def test_workflow_execution_short_dict_representation():
wfe = WorkflowExecution(domain, wf_type, "ab1234") wfe = WorkflowExecution(domain, wf_type, "ab1234")
sd = wfe.to_short_dict() sd = wfe.to_short_dict()
sd["workflowId"].should.equal("ab1234") assert sd["workflowId"] == "ab1234"
sd.should.contain("runId") assert "runId" in sd
def test_workflow_execution_medium_dict_representation(): def test_workflow_execution_medium_dict_representation():
@ -119,16 +125,16 @@ def test_workflow_execution_medium_dict_representation():
wfe = WorkflowExecution(domain, wf_type, "ab1234") wfe = WorkflowExecution(domain, wf_type, "ab1234")
md = wfe.to_medium_dict() md = wfe.to_medium_dict()
md["execution"].should.equal(wfe.to_short_dict()) assert md["execution"] == wfe.to_short_dict()
md["workflowType"].should.equal(wf_type.to_short_dict()) assert md["workflowType"] == wf_type.to_short_dict()
md["startTimestamp"].should.be.a("float") assert isinstance(md["startTimestamp"], float)
md["executionStatus"].should.equal("OPEN") assert md["executionStatus"] == "OPEN"
md["cancelRequested"].should.equal(False) assert md["cancelRequested"] is False
md.should_not.contain("tagList") assert "tagList" not in md
wfe.tag_list = ["foo", "bar", "baz"] wfe.tag_list = ["foo", "bar", "baz"]
md = wfe.to_medium_dict() md = wfe.to_medium_dict()
md["tagList"].should.equal(["foo", "bar", "baz"]) assert md["tagList"] == ["foo", "bar", "baz"]
def test_workflow_execution_full_dict_representation(): def test_workflow_execution_full_dict_representation():
@ -144,18 +150,16 @@ def test_workflow_execution_full_dict_representation():
wfe = WorkflowExecution(domain, wf_type, "ab1234") wfe = WorkflowExecution(domain, wf_type, "ab1234")
fd = wfe.to_full_dict() fd = wfe.to_full_dict()
fd["executionInfo"].should.equal(wfe.to_medium_dict()) assert fd["executionInfo"] == wfe.to_medium_dict()
fd["openCounts"]["openTimers"].should.equal(0) assert fd["openCounts"]["openTimers"] == 0
fd["openCounts"]["openDecisionTasks"].should.equal(0) assert fd["openCounts"]["openDecisionTasks"] == 0
fd["openCounts"]["openActivityTasks"].should.equal(0) assert fd["openCounts"]["openActivityTasks"] == 0
fd["executionConfiguration"].should.equal( assert fd["executionConfiguration"] == {
{ "childPolicy": "ABANDON",
"childPolicy": "ABANDON", "executionStartToCloseTimeout": "300",
"executionStartToCloseTimeout": "300", "taskList": {"name": "queue"},
"taskList": {"name": "queue"}, "taskStartToCloseTimeout": "300",
"taskStartToCloseTimeout": "300", }
}
)
def test_closed_workflow_execution_full_dict_representation(): def test_closed_workflow_execution_full_dict_representation():
@ -177,18 +181,16 @@ def test_closed_workflow_execution_full_dict_representation():
medium_dict = wfe.to_medium_dict() medium_dict = wfe.to_medium_dict()
medium_dict["closeStatus"] = "CANCELED" medium_dict["closeStatus"] = "CANCELED"
medium_dict["closeTimestamp"] = 1420066801.123 medium_dict["closeTimestamp"] = 1420066801.123
fd["executionInfo"].should.equal(medium_dict) assert fd["executionInfo"] == medium_dict
fd["openCounts"]["openTimers"].should.equal(0) assert fd["openCounts"]["openTimers"] == 0
fd["openCounts"]["openDecisionTasks"].should.equal(0) assert fd["openCounts"]["openDecisionTasks"] == 0
fd["openCounts"]["openActivityTasks"].should.equal(0) assert fd["openCounts"]["openActivityTasks"] == 0
fd["executionConfiguration"].should.equal( assert fd["executionConfiguration"] == {
{ "childPolicy": "ABANDON",
"childPolicy": "ABANDON", "executionStartToCloseTimeout": "300",
"executionStartToCloseTimeout": "300", "taskList": {"name": "queue"},
"taskList": {"name": "queue"}, "taskStartToCloseTimeout": "300",
"taskStartToCloseTimeout": "300", }
}
)
def test_workflow_execution_list_dict_representation(): def test_workflow_execution_list_dict_representation():
@ -204,47 +206,47 @@ def test_workflow_execution_list_dict_representation():
wfe = WorkflowExecution(domain, wf_type, "ab1234") wfe = WorkflowExecution(domain, wf_type, "ab1234")
ld = wfe.to_list_dict() ld = wfe.to_list_dict()
ld["workflowType"]["version"].should.equal("v1.0") assert ld["workflowType"]["version"] == "v1.0"
ld["workflowType"]["name"].should.equal("test-workflow") assert ld["workflowType"]["name"] == "test-workflow"
ld["executionStatus"].should.equal("OPEN") assert ld["executionStatus"] == "OPEN"
ld["execution"]["workflowId"].should.equal("ab1234") assert ld["execution"]["workflowId"] == "ab1234"
ld["execution"].should.contain("runId") assert "runId" in ld["execution"]
ld["cancelRequested"].should.equal(False) assert ld["cancelRequested"] is False
ld.should.contain("startTimestamp") assert "startTimestamp" in ld
def test_workflow_execution_schedule_decision_task(): def test_workflow_execution_schedule_decision_task():
wfe = make_workflow_execution() wfe = make_workflow_execution()
wfe.open_counts["openDecisionTasks"].should.equal(0) assert wfe.open_counts["openDecisionTasks"] == 0
wfe.schedule_decision_task() wfe.schedule_decision_task()
wfe.open_counts["openDecisionTasks"].should.equal(1) assert wfe.open_counts["openDecisionTasks"] == 1
def test_workflow_execution_dont_schedule_decision_if_existing_started_and_other_scheduled(): def test_workflow_execution_dont_schedule_decision_if_existing_started_and_other_scheduled():
wfe = make_workflow_execution() wfe = make_workflow_execution()
wfe.open_counts["openDecisionTasks"].should.equal(0) assert wfe.open_counts["openDecisionTasks"] == 0
wfe.schedule_decision_task() wfe.schedule_decision_task()
wfe.open_counts["openDecisionTasks"].should.equal(1) assert wfe.open_counts["openDecisionTasks"] == 1
wfe.decision_tasks[0].start("evt_id") wfe.decision_tasks[0].start("evt_id")
wfe.schedule_decision_task() wfe.schedule_decision_task()
wfe.schedule_decision_task() wfe.schedule_decision_task()
wfe.open_counts["openDecisionTasks"].should.equal(2) assert wfe.open_counts["openDecisionTasks"] == 2
def test_workflow_execution_schedule_decision_if_existing_started_and_no_other_scheduled(): def test_workflow_execution_schedule_decision_if_existing_started_and_no_other_scheduled():
wfe = make_workflow_execution() wfe = make_workflow_execution()
wfe.open_counts["openDecisionTasks"].should.equal(0) assert wfe.open_counts["openDecisionTasks"] == 0
wfe.schedule_decision_task() wfe.schedule_decision_task()
wfe.open_counts["openDecisionTasks"].should.equal(1) assert wfe.open_counts["openDecisionTasks"] == 1
wfe.decision_tasks[0].start("evt_id") wfe.decision_tasks[0].start("evt_id")
wfe.schedule_decision_task() wfe.schedule_decision_task()
wfe.open_counts["openDecisionTasks"].should.equal(2) assert wfe.open_counts["openDecisionTasks"] == 2
def test_workflow_execution_start_decision_task(): def test_workflow_execution_start_decision_task():
@ -253,9 +255,9 @@ def test_workflow_execution_start_decision_task():
dt = wfe.decision_tasks[0] dt = wfe.decision_tasks[0]
wfe.start_decision_task(dt.task_token, identity="srv01") wfe.start_decision_task(dt.task_token, identity="srv01")
dt = wfe.decision_tasks[0] dt = wfe.decision_tasks[0]
dt.state.should.equal("STARTED") assert dt.state == "STARTED"
wfe.events()[-1].event_type.should.equal("DecisionTaskStarted") assert wfe.events()[-1].event_type == "DecisionTaskStarted"
wfe.events()[-1].event_attributes["identity"].should.equal("srv01") assert wfe.events()[-1].event_attributes["identity"] == "srv01"
def test_workflow_execution_history_events_ids(): def test_workflow_execution_history_events_ids():
@ -264,19 +266,19 @@ def test_workflow_execution_history_events_ids():
wfe._add_event("DecisionTaskScheduled") wfe._add_event("DecisionTaskScheduled")
wfe._add_event("DecisionTaskStarted") wfe._add_event("DecisionTaskStarted")
ids = [evt.event_id for evt in wfe.events()] ids = [evt.event_id for evt in wfe.events()]
ids.should.equal([1, 2, 3]) assert ids == [1, 2, 3]
@freeze_time("2015-01-01 12:00:00") @freeze_time("2015-01-01 12:00:00")
def test_workflow_execution_start(): def test_workflow_execution_start():
wfe = make_workflow_execution() wfe = make_workflow_execution()
wfe.events().should.equal([]) assert wfe.events() == []
wfe.start() wfe.start()
wfe.start_timestamp.should.equal(1420113600.0) assert wfe.start_timestamp == 1420113600.0
wfe.events().should.have.length_of(2) assert len(wfe.events()) == 2
wfe.events()[0].event_type.should.equal("WorkflowExecutionStarted") assert wfe.events()[0].event_type == "WorkflowExecutionStarted"
wfe.events()[1].event_type.should.equal("DecisionTaskScheduled") assert wfe.events()[1].event_type == "DecisionTaskScheduled"
@freeze_time("2015-01-02 12:00:00") @freeze_time("2015-01-02 12:00:00")
@ -284,12 +286,12 @@ def test_workflow_execution_complete():
wfe = make_workflow_execution() wfe = make_workflow_execution()
wfe.complete(123, result="foo") wfe.complete(123, result="foo")
wfe.execution_status.should.equal("CLOSED") assert wfe.execution_status == "CLOSED"
wfe.close_status.should.equal("COMPLETED") assert wfe.close_status == "COMPLETED"
wfe.close_timestamp.should.equal(1420200000.0) assert wfe.close_timestamp == 1420200000.0
wfe.events()[-1].event_type.should.equal("WorkflowExecutionCompleted") assert wfe.events()[-1].event_type == "WorkflowExecutionCompleted"
wfe.events()[-1].event_attributes["decisionTaskCompletedEventId"].should.equal(123) assert wfe.events()[-1].event_attributes["decisionTaskCompletedEventId"] == 123
wfe.events()[-1].event_attributes["result"].should.equal("foo") assert wfe.events()[-1].event_attributes["result"] == "foo"
@freeze_time("2015-01-02 12:00:00") @freeze_time("2015-01-02 12:00:00")
@ -297,35 +299,35 @@ def test_workflow_execution_fail():
wfe = make_workflow_execution() wfe = make_workflow_execution()
wfe.fail(123, details="some details", reason="my rules") wfe.fail(123, details="some details", reason="my rules")
wfe.execution_status.should.equal("CLOSED") assert wfe.execution_status == "CLOSED"
wfe.close_status.should.equal("FAILED") assert wfe.close_status == "FAILED"
wfe.close_timestamp.should.equal(1420200000.0) assert wfe.close_timestamp == 1420200000.0
wfe.events()[-1].event_type.should.equal("WorkflowExecutionFailed") assert wfe.events()[-1].event_type == "WorkflowExecutionFailed"
wfe.events()[-1].event_attributes["decisionTaskCompletedEventId"].should.equal(123) assert wfe.events()[-1].event_attributes["decisionTaskCompletedEventId"] == 123
wfe.events()[-1].event_attributes["details"].should.equal("some details") assert wfe.events()[-1].event_attributes["details"] == "some details"
wfe.events()[-1].event_attributes["reason"].should.equal("my rules") assert wfe.events()[-1].event_attributes["reason"] == "my rules"
@freeze_time("2015-01-01 12:00:00") @freeze_time("2015-01-01 12:00:00")
def test_workflow_execution_schedule_activity_task(): def test_workflow_execution_schedule_activity_task():
wfe = make_workflow_execution() wfe = make_workflow_execution()
wfe.latest_activity_task_timestamp.should.equal(None) assert wfe.latest_activity_task_timestamp is None
wfe.schedule_activity_task(123, VALID_ACTIVITY_TASK_ATTRIBUTES) wfe.schedule_activity_task(123, VALID_ACTIVITY_TASK_ATTRIBUTES)
wfe.latest_activity_task_timestamp.should.equal(1420113600.0) assert wfe.latest_activity_task_timestamp == 1420113600.0
wfe.open_counts["openActivityTasks"].should.equal(1) assert wfe.open_counts["openActivityTasks"] == 1
last_event = wfe.events()[-1] last_event = wfe.events()[-1]
last_event.event_type.should.equal("ActivityTaskScheduled") assert last_event.event_type == "ActivityTaskScheduled"
last_event.event_attributes["decisionTaskCompletedEventId"].should.equal(123) assert last_event.event_attributes["decisionTaskCompletedEventId"] == 123
last_event.event_attributes["taskList"]["name"].should.equal("task-list-name") assert last_event.event_attributes["taskList"]["name"] == "task-list-name"
wfe.activity_tasks.should.have.length_of(1) assert len(wfe.activity_tasks) == 1
task = wfe.activity_tasks[0] task = wfe.activity_tasks[0]
task.activity_id.should.equal("my-activity-001") assert task.activity_id == "my-activity-001"
task.activity_type.name.should.equal("test-activity") assert task.activity_type.name == "test-activity"
wfe.domain.activity_task_lists["task-list-name"].should.contain(task) assert task in wfe.domain.activity_task_lists["task-list-name"]
def test_workflow_execution_schedule_activity_task_without_task_list_should_take_default(): def test_workflow_execution_schedule_activity_task_without_task_list_should_take_default():
@ -343,13 +345,13 @@ def test_workflow_execution_schedule_activity_task_without_task_list_should_take
}, },
) )
wfe.open_counts["openActivityTasks"].should.equal(1) assert wfe.open_counts["openActivityTasks"] == 1
last_event = wfe.events()[-1] last_event = wfe.events()[-1]
last_event.event_type.should.equal("ActivityTaskScheduled") assert last_event.event_type == "ActivityTaskScheduled"
last_event.event_attributes["taskList"]["name"].should.equal("foobar") assert last_event.event_attributes["taskList"]["name"] == "foobar"
task = wfe.activity_tasks[0] task = wfe.activity_tasks[0]
wfe.domain.activity_task_lists["foobar"].should.contain(task) assert task in wfe.domain.activity_task_lists["foobar"]
def test_workflow_execution_schedule_activity_task_should_fail_if_wrong_attributes(): def test_workflow_execution_schedule_activity_task_should_fail_if_wrong_attributes():
@ -366,66 +368,66 @@ def test_workflow_execution_schedule_activity_task_should_fail_if_wrong_attribut
wfe.schedule_activity_task(123, hsh) wfe.schedule_activity_task(123, hsh)
last_event = wfe.events()[-1] last_event = wfe.events()[-1]
last_event.event_type.should.equal("ScheduleActivityTaskFailed") assert last_event.event_type == "ScheduleActivityTaskFailed"
last_event.event_attributes["cause"].should.equal("ACTIVITY_TYPE_DOES_NOT_EXIST") assert last_event.event_attributes["cause"] == "ACTIVITY_TYPE_DOES_NOT_EXIST"
hsh["activityType"]["name"] = "test-activity" hsh["activityType"]["name"] = "test-activity"
wfe.schedule_activity_task(123, hsh) wfe.schedule_activity_task(123, hsh)
last_event = wfe.events()[-1] last_event = wfe.events()[-1]
last_event.event_type.should.equal("ScheduleActivityTaskFailed") assert last_event.event_type == "ScheduleActivityTaskFailed"
last_event.event_attributes["cause"].should.equal("ACTIVITY_TYPE_DEPRECATED") assert last_event.event_attributes["cause"] == "ACTIVITY_TYPE_DEPRECATED"
hsh["activityType"]["version"] = "v1.2" hsh["activityType"]["version"] = "v1.2"
wfe.schedule_activity_task(123, hsh) wfe.schedule_activity_task(123, hsh)
last_event = wfe.events()[-1] last_event = wfe.events()[-1]
last_event.event_type.should.equal("ScheduleActivityTaskFailed") assert last_event.event_type == "ScheduleActivityTaskFailed"
last_event.event_attributes["cause"].should.equal("DEFAULT_TASK_LIST_UNDEFINED") assert last_event.event_attributes["cause"] == "DEFAULT_TASK_LIST_UNDEFINED"
hsh["taskList"] = {"name": "foobar"} hsh["taskList"] = {"name": "foobar"}
wfe.schedule_activity_task(123, hsh) wfe.schedule_activity_task(123, hsh)
last_event = wfe.events()[-1] last_event = wfe.events()[-1]
last_event.event_type.should.equal("ScheduleActivityTaskFailed") assert last_event.event_type == "ScheduleActivityTaskFailed"
last_event.event_attributes["cause"].should.equal( assert last_event.event_attributes["cause"] == (
"DEFAULT_SCHEDULE_TO_START_TIMEOUT_UNDEFINED" "DEFAULT_SCHEDULE_TO_START_TIMEOUT_UNDEFINED"
) )
hsh["scheduleToStartTimeout"] = "600" hsh["scheduleToStartTimeout"] = "600"
wfe.schedule_activity_task(123, hsh) wfe.schedule_activity_task(123, hsh)
last_event = wfe.events()[-1] last_event = wfe.events()[-1]
last_event.event_type.should.equal("ScheduleActivityTaskFailed") assert last_event.event_type == "ScheduleActivityTaskFailed"
last_event.event_attributes["cause"].should.equal( assert last_event.event_attributes["cause"] == (
"DEFAULT_SCHEDULE_TO_CLOSE_TIMEOUT_UNDEFINED" "DEFAULT_SCHEDULE_TO_CLOSE_TIMEOUT_UNDEFINED"
) )
hsh["scheduleToCloseTimeout"] = "600" hsh["scheduleToCloseTimeout"] = "600"
wfe.schedule_activity_task(123, hsh) wfe.schedule_activity_task(123, hsh)
last_event = wfe.events()[-1] last_event = wfe.events()[-1]
last_event.event_type.should.equal("ScheduleActivityTaskFailed") assert last_event.event_type == "ScheduleActivityTaskFailed"
last_event.event_attributes["cause"].should.equal( assert last_event.event_attributes["cause"] == (
"DEFAULT_START_TO_CLOSE_TIMEOUT_UNDEFINED" "DEFAULT_START_TO_CLOSE_TIMEOUT_UNDEFINED"
) )
hsh["startToCloseTimeout"] = "600" hsh["startToCloseTimeout"] = "600"
wfe.schedule_activity_task(123, hsh) wfe.schedule_activity_task(123, hsh)
last_event = wfe.events()[-1] last_event = wfe.events()[-1]
last_event.event_type.should.equal("ScheduleActivityTaskFailed") assert last_event.event_type == "ScheduleActivityTaskFailed"
last_event.event_attributes["cause"].should.equal( assert last_event.event_attributes["cause"] == (
"DEFAULT_HEARTBEAT_TIMEOUT_UNDEFINED" "DEFAULT_HEARTBEAT_TIMEOUT_UNDEFINED"
) )
wfe.open_counts["openActivityTasks"].should.equal(0) assert wfe.open_counts["openActivityTasks"] == 0
wfe.activity_tasks.should.have.length_of(0) assert len(wfe.activity_tasks) == 0
wfe.domain.activity_task_lists.should.have.length_of(0) assert len(wfe.domain.activity_task_lists) == 0
hsh["heartbeatTimeout"] = "300" hsh["heartbeatTimeout"] = "300"
wfe.schedule_activity_task(123, hsh) wfe.schedule_activity_task(123, hsh)
last_event = wfe.events()[-1] last_event = wfe.events()[-1]
last_event.event_type.should.equal("ActivityTaskScheduled") assert last_event.event_type == "ActivityTaskScheduled"
task = wfe.activity_tasks[0] task = wfe.activity_tasks[0]
wfe.domain.activity_task_lists["foobar"].should.contain(task) assert task in wfe.domain.activity_task_lists["foobar"]
wfe.open_counts["openDecisionTasks"].should.equal(0) assert wfe.open_counts["openDecisionTasks"] == 0
wfe.open_counts["openActivityTasks"].should.equal(1) assert wfe.open_counts["openActivityTasks"] == 1
def test_workflow_execution_schedule_activity_task_failure_triggers_new_decision(): def test_workflow_execution_schedule_activity_task_failure_triggers_new_decision():
@ -460,28 +462,28 @@ def test_workflow_execution_schedule_activity_task_failure_triggers_new_decision
], ],
) )
wfe.latest_execution_context.should.equal("free-form execution context") assert wfe.latest_execution_context == "free-form execution context"
wfe.open_counts["openActivityTasks"].should.equal(0) assert wfe.open_counts["openActivityTasks"] == 0
wfe.open_counts["openDecisionTasks"].should.equal(1) assert wfe.open_counts["openDecisionTasks"] == 1
last_events = wfe.events()[-3:] last_events = wfe.events()[-3:]
last_events[0].event_type.should.equal("ScheduleActivityTaskFailed") assert last_events[0].event_type == "ScheduleActivityTaskFailed"
last_events[1].event_type.should.equal("ScheduleActivityTaskFailed") assert last_events[1].event_type == "ScheduleActivityTaskFailed"
last_events[2].event_type.should.equal("DecisionTaskScheduled") assert last_events[2].event_type == "DecisionTaskScheduled"
def test_workflow_execution_schedule_activity_task_with_same_activity_id(): def test_workflow_execution_schedule_activity_task_with_same_activity_id():
wfe = make_workflow_execution() wfe = make_workflow_execution()
wfe.schedule_activity_task(123, VALID_ACTIVITY_TASK_ATTRIBUTES) wfe.schedule_activity_task(123, VALID_ACTIVITY_TASK_ATTRIBUTES)
wfe.open_counts["openActivityTasks"].should.equal(1) assert wfe.open_counts["openActivityTasks"] == 1
last_event = wfe.events()[-1] last_event = wfe.events()[-1]
last_event.event_type.should.equal("ActivityTaskScheduled") assert last_event.event_type == "ActivityTaskScheduled"
wfe.schedule_activity_task(123, VALID_ACTIVITY_TASK_ATTRIBUTES) wfe.schedule_activity_task(123, VALID_ACTIVITY_TASK_ATTRIBUTES)
wfe.open_counts["openActivityTasks"].should.equal(1) assert wfe.open_counts["openActivityTasks"] == 1
last_event = wfe.events()[-1] last_event = wfe.events()[-1]
last_event.event_type.should.equal("ScheduleActivityTaskFailed") assert last_event.event_type == "ScheduleActivityTaskFailed"
last_event.event_attributes["cause"].should.equal("ACTIVITY_ID_ALREADY_IN_USE") assert last_event.event_attributes["cause"] == "ACTIVITY_ID_ALREADY_IN_USE"
def test_workflow_execution_start_activity_task(): def test_workflow_execution_start_activity_task():
@ -490,9 +492,9 @@ def test_workflow_execution_start_activity_task():
task_token = wfe.activity_tasks[-1].task_token task_token = wfe.activity_tasks[-1].task_token
wfe.start_activity_task(task_token, identity="worker01") wfe.start_activity_task(task_token, identity="worker01")
task = wfe.activity_tasks[-1] task = wfe.activity_tasks[-1]
task.state.should.equal("STARTED") assert task.state == "STARTED"
wfe.events()[-1].event_type.should.equal("ActivityTaskStarted") assert wfe.events()[-1].event_type == "ActivityTaskStarted"
wfe.events()[-1].event_attributes["identity"].should.equal("worker01") assert wfe.events()[-1].event_attributes["identity"] == "worker01"
def test_complete_activity_task(): def test_complete_activity_task():
@ -500,19 +502,19 @@ def test_complete_activity_task():
wfe.schedule_activity_task(123, VALID_ACTIVITY_TASK_ATTRIBUTES) wfe.schedule_activity_task(123, VALID_ACTIVITY_TASK_ATTRIBUTES)
task_token = wfe.activity_tasks[-1].task_token task_token = wfe.activity_tasks[-1].task_token
wfe.open_counts["openActivityTasks"].should.equal(1) assert wfe.open_counts["openActivityTasks"] == 1
wfe.open_counts["openDecisionTasks"].should.equal(0) assert wfe.open_counts["openDecisionTasks"] == 0
wfe.start_activity_task(task_token, identity="worker01") wfe.start_activity_task(task_token, identity="worker01")
wfe.complete_activity_task(task_token, result="a superb result") wfe.complete_activity_task(task_token, result="a superb result")
task = wfe.activity_tasks[-1] task = wfe.activity_tasks[-1]
task.state.should.equal("COMPLETED") assert task.state == "COMPLETED"
wfe.events()[-2].event_type.should.equal("ActivityTaskCompleted") assert wfe.events()[-2].event_type == "ActivityTaskCompleted"
wfe.events()[-1].event_type.should.equal("DecisionTaskScheduled") assert wfe.events()[-1].event_type == "DecisionTaskScheduled"
wfe.open_counts["openActivityTasks"].should.equal(0) assert wfe.open_counts["openActivityTasks"] == 0
wfe.open_counts["openDecisionTasks"].should.equal(1) assert wfe.open_counts["openDecisionTasks"] == 1
def test_terminate(): def test_terminate():
@ -520,28 +522,28 @@ def test_terminate():
wfe.schedule_decision_task() wfe.schedule_decision_task()
wfe.terminate() wfe.terminate()
wfe.execution_status.should.equal("CLOSED") assert wfe.execution_status == "CLOSED"
wfe.close_status.should.equal("TERMINATED") assert wfe.close_status == "TERMINATED"
wfe.close_cause.should.equal("OPERATOR_INITIATED") assert wfe.close_cause == "OPERATOR_INITIATED"
wfe.open_counts["openDecisionTasks"].should.equal(1) assert wfe.open_counts["openDecisionTasks"] == 1
last_event = wfe.events()[-1] last_event = wfe.events()[-1]
last_event.event_type.should.equal("WorkflowExecutionTerminated") assert last_event.event_type == "WorkflowExecutionTerminated"
# take default child_policy if not provided (as here) # take default child_policy if not provided (as here)
last_event.event_attributes["childPolicy"].should.equal("ABANDON") assert last_event.event_attributes["childPolicy"] == "ABANDON"
def test_first_timeout(): def test_first_timeout():
wfe = make_workflow_execution() wfe = make_workflow_execution()
wfe.first_timeout().should.be.none assert wfe.first_timeout() is None
with freeze_time("2015-01-01 12:00:00"): with freeze_time("2015-01-01 12:00:00"):
wfe.start() wfe.start()
wfe.first_timeout().should.be.none assert wfe.first_timeout() is None
with freeze_time("2015-01-01 14:01"): with freeze_time("2015-01-01 14:01"):
# 2 hours timeout reached # 2 hours timeout reached
wfe.first_timeout().should.be.a(Timeout) assert isinstance(wfe.first_timeout(), Timeout)
# See moto/swf/models/workflow_execution.py "_process_timeouts()" for more # See moto/swf/models/workflow_execution.py "_process_timeouts()" for more
@ -570,14 +572,12 @@ def test_timeouts_are_processed_in_order_and_reevaluated():
wfe._process_timeouts() wfe._process_timeouts()
event_types = [e.event_type for e in wfe.events()[event_idx:]] event_types = [e.event_type for e in wfe.events()[event_idx:]]
event_types.should.equal( assert event_types == [
[ "DecisionTaskTimedOut",
"DecisionTaskTimedOut", "DecisionTaskScheduled",
"DecisionTaskScheduled", "DecisionTaskStarted",
"DecisionTaskStarted", "WorkflowExecutionTimedOut",
"WorkflowExecutionTimedOut", ]
]
)
def test_record_marker(): def test_record_marker():
@ -587,9 +587,9 @@ def test_record_marker():
wfe.record_marker(123, MARKER_EVENT_ATTRIBUTES) wfe.record_marker(123, MARKER_EVENT_ATTRIBUTES)
last_event = wfe.events()[-1] last_event = wfe.events()[-1]
last_event.event_type.should.equal("MarkerRecorded") assert last_event.event_type == "MarkerRecorded"
last_event.event_attributes["markerName"].should.equal("example_marker") assert last_event.event_attributes["markerName"] == "example_marker"
last_event.event_attributes["decisionTaskCompletedEventId"].should.equal(123) assert last_event.event_attributes["decisionTaskCompletedEventId"] == 123
def test_start_timer(): def test_start_timer():
@ -600,10 +600,10 @@ def test_start_timer():
wfe.start_timer(123, START_TIMER_EVENT_ATTRIBUTES) wfe.start_timer(123, START_TIMER_EVENT_ATTRIBUTES)
last_event = wfe.events()[-1] last_event = wfe.events()[-1]
last_event.event_type.should.equal("TimerStarted") assert last_event.event_type == "TimerStarted"
last_event.event_attributes["startToFireTimeout"].should.equal("10") assert last_event.event_attributes["startToFireTimeout"] == "10"
last_event.event_attributes["timerId"].should.equal("abc123") assert last_event.event_attributes["timerId"] == "abc123"
last_event.event_attributes["decisionTaskCompletedEventId"].should.equal(123) assert last_event.event_attributes["decisionTaskCompletedEventId"] == 123
def test_start_timer_correctly_fires_timer_later(): def test_start_timer_correctly_fires_timer_later():
@ -618,10 +618,10 @@ def test_start_timer_correctly_fires_timer_later():
second_to_last_event = wfe.events()[-2] second_to_last_event = wfe.events()[-2]
last_event = wfe.events()[-1] last_event = wfe.events()[-1]
second_to_last_event.event_type.should.equal("TimerFired") assert second_to_last_event.event_type == "TimerFired"
second_to_last_event.event_attributes["timerId"].should.equal("abc123") assert second_to_last_event.event_attributes["timerId"] == "abc123"
second_to_last_event.event_attributes["startedEventId"].should.equal(1) assert second_to_last_event.event_attributes["startedEventId"] == 1
last_event.event_type.should.equal("DecisionTaskScheduled") assert last_event.event_type == "DecisionTaskScheduled"
def test_start_timer_fails_if_timer_already_started(): def test_start_timer_fails_if_timer_already_started():
@ -634,10 +634,10 @@ def test_start_timer_fails_if_timer_already_started():
wfe.start_timer(123, START_TIMER_EVENT_ATTRIBUTES) wfe.start_timer(123, START_TIMER_EVENT_ATTRIBUTES)
last_event = wfe.events()[-1] last_event = wfe.events()[-1]
last_event.event_type.should.equal("StartTimerFailed") assert last_event.event_type == "StartTimerFailed"
last_event.event_attributes["cause"].should.equal("TIMER_ID_ALREADY_IN_USE") assert last_event.event_attributes["cause"] == "TIMER_ID_ALREADY_IN_USE"
last_event.event_attributes["timerId"].should.equal("abc123") assert last_event.event_attributes["timerId"] == "abc123"
last_event.event_attributes["decisionTaskCompletedEventId"].should.equal(123) assert last_event.event_attributes["decisionTaskCompletedEventId"] == 123
def test_cancel_timer(): def test_cancel_timer():
@ -649,10 +649,10 @@ def test_cancel_timer():
wfe.cancel_timer(123, "abc123") wfe.cancel_timer(123, "abc123")
last_event = wfe.events()[-1] last_event = wfe.events()[-1]
last_event.event_type.should.equal("TimerCancelled") assert last_event.event_type == "TimerCancelled"
last_event.event_attributes["startedEventId"].should.equal(1) assert last_event.event_attributes["startedEventId"] == 1
last_event.event_attributes["timerId"].should.equal("abc123") assert last_event.event_attributes["timerId"] == "abc123"
last_event.event_attributes["decisionTaskCompletedEventId"].should.equal(123) assert last_event.event_attributes["decisionTaskCompletedEventId"] == 123
existing_timer.cancel.assert_called_once() existing_timer.cancel.assert_called_once()
assert not wfe._timers.get("abc123") assert not wfe._timers.get("abc123")
@ -663,9 +663,9 @@ def test_cancel_timer_fails_if_timer_not_found():
wfe.cancel_timer(123, "abc123") wfe.cancel_timer(123, "abc123")
last_event = wfe.events()[-1] last_event = wfe.events()[-1]
last_event.event_type.should.equal("CancelTimerFailed") assert last_event.event_type == "CancelTimerFailed"
last_event.event_attributes["cause"].should.equal("TIMER_ID_UNKNOWN") assert last_event.event_attributes["cause"] == "TIMER_ID_UNKNOWN"
last_event.event_attributes["decisionTaskCompletedEventId"].should.equal(123) assert last_event.event_attributes["decisionTaskCompletedEventId"] == 123
def test_cancel_workflow(): def test_cancel_workflow():
@ -675,9 +675,9 @@ def test_cancel_workflow():
wfe.cancel(123, "I want to cancel") wfe.cancel(123, "I want to cancel")
last_event = wfe.events()[-1] last_event = wfe.events()[-1]
last_event.event_type.should.equal("WorkflowExecutionCanceled") assert last_event.event_type == "WorkflowExecutionCanceled"
last_event.event_attributes["details"].should.equal("I want to cancel") assert last_event.event_attributes["details"] == "I want to cancel"
last_event.event_attributes["decisionTaskCompletedEventId"].should.equal(123) assert last_event.event_attributes["decisionTaskCompletedEventId"] == 123
def test_cancel_workflow_fails_if_open_decision(): def test_cancel_workflow_fails_if_open_decision():
@ -687,6 +687,6 @@ def test_cancel_workflow_fails_if_open_decision():
wfe.cancel(123, "I want to cancel") wfe.cancel(123, "I want to cancel")
last_event = wfe.events()[-1] last_event = wfe.events()[-1]
last_event.event_type.should.equal("CancelWorkflowExecutionFailed") assert last_event.event_type == "CancelWorkflowExecutionFailed"
last_event.event_attributes["cause"].should.equal("UNHANDLED_DECISION") assert last_event.event_attributes["cause"] == "UNHANDLED_DECISION"
last_event.event_attributes["decisionTaskCompletedEventId"].should.equal(123) assert last_event.event_attributes["decisionTaskCompletedEventId"] == 123

View File

@ -1,7 +1,8 @@
import re
from unittest import SkipTest
from botocore.exceptions import ClientError from botocore.exceptions import ClientError
from freezegun import freeze_time from freezegun import freeze_time
import sure # noqa # pylint: disable=unused-import
from unittest import SkipTest
import pytest import pytest
from moto import mock_swf from moto import mock_swf
@ -28,17 +29,18 @@ def test_poll_for_activity_task_when_one_boto3():
taskList={"name": "activity-task-list"}, taskList={"name": "activity-task-list"},
identity="surprise", identity="surprise",
) )
resp["activityId"].should.equal("my-activity-001") assert resp["activityId"] == "my-activity-001"
resp["taskToken"].should.match("[-a-z0-9]+") assert re.match("[-a-z0-9]+", resp["taskToken"])
resp = client.get_workflow_execution_history( resp = client.get_workflow_execution_history(
domain="test-domain", domain="test-domain",
execution={"runId": client.run_id, "workflowId": "uid-abcd1234"}, execution={"runId": client.run_id, "workflowId": "uid-abcd1234"},
) )
resp["events"][-1]["eventType"].should.equal("ActivityTaskStarted") assert resp["events"][-1]["eventType"] == "ActivityTaskStarted"
resp["events"][-1]["activityTaskStartedEventAttributes"].should.equal( assert resp["events"][-1]["activityTaskStartedEventAttributes"] == {
{"identity": "surprise", "scheduledEventId": 5} "identity": "surprise",
) "scheduledEventId": 5,
}
@pytest.mark.parametrize("task_name", ["activity-task-list", "non-existent-queue"]) @pytest.mark.parametrize("task_name", ["activity-task-list", "non-existent-queue"])
@ -48,9 +50,9 @@ def test_poll_for_activity_task_when_none_boto3(task_name):
resp = client.poll_for_decision_task( resp = client.poll_for_decision_task(
domain="test-domain", taskList={"name": task_name} domain="test-domain", taskList={"name": task_name}
) )
resp.shouldnt.have.key("taskToken") assert "taskToken" not in resp
resp.should.have.key("startedEventId").equal(0) assert resp["startedEventId"] == 0
resp.should.have.key("previousStartedEventId").equal(0) assert resp["previousStartedEventId"] == 0
# CountPendingActivityTasks endpoint # CountPendingActivityTasks endpoint
@ -72,8 +74,8 @@ def test_count_pending_activity_tasks_boto3(task_name, cnt):
resp = client.count_pending_activity_tasks( resp = client.count_pending_activity_tasks(
domain="test-domain", taskList={"name": task_name} domain="test-domain", taskList={"name": task_name}
) )
resp.should.have.key("count").equal(cnt) assert resp["count"] == cnt
resp.should.have.key("truncated").equal(False) assert resp["truncated"] is False
# RespondActivityTaskCompleted endpoint # RespondActivityTaskCompleted endpoint
@ -100,10 +102,12 @@ def test_respond_activity_task_completed_boto3():
domain="test-domain", domain="test-domain",
execution={"runId": client.run_id, "workflowId": "uid-abcd1234"}, execution={"runId": client.run_id, "workflowId": "uid-abcd1234"},
) )
resp["events"][-2]["eventType"].should.equal("ActivityTaskCompleted") assert resp["events"][-2]["eventType"] == "ActivityTaskCompleted"
resp["events"][-2]["activityTaskCompletedEventAttributes"].should.equal( assert resp["events"][-2]["activityTaskCompletedEventAttributes"] == {
{"result": "result of the task", "scheduledEventId": 5, "startedEventId": 6} "result": "result of the task",
) "scheduledEventId": 5,
"startedEventId": 6,
}
@mock_swf @mock_swf
@ -123,11 +127,11 @@ def test_respond_activity_task_completed_on_closed_workflow_execution_boto3():
with pytest.raises(ClientError) as ex: with pytest.raises(ClientError) as ex:
client.respond_activity_task_completed(taskToken=activity_token) client.respond_activity_task_completed(taskToken=activity_token)
ex.value.response["Error"]["Code"].should.equal("UnknownResourceFault") assert ex.value.response["Error"]["Code"] == "UnknownResourceFault"
ex.value.response["Error"]["Message"].should.equal( assert ex.value.response["Error"]["Message"] == (
f"Unknown execution: WorkflowExecution=[workflowId=uid-abcd1234, runId={client.run_id}]" f"Unknown execution: WorkflowExecution=[workflowId=uid-abcd1234, runId={client.run_id}]"
) )
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
@mock_swf @mock_swf
@ -147,11 +151,11 @@ def test_respond_activity_task_completed_with_task_already_completed_boto3():
with pytest.raises(ClientError) as ex: with pytest.raises(ClientError) as ex:
client.respond_activity_task_completed(taskToken=activity_token) client.respond_activity_task_completed(taskToken=activity_token)
ex.value.response["Error"]["Code"].should.equal("UnknownResourceFault") assert ex.value.response["Error"]["Code"] == "UnknownResourceFault"
ex.value.response["Error"]["Message"].should.equal( assert ex.value.response["Error"]["Message"] == (
"Unknown activity, scheduledEventId = 5" "Unknown activity, scheduledEventId = 5"
) )
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
# RespondActivityTaskFailed endpoint # RespondActivityTaskFailed endpoint
@ -178,15 +182,13 @@ def test_respond_activity_task_failed_boto3():
domain="test-domain", domain="test-domain",
execution={"runId": client.run_id, "workflowId": "uid-abcd1234"}, execution={"runId": client.run_id, "workflowId": "uid-abcd1234"},
) )
resp["events"][-2]["eventType"].should.equal("ActivityTaskFailed") assert resp["events"][-2]["eventType"] == "ActivityTaskFailed"
resp["events"][-2]["activityTaskFailedEventAttributes"].should.equal( assert resp["events"][-2]["activityTaskFailedEventAttributes"] == {
{ "reason": "short reason",
"reason": "short reason", "details": "long details",
"details": "long details", "scheduledEventId": 5,
"scheduledEventId": 5, "startedEventId": 6,
"startedEventId": 6, }
}
)
@mock_swf @mock_swf
@ -201,15 +203,15 @@ def test_respond_activity_task_completed_with_wrong_token_boto3():
client.respond_decision_task_completed( client.respond_decision_task_completed(
taskToken=decision_token, decisions=[SCHEDULE_ACTIVITY_TASK_DECISION] taskToken=decision_token, decisions=[SCHEDULE_ACTIVITY_TASK_DECISION]
) )
client.poll_for_activity_task( _ = client.poll_for_activity_task(
domain="test-domain", taskList={"name": "activity-task-list"} domain="test-domain", taskList={"name": "activity-task-list"}
)["taskToken"] )["taskToken"]
with pytest.raises(ClientError) as ex: with pytest.raises(ClientError) as ex:
client.respond_activity_task_failed(taskToken="not-a-correct-token") client.respond_activity_task_failed(taskToken="not-a-correct-token")
ex.value.response["Error"]["Code"].should.equal("ValidationException") assert ex.value.response["Error"]["Code"] == "ValidationException"
ex.value.response["Error"]["Message"].should.equal("Invalid token") assert ex.value.response["Error"]["Message"] == "Invalid token"
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
# RecordActivityTaskHeartbeat endpoint # RecordActivityTaskHeartbeat endpoint
@ -229,7 +231,7 @@ def test_record_activity_task_heartbeat_boto3():
)["taskToken"] )["taskToken"]
resp = client.record_activity_task_heartbeat(taskToken=activity_token) resp = client.record_activity_task_heartbeat(taskToken=activity_token)
resp.should.have.key("cancelRequested").equal(False) assert resp["cancelRequested"] is False
@mock_swf @mock_swf
@ -241,15 +243,15 @@ def test_record_activity_task_heartbeat_with_wrong_token_boto3():
client.respond_decision_task_completed( client.respond_decision_task_completed(
taskToken=decision_token, decisions=[SCHEDULE_ACTIVITY_TASK_DECISION] taskToken=decision_token, decisions=[SCHEDULE_ACTIVITY_TASK_DECISION]
) )
client.poll_for_activity_task( _ = client.poll_for_activity_task(
domain="test-domain", taskList={"name": "activity-task-list"} domain="test-domain", taskList={"name": "activity-task-list"}
)["taskToken"] )["taskToken"]
with pytest.raises(ClientError) as ex: with pytest.raises(ClientError) as ex:
client.record_activity_task_heartbeat(taskToken="bad-token") client.record_activity_task_heartbeat(taskToken="bad-token")
ex.value.response["Error"]["Code"].should.equal("ValidationException") assert ex.value.response["Error"]["Code"] == "ValidationException"
ex.value.response["Error"]["Message"].should.equal("Invalid token") assert ex.value.response["Error"]["Message"] == "Invalid token"
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
@mock_swf @mock_swf
@ -278,6 +280,6 @@ def test_record_activity_task_heartbeat_sets_details_in_case_of_timeout_boto3():
domain="test-domain", domain="test-domain",
execution={"runId": client.run_id, "workflowId": "uid-abcd1234"}, execution={"runId": client.run_id, "workflowId": "uid-abcd1234"},
) )
resp["events"][-2]["eventType"].should.equal("ActivityTaskTimedOut") assert resp["events"][-2]["eventType"] == "ActivityTaskTimedOut"
attrs = resp["events"][-2]["activityTaskTimedOutEventAttributes"] attrs = resp["events"][-2]["activityTaskTimedOutEventAttributes"]
attrs["details"].should.equal("some progress details") assert attrs["details"] == "some progress details"

View File

@ -1,6 +1,5 @@
import boto3 import boto3
from botocore.exceptions import ClientError from botocore.exceptions import ClientError
import sure # noqa # pylint: disable=unused-import
import pytest import pytest
from moto import mock_swf from moto import mock_swf
@ -20,10 +19,10 @@ def test_register_activity_type_boto3():
types = client.list_activity_types( types = client.list_activity_types(
domain="test-domain", registrationStatus="REGISTERED" domain="test-domain", registrationStatus="REGISTERED"
)["typeInfos"] )["typeInfos"]
types.should.have.length_of(1) assert len(types) == 1
actype = types[0] actype = types[0]
actype["activityType"]["name"].should.equal("test-activity") assert actype["activityType"]["name"] == "test-activity"
actype["activityType"]["version"].should.equal("v1.0") assert actype["activityType"]["version"] == "v1.0"
@mock_swf @mock_swf
@ -40,11 +39,11 @@ def test_register_already_existing_activity_type_boto3():
client.register_activity_type( client.register_activity_type(
domain="test-domain", name="test-activity", version="v1.0" domain="test-domain", name="test-activity", version="v1.0"
) )
ex.value.response["Error"]["Code"].should.equal("TypeAlreadyExistsFault") assert ex.value.response["Error"]["Code"] == "TypeAlreadyExistsFault"
ex.value.response["Error"]["Message"].should.equal( assert ex.value.response["Error"]["Message"] == (
"ActivityType=[name=test-activity, version=v1.0]" "ActivityType=[name=test-activity, version=v1.0]"
) )
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
# ListActivityTypes endpoint # ListActivityTypes endpoint
@ -73,7 +72,7 @@ def test_list_activity_types_boto3():
names = [ names = [
activity_type["activityType"]["name"] for activity_type in types["typeInfos"] activity_type["activityType"]["name"] for activity_type in types["typeInfos"]
] ]
names.should.equal(["a-test-activity", "b-test-activity", "c-test-activity"]) assert names == ["a-test-activity", "b-test-activity", "c-test-activity"]
@mock_swf @mock_swf
@ -99,7 +98,7 @@ def test_list_activity_types_reverse_order_boto3():
names = [ names = [
activity_type["activityType"]["name"] for activity_type in types["typeInfos"] activity_type["activityType"]["name"] for activity_type in types["typeInfos"]
] ]
names.should.equal(["c-test-activity", "b-test-activity", "a-test-activity"]) assert names == ["c-test-activity", "b-test-activity", "a-test-activity"]
# DeprecateActivityType endpoint # DeprecateActivityType endpoint
@ -119,10 +118,10 @@ def test_deprecate_activity_type_boto3():
types = client.list_activity_types( types = client.list_activity_types(
domain="test-domain", registrationStatus="DEPRECATED" domain="test-domain", registrationStatus="DEPRECATED"
) )
types.should.have.key("typeInfos").being.length_of(1) assert len(types["typeInfos"]) == 1
actype = types["typeInfos"][0] actype = types["typeInfos"][0]
actype["activityType"]["name"].should.equal("test-activity") assert actype["activityType"]["name"] == "test-activity"
actype["activityType"]["version"].should.equal("v1.0") assert actype["activityType"]["version"] == "v1.0"
@mock_swf @mock_swf
@ -143,11 +142,11 @@ def test_deprecate_already_deprecated_activity_type_boto3():
domain="test-domain", domain="test-domain",
activityType={"name": "test-activity", "version": "v1.0"}, activityType={"name": "test-activity", "version": "v1.0"},
) )
ex.value.response["Error"]["Code"].should.equal("TypeDeprecatedFault") assert ex.value.response["Error"]["Code"] == "TypeDeprecatedFault"
ex.value.response["Error"]["Message"].should.equal( assert ex.value.response["Error"]["Message"] == (
"ActivityType=[name=test-activity, version=v1.0]" "ActivityType=[name=test-activity, version=v1.0]"
) )
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
@mock_swf @mock_swf
@ -162,11 +161,11 @@ def test_deprecate_non_existent_activity_type_boto3():
domain="test-domain", domain="test-domain",
activityType={"name": "test-activity", "version": "v1.0"}, activityType={"name": "test-activity", "version": "v1.0"},
) )
ex.value.response["Error"]["Code"].should.equal("UnknownResourceFault") assert ex.value.response["Error"]["Code"] == "UnknownResourceFault"
ex.value.response["Error"]["Message"].should.equal( assert ex.value.response["Error"]["Message"] == (
"Unknown type: ActivityType=[name=test-activity, version=v1.0]" "Unknown type: ActivityType=[name=test-activity, version=v1.0]"
) )
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
# DeprecateActivityType endpoint # DeprecateActivityType endpoint
@ -189,7 +188,7 @@ def test_undeprecate_activity_type():
resp = client.describe_activity_type( resp = client.describe_activity_type(
domain="test-domain", activityType={"name": "test-activity", "version": "v1.0"} domain="test-domain", activityType={"name": "test-activity", "version": "v1.0"}
) )
resp["typeInfo"]["status"].should.equal("REGISTERED") assert resp["typeInfo"]["status"] == "REGISTERED"
@mock_swf @mock_swf
@ -208,9 +207,11 @@ def test_undeprecate_already_undeprecated_activity_type():
domain="test-domain", activityType={"name": "test-activity", "version": "v1.0"} domain="test-domain", activityType={"name": "test-activity", "version": "v1.0"}
) )
client.undeprecate_activity_type.when.called_with( with pytest.raises(ClientError):
domain="test-domain", activityType={"name": "test-activity", "version": "v1.0"} client.undeprecate_activity_type(
).should.throw(ClientError) domain="test-domain",
activityType={"name": "test-activity", "version": "v1.0"},
)
@mock_swf @mock_swf
@ -223,9 +224,11 @@ def test_undeprecate_never_deprecated_activity_type():
domain="test-domain", name="test-activity", version="v1.0" domain="test-domain", name="test-activity", version="v1.0"
) )
client.undeprecate_activity_type.when.called_with( with pytest.raises(ClientError):
domain="test-domain", activityType={"name": "test-activity", "version": "v1.0"} client.undeprecate_activity_type(
).should.throw(ClientError) domain="test-domain",
activityType={"name": "test-activity", "version": "v1.0"},
)
@mock_swf @mock_swf
@ -235,9 +238,11 @@ def test_undeprecate_non_existent_activity_type():
name="test-domain", workflowExecutionRetentionPeriodInDays="60" name="test-domain", workflowExecutionRetentionPeriodInDays="60"
) )
client.undeprecate_activity_type.when.called_with( with pytest.raises(ClientError):
domain="test-domain", activityType={"name": "test-activity", "version": "v1.0"} client.undeprecate_activity_type(
).should.throw(ClientError) domain="test-domain",
activityType={"name": "test-activity", "version": "v1.0"},
)
# DescribeActivityType endpoint # DescribeActivityType endpoint
@ -258,11 +263,11 @@ def test_describe_activity_type_boto3():
actype = client.describe_activity_type( actype = client.describe_activity_type(
domain="test-domain", activityType={"name": "test-activity", "version": "v1.0"} domain="test-domain", activityType={"name": "test-activity", "version": "v1.0"}
) )
actype["configuration"]["defaultTaskList"]["name"].should.equal("foo") assert actype["configuration"]["defaultTaskList"]["name"] == "foo"
infos = actype["typeInfo"] infos = actype["typeInfo"]
infos["activityType"]["name"].should.equal("test-activity") assert infos["activityType"]["name"] == "test-activity"
infos["activityType"]["version"].should.equal("v1.0") assert infos["activityType"]["version"] == "v1.0"
infos["status"].should.equal("REGISTERED") assert infos["status"] == "REGISTERED"
@mock_swf @mock_swf
@ -277,8 +282,8 @@ def test_describe_non_existent_activity_type_boto3():
domain="test-domain", domain="test-domain",
activityType={"name": "test-activity", "version": "v1.0"}, activityType={"name": "test-activity", "version": "v1.0"},
) )
ex.value.response["Error"]["Code"].should.equal("UnknownResourceFault") assert ex.value.response["Error"]["Code"] == "UnknownResourceFault"
ex.value.response["Error"]["Message"].should.equal( assert ex.value.response["Error"]["Message"] == (
"Unknown type: ActivityType=[name=test-activity, version=v1.0]" "Unknown type: ActivityType=[name=test-activity, version=v1.0]"
) )
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400

View File

@ -1,9 +1,10 @@
from botocore.exceptions import ClientError
from datetime import datetime from datetime import datetime
import re
from time import sleep
from botocore.exceptions import ClientError
from dateutil.parser import parse as dtparse from dateutil.parser import parse as dtparse
from freezegun import freeze_time from freezegun import freeze_time
from time import sleep
import sure # noqa # pylint: disable=unused-import
import pytest import pytest
from moto import mock_swf, settings from moto import mock_swf, settings
@ -23,18 +24,20 @@ def test_poll_for_decision_task_when_one_boto3():
execution={"runId": client.run_id, "workflowId": "uid-abcd1234"}, execution={"runId": client.run_id, "workflowId": "uid-abcd1234"},
) )
types = [evt["eventType"] for evt in resp["events"]] types = [evt["eventType"] for evt in resp["events"]]
types.should.equal(["WorkflowExecutionStarted", "DecisionTaskScheduled"]) assert types == ["WorkflowExecutionStarted", "DecisionTaskScheduled"]
resp = client.poll_for_decision_task( resp = client.poll_for_decision_task(
domain="test-domain", taskList={"name": "queue"}, identity="srv01" domain="test-domain", taskList={"name": "queue"}, identity="srv01"
) )
types = [evt["eventType"] for evt in resp["events"]] types = [evt["eventType"] for evt in resp["events"]]
types.should.equal( assert types == [
["WorkflowExecutionStarted", "DecisionTaskScheduled", "DecisionTaskStarted"] "WorkflowExecutionStarted",
) "DecisionTaskScheduled",
"DecisionTaskStarted",
]
resp["events"][-1]["decisionTaskStartedEventAttributes"]["identity"].should.equal( assert (
"srv01" resp["events"][-1]["decisionTaskStartedEventAttributes"]["identity"] == "srv01"
) )
@ -75,14 +78,16 @@ def test_poll_for_decision_task_ensure_single_started_task():
resp = client.poll_for_decision_task( resp = client.poll_for_decision_task(
domain="test-domain", taskList={"name": "queue"} domain="test-domain", taskList={"name": "queue"}
) )
resp.should.have.key("taskToken") assert "taskToken" in resp
first_decision_task = resp["taskToken"] first_decision_task = resp["taskToken"]
# History should have just the decision task triggered on workflow start # History should have just the decision task triggered on workflow start
types = [evt["eventType"] for evt in resp["events"]] types = [evt["eventType"] for evt in resp["events"]]
types.should.equal( assert types == [
["WorkflowExecutionStarted", "DecisionTaskScheduled", "DecisionTaskStarted"] "WorkflowExecutionStarted",
) "DecisionTaskScheduled",
"DecisionTaskStarted",
]
# Schedule another decision task, before first one is completed # Schedule another decision task, before first one is completed
client.signal_workflow_execution( client.signal_workflow_execution(
@ -99,42 +104,38 @@ def test_poll_for_decision_task_ensure_single_started_task():
) )
assert resp["previousStartedEventId"] == 0 assert resp["previousStartedEventId"] == 0
assert resp["startedEventId"] == 0 assert resp["startedEventId"] == 0
assert resp.should_not.have.key("taskToken") assert "taskToken" not in resp
resp = client.get_workflow_execution_history( resp = client.get_workflow_execution_history(
domain="test-domain", domain="test-domain",
execution={"runId": client.run_id, "workflowId": "uid-abcd1234"}, execution={"runId": client.run_id, "workflowId": "uid-abcd1234"},
) )
types = [evt["eventType"] for evt in resp["events"]] types = [evt["eventType"] for evt in resp["events"]]
types.should.equal( assert types == [
[ "WorkflowExecutionStarted",
"WorkflowExecutionStarted", "DecisionTaskScheduled",
"DecisionTaskScheduled", "DecisionTaskStarted",
"DecisionTaskStarted", "WorkflowExecutionSignaled",
"WorkflowExecutionSignaled", "DecisionTaskScheduled",
"DecisionTaskScheduled", ]
]
)
client.respond_decision_task_completed(taskToken=first_decision_task) client.respond_decision_task_completed(taskToken=first_decision_task)
resp = client.poll_for_decision_task( resp = client.poll_for_decision_task(
domain="test-domain", taskList={"name": "queue"} domain="test-domain", taskList={"name": "queue"}
) )
resp.should.have.key("taskToken") assert "taskToken" in resp
types = [evt["eventType"] for evt in resp["events"]] types = [evt["eventType"] for evt in resp["events"]]
types.should.equal( assert types == [
[ "WorkflowExecutionStarted",
"WorkflowExecutionStarted", "DecisionTaskScheduled",
"DecisionTaskScheduled", "DecisionTaskStarted",
"DecisionTaskStarted", "WorkflowExecutionSignaled",
"WorkflowExecutionSignaled", "DecisionTaskScheduled",
"DecisionTaskScheduled", "DecisionTaskCompleted",
"DecisionTaskCompleted", "DecisionTaskStarted",
"DecisionTaskStarted", ]
]
)
@mock_swf @mock_swf
@ -146,7 +147,7 @@ def test_poll_for_decision_task_exclude_completed_executions():
execution={"runId": client.run_id, "workflowId": "uid-abcd1234"}, execution={"runId": client.run_id, "workflowId": "uid-abcd1234"},
) )
types = [evt["eventType"] for evt in resp["events"]] types = [evt["eventType"] for evt in resp["events"]]
types.should.equal(["WorkflowExecutionStarted", "DecisionTaskScheduled"]) assert types == ["WorkflowExecutionStarted", "DecisionTaskScheduled"]
client.terminate_workflow_execution( client.terminate_workflow_execution(
domain="test-domain", runId=client.run_id, workflowId="uid-abcd1234" domain="test-domain", runId=client.run_id, workflowId="uid-abcd1234"
@ -154,7 +155,7 @@ def test_poll_for_decision_task_exclude_completed_executions():
resp = client.poll_for_decision_task( resp = client.poll_for_decision_task(
domain="test-domain", taskList={"name": "queue"} domain="test-domain", taskList={"name": "queue"}
) )
resp.should_not.have.key("taskToken") assert "taskToken" not in resp
@mock_swf @mock_swf
@ -168,8 +169,8 @@ def test_poll_for_decision_task_when_none_boto3():
) )
# this is the DecisionTask representation you get from the real SWF # this is the DecisionTask representation you get from the real SWF
# after waiting 60s when there's no decision to be taken # after waiting 60s when there's no decision to be taken
resp.should.have.key("previousStartedEventId").equal(0) assert resp["previousStartedEventId"] == 0
resp.should.have.key("startedEventId").equal(0) assert resp["startedEventId"] == 0
@mock_swf @mock_swf
@ -178,8 +179,8 @@ def test_poll_for_decision_task_on_non_existent_queue_boto3():
resp = client.poll_for_decision_task( resp = client.poll_for_decision_task(
domain="test-domain", taskList={"name": "non-existent-queue"} domain="test-domain", taskList={"name": "non-existent-queue"}
) )
resp.should.have.key("previousStartedEventId").equal(0) assert resp["previousStartedEventId"] == 0
resp.should.have.key("startedEventId").equal(0) assert resp["startedEventId"] == 0
@mock_swf @mock_swf
@ -189,9 +190,11 @@ def test_poll_for_decision_task_with_reverse_order_boto3():
domain="test-domain", taskList={"name": "queue"}, reverseOrder=True domain="test-domain", taskList={"name": "queue"}, reverseOrder=True
) )
types = [evt["eventType"] for evt in resp["events"]] types = [evt["eventType"] for evt in resp["events"]]
types.should.equal( assert types == [
["DecisionTaskStarted", "DecisionTaskScheduled", "WorkflowExecutionStarted"] "DecisionTaskStarted",
) "DecisionTaskScheduled",
"WorkflowExecutionStarted",
]
# CountPendingDecisionTasks endpoint # CountPendingDecisionTasks endpoint
@ -204,8 +207,8 @@ def test_count_pending_decision_tasks_boto3():
resp = client.count_pending_decision_tasks( resp = client.count_pending_decision_tasks(
domain="test-domain", taskList={"name": "queue"} domain="test-domain", taskList={"name": "queue"}
) )
resp.should.have.key("count").equal(1) assert resp["count"] == 1
resp.should.have.key("truncated").equal(False) assert resp["truncated"] is False
@mock_swf @mock_swf
@ -214,8 +217,8 @@ def test_count_pending_decision_tasks_on_non_existent_task_list_boto3():
resp = client.count_pending_decision_tasks( resp = client.count_pending_decision_tasks(
domain="test-domain", taskList={"name": "non-existent"} domain="test-domain", taskList={"name": "non-existent"}
) )
resp.should.have.key("count").equal(0) assert resp["count"] == 0
resp.should.have.key("truncated").equal(False) assert resp["truncated"] is False
@mock_swf @mock_swf
@ -229,8 +232,8 @@ def test_count_pending_decision_tasks_after_decision_completes_boto3():
resp = client.count_pending_decision_tasks( resp = client.count_pending_decision_tasks(
domain="test-domain", taskList={"name": "queue"} domain="test-domain", taskList={"name": "queue"}
) )
resp.should.have.key("count").equal(0) assert resp["count"] == 0
resp.should.have.key("truncated").equal(False) assert resp["truncated"] is False
# RespondDecisionTaskCompleted endpoint # RespondDecisionTaskCompleted endpoint
@ -253,28 +256,24 @@ def test_respond_decision_task_completed_with_no_decision_boto3():
execution={"runId": client.run_id, "workflowId": "uid-abcd1234"}, execution={"runId": client.run_id, "workflowId": "uid-abcd1234"},
) )
types = [evt["eventType"] for evt in resp["events"]] types = [evt["eventType"] for evt in resp["events"]]
types.should.equal( assert types == [
[ "WorkflowExecutionStarted",
"WorkflowExecutionStarted", "DecisionTaskScheduled",
"DecisionTaskScheduled", "DecisionTaskStarted",
"DecisionTaskStarted", "DecisionTaskCompleted",
"DecisionTaskCompleted", ]
]
)
evt = resp["events"][-1] evt = resp["events"][-1]
evt["decisionTaskCompletedEventAttributes"].should.equal( assert evt["decisionTaskCompletedEventAttributes"] == {
{ "executionContext": "free-form context",
"executionContext": "free-form context", "scheduledEventId": 2,
"scheduledEventId": 2, "startedEventId": 3,
"startedEventId": 3, }
}
)
resp = client.describe_workflow_execution( resp = client.describe_workflow_execution(
domain="test-domain", domain="test-domain",
execution={"runId": client.run_id, "workflowId": "uid-abcd1234"}, execution={"runId": client.run_id, "workflowId": "uid-abcd1234"},
) )
resp["latestExecutionContext"].should.equal("free-form context") assert resp["latestExecutionContext"] == "free-form context"
@mock_swf @mock_swf
@ -283,9 +282,9 @@ def test_respond_decision_task_completed_with_wrong_token_boto3():
client.poll_for_decision_task(domain="test-domain", taskList={"name": "queue"}) client.poll_for_decision_task(domain="test-domain", taskList={"name": "queue"})
with pytest.raises(ClientError) as ex: with pytest.raises(ClientError) as ex:
client.respond_decision_task_completed(taskToken="not-a-correct-token") client.respond_decision_task_completed(taskToken="not-a-correct-token")
ex.value.response["Error"]["Code"].should.equal("ValidationException") assert ex.value.response["Error"]["Code"] == "ValidationException"
ex.value.response["Error"]["Message"].should.equal("Invalid token") assert ex.value.response["Error"]["Message"] == "Invalid token"
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
@mock_swf @mock_swf
@ -300,11 +299,11 @@ def test_respond_decision_task_completed_on_close_workflow_execution_boto3():
with pytest.raises(ClientError) as ex: with pytest.raises(ClientError) as ex:
client.respond_decision_task_completed(taskToken=task_token) client.respond_decision_task_completed(taskToken=task_token)
ex.value.response["Error"]["Code"].should.equal("UnknownResourceFault") assert ex.value.response["Error"]["Code"] == "UnknownResourceFault"
ex.value.response["Error"]["Message"].should.equal( assert ex.value.response["Error"]["Message"] == (
f"Unknown execution: WorkflowExecution=[workflowId=uid-abcd1234, runId={client.run_id}]" f"Unknown execution: WorkflowExecution=[workflowId=uid-abcd1234, runId={client.run_id}]"
) )
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
@mock_swf @mock_swf
@ -318,11 +317,11 @@ def test_respond_decision_task_completed_with_task_already_completed_boto3():
with pytest.raises(ClientError) as ex: with pytest.raises(ClientError) as ex:
client.respond_decision_task_completed(taskToken=task_token) client.respond_decision_task_completed(taskToken=task_token)
ex.value.response["Error"]["Code"].should.equal("UnknownResourceFault") assert ex.value.response["Error"]["Code"] == "UnknownResourceFault"
ex.value.response["Error"]["Message"].should.equal( assert ex.value.response["Error"]["Message"] == (
"Unknown decision task, scheduledEventId = 2" "Unknown decision task, scheduledEventId = 2"
) )
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
@mock_swf @mock_swf
@ -346,18 +345,17 @@ def test_respond_decision_task_completed_with_complete_workflow_execution_boto3(
execution={"runId": client.run_id, "workflowId": "uid-abcd1234"}, execution={"runId": client.run_id, "workflowId": "uid-abcd1234"},
) )
types = [evt["eventType"] for evt in resp["events"]] types = [evt["eventType"] for evt in resp["events"]]
types.should.equal( assert types == [
[ "WorkflowExecutionStarted",
"WorkflowExecutionStarted", "DecisionTaskScheduled",
"DecisionTaskScheduled", "DecisionTaskStarted",
"DecisionTaskStarted", "DecisionTaskCompleted",
"DecisionTaskCompleted", "WorkflowExecutionCompleted",
"WorkflowExecutionCompleted", ]
] assert (
resp["events"][-1]["workflowExecutionCompletedEventAttributes"]["result"]
== "foo bar"
) )
resp["events"][-1]["workflowExecutionCompletedEventAttributes"][
"result"
].should.equal("foo bar")
@mock_swf @mock_swf
@ -377,11 +375,11 @@ def test_respond_decision_task_completed_with_close_decision_not_last_boto3():
client.respond_decision_task_completed( client.respond_decision_task_completed(
taskToken=task_token, decisions=decisions taskToken=task_token, decisions=decisions
) )
ex.value.response["Error"]["Code"].should.equal("ValidationException") assert ex.value.response["Error"]["Code"] == "ValidationException"
ex.value.response["Error"]["Message"].should.equal( assert ex.value.response["Error"]["Message"] == (
"Close must be last decision in list" "Close must be last decision in list"
) )
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
@mock_swf @mock_swf
@ -401,11 +399,12 @@ def test_respond_decision_task_completed_with_invalid_decision_type_boto3():
client.respond_decision_task_completed( client.respond_decision_task_completed(
taskToken=task_token, decisions=decisions taskToken=task_token, decisions=decisions
) )
ex.value.response["Error"]["Code"].should.equal("ValidationException") assert ex.value.response["Error"]["Code"] == "ValidationException"
ex.value.response["Error"]["Message"].should.match( assert re.search(
"Value 'BadDecisionType' at 'decisions.1.member.decisionType'" "Value 'BadDecisionType' at 'decisions.1.member.decisionType'",
ex.value.response["Error"]["Message"],
) )
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
@mock_swf @mock_swf
@ -422,11 +421,16 @@ def test_respond_decision_task_completed_with_missing_attributes_totally_boto3()
client.respond_decision_task_completed( client.respond_decision_task_completed(
taskToken=task_token, decisions=decisions taskToken=task_token, decisions=decisions
) )
ex.value.response["Error"]["Code"].should.equal("ValidationException") assert ex.value.response["Error"]["Code"] == "ValidationException"
ex.value.response["Error"]["Message"].should.match( assert re.search(
"Value null at 'decisions.1.member.startTimerDecisionAttributes.timerId' failed to satisfy constraint" (
"Value null at "
"'decisions.1.member.startTimerDecisionAttributes.timerId' "
"failed to satisfy constraint"
),
ex.value.response["Error"]["Message"],
) )
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
@mock_swf @mock_swf
@ -453,18 +457,16 @@ def test_respond_decision_task_completed_with_fail_workflow_execution_boto3():
execution={"runId": client.run_id, "workflowId": "uid-abcd1234"}, execution={"runId": client.run_id, "workflowId": "uid-abcd1234"},
) )
types = [evt["eventType"] for evt in resp["events"]] types = [evt["eventType"] for evt in resp["events"]]
types.should.equal( assert types == [
[ "WorkflowExecutionStarted",
"WorkflowExecutionStarted", "DecisionTaskScheduled",
"DecisionTaskScheduled", "DecisionTaskStarted",
"DecisionTaskStarted", "DecisionTaskCompleted",
"DecisionTaskCompleted", "WorkflowExecutionFailed",
"WorkflowExecutionFailed", ]
]
)
attrs = resp["events"][-1]["workflowExecutionFailedEventAttributes"] attrs = resp["events"][-1]["workflowExecutionFailedEventAttributes"]
attrs["reason"].should.equal("my rules") assert attrs["reason"] == "my rules"
attrs["details"].should.equal("foo") assert attrs["details"] == "foo"
@mock_swf @mock_swf
@ -495,34 +497,30 @@ def test_respond_decision_task_completed_with_schedule_activity_task_boto3():
execution={"runId": client.run_id, "workflowId": "uid-abcd1234"}, execution={"runId": client.run_id, "workflowId": "uid-abcd1234"},
) )
types = [evt["eventType"] for evt in resp["events"]] types = [evt["eventType"] for evt in resp["events"]]
types.should.equal( assert types == [
[ "WorkflowExecutionStarted",
"WorkflowExecutionStarted", "DecisionTaskScheduled",
"DecisionTaskScheduled", "DecisionTaskStarted",
"DecisionTaskStarted", "DecisionTaskCompleted",
"DecisionTaskCompleted", "ActivityTaskScheduled",
"ActivityTaskScheduled", ]
] assert resp["events"][-1]["activityTaskScheduledEventAttributes"] == {
) "decisionTaskCompletedEventId": 4,
resp["events"][-1]["activityTaskScheduledEventAttributes"].should.equal( "activityId": "my-activity-001",
{ "activityType": {"name": "test-activity", "version": "v1.1"},
"decisionTaskCompletedEventId": 4, "heartbeatTimeout": "60",
"activityId": "my-activity-001", "input": "123",
"activityType": {"name": "test-activity", "version": "v1.1"}, "taskList": {"name": "my-task-list"},
"heartbeatTimeout": "60", }
"input": "123",
"taskList": {"name": "my-task-list"},
}
)
resp = client.describe_workflow_execution( resp = client.describe_workflow_execution(
domain="test-domain", domain="test-domain",
execution={"runId": client.run_id, "workflowId": "uid-abcd1234"}, execution={"runId": client.run_id, "workflowId": "uid-abcd1234"},
) )
resp["latestActivityTaskTimestamp"].should.be.a(datetime) assert isinstance(resp["latestActivityTaskTimestamp"], datetime)
if not settings.TEST_SERVER_MODE: if not settings.TEST_SERVER_MODE:
ts = resp["latestActivityTaskTimestamp"] ts = resp["latestActivityTaskTimestamp"]
ts.should.equal(dtparse("2015-01-01 12:00:00 UTC")) assert ts == dtparse("2015-01-01 12:00:00 UTC")
@mock_swf @mock_swf
@ -546,18 +544,17 @@ def test_record_marker_decision():
execution={"runId": client.run_id, "workflowId": "uid-abcd1234"}, execution={"runId": client.run_id, "workflowId": "uid-abcd1234"},
) )
types = [evt["eventType"] for evt in resp["events"]] types = [evt["eventType"] for evt in resp["events"]]
types.should.equal( assert types == [
[ "WorkflowExecutionStarted",
"WorkflowExecutionStarted", "DecisionTaskScheduled",
"DecisionTaskScheduled", "DecisionTaskStarted",
"DecisionTaskStarted", "DecisionTaskCompleted",
"DecisionTaskCompleted", "MarkerRecorded",
"MarkerRecorded", ]
] assert resp["events"][-1]["markerRecordedEventAttributes"] == {
) "decisionTaskCompletedEventId": 4,
resp["events"][-1]["markerRecordedEventAttributes"].should.equal( "markerName": "TheMarker",
{"decisionTaskCompletedEventId": 4, "markerName": "TheMarker"} }
)
@mock_swf @mock_swf
@ -585,27 +582,24 @@ def test_start_and_fire_timer_decision():
execution={"runId": client.run_id, "workflowId": "uid-abcd1234"}, execution={"runId": client.run_id, "workflowId": "uid-abcd1234"},
) )
types = [evt["eventType"] for evt in resp["events"]] types = [evt["eventType"] for evt in resp["events"]]
types.should.equal( assert types == [
[ "WorkflowExecutionStarted",
"WorkflowExecutionStarted", "DecisionTaskScheduled",
"DecisionTaskScheduled", "DecisionTaskStarted",
"DecisionTaskStarted", "DecisionTaskCompleted",
"DecisionTaskCompleted", "TimerStarted",
"TimerStarted", "TimerFired",
"TimerFired", "DecisionTaskScheduled",
"DecisionTaskScheduled", ]
] assert resp["events"][-3]["timerStartedEventAttributes"] == {
) "decisionTaskCompletedEventId": 4,
resp["events"][-3]["timerStartedEventAttributes"].should.equal( "startToFireTimeout": "1",
{ "timerId": "timer1",
"decisionTaskCompletedEventId": 4, }
"startToFireTimeout": "1", assert resp["events"][-2]["timerFiredEventAttributes"] == {
"timerId": "timer1", "startedEventId": 5,
} "timerId": "timer1",
) }
resp["events"][-2]["timerFiredEventAttributes"].should.equal(
{"startedEventId": 5, "timerId": "timer1"}
)
@mock_swf @mock_swf
@ -631,23 +625,22 @@ def test_cancel_workflow_decision():
execution={"runId": client.run_id, "workflowId": "uid-abcd1234"}, execution={"runId": client.run_id, "workflowId": "uid-abcd1234"},
) )
types = [evt["eventType"] for evt in resp["events"]] types = [evt["eventType"] for evt in resp["events"]]
types.should.equal( assert types == [
[ "WorkflowExecutionStarted",
"WorkflowExecutionStarted", "DecisionTaskScheduled",
"DecisionTaskScheduled", "DecisionTaskStarted",
"DecisionTaskStarted", "DecisionTaskCompleted",
"DecisionTaskCompleted", "WorkflowExecutionCanceled",
"WorkflowExecutionCanceled", ]
] assert resp["events"][-1]["workflowExecutionCanceledEventAttributes"] == {
) "decisionTaskCompletedEventId": 4,
resp["events"][-1]["workflowExecutionCanceledEventAttributes"].should.equal( "details": "decide to cancel",
{"decisionTaskCompletedEventId": 4, "details": "decide to cancel"} }
)
workflow_result = client.describe_workflow_execution( workflow_result = client.describe_workflow_execution(
domain="test-domain", domain="test-domain",
execution={"runId": client.run_id, "workflowId": "uid-abcd1234"}, execution={"runId": client.run_id, "workflowId": "uid-abcd1234"},
)["executionInfo"] )["executionInfo"]
workflow_result.should.contain("closeTimestamp") assert "closeTimestamp" in workflow_result
workflow_result["executionStatus"].should.equal("CLOSED") assert workflow_result["executionStatus"] == "CLOSED"
workflow_result["closeStatus"].should.equal("CANCELED") assert workflow_result["closeStatus"] == "CANCELED"
workflow_result["cancelRequested"].should.equal(True) assert workflow_result["cancelRequested"] is True

View File

@ -1,215 +1,209 @@
import boto3 import boto3
from botocore.exceptions import ClientError from botocore.exceptions import ClientError
import sure # noqa # pylint: disable=unused-import import pytest
import pytest
from moto import mock_swf
from moto import mock_swf from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID
from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID
# RegisterDomain endpoint
# RegisterDomain endpoint @mock_swf
@mock_swf def test_register_domain_boto3():
def test_register_domain_boto3(): client = boto3.client("swf", region_name="us-west-1")
client = boto3.client("swf", region_name="us-west-1") client.register_domain(
client.register_domain( name="test-domain",
name="test-domain", workflowExecutionRetentionPeriodInDays="60",
workflowExecutionRetentionPeriodInDays="60", description="A test domain",
description="A test domain", )
)
all_domains = client.list_domains(registrationStatus="REGISTERED")
all_domains = client.list_domains(registrationStatus="REGISTERED") assert len(all_domains["domainInfos"]) == 1
all_domains.should.have.key("domainInfos").being.length_of(1) domain = all_domains["domainInfos"][0]
domain = all_domains["domainInfos"][0]
assert domain["name"] == "test-domain"
domain["name"].should.equal("test-domain") assert domain["status"] == "REGISTERED"
domain["status"].should.equal("REGISTERED") assert domain["description"] == "A test domain"
domain["description"].should.equal("A test domain") assert domain["arn"] == f"arn:aws:swf:us-west-1:{ACCOUNT_ID}:/domain/test-domain"
domain["arn"].should.equal(
f"arn:aws:swf:us-west-1:{ACCOUNT_ID}:/domain/test-domain"
) @mock_swf
def test_register_already_existing_domain_boto3():
client = boto3.client("swf", region_name="us-west-1")
@mock_swf client.register_domain(
def test_register_already_existing_domain_boto3(): name="test-domain",
client = boto3.client("swf", region_name="us-west-1") workflowExecutionRetentionPeriodInDays="60",
client.register_domain( description="A test domain",
name="test-domain", )
workflowExecutionRetentionPeriodInDays="60",
description="A test domain", with pytest.raises(ClientError) as ex:
) client.register_domain(
name="test-domain",
with pytest.raises(ClientError) as ex: workflowExecutionRetentionPeriodInDays="60",
client.register_domain( description="A test domain",
name="test-domain", )
workflowExecutionRetentionPeriodInDays="60", assert ex.value.response["Error"]["Code"] == "DomainAlreadyExistsFault"
description="A test domain", assert ex.value.response["Error"]["Message"] == "test-domain"
) assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
ex.value.response["Error"]["Code"].should.equal("DomainAlreadyExistsFault")
ex.value.response["Error"]["Message"].should.equal("test-domain")
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) # ListDomains endpoint
@mock_swf
def test_list_domains_order_boto3():
# ListDomains endpoint client = boto3.client("swf", region_name="us-west-1")
@mock_swf client.register_domain(
def test_list_domains_order_boto3(): name="b-test-domain", workflowExecutionRetentionPeriodInDays="60"
client = boto3.client("swf", region_name="us-west-1") )
client.register_domain( client.register_domain(
name="b-test-domain", workflowExecutionRetentionPeriodInDays="60" name="a-test-domain", workflowExecutionRetentionPeriodInDays="60"
) )
client.register_domain( client.register_domain(
name="a-test-domain", workflowExecutionRetentionPeriodInDays="60" name="c-test-domain", workflowExecutionRetentionPeriodInDays="60"
) )
client.register_domain(
name="c-test-domain", workflowExecutionRetentionPeriodInDays="60" all_domains = client.list_domains(registrationStatus="REGISTERED")
) assert len(all_domains["domainInfos"]) == 3
all_domains = client.list_domains(registrationStatus="REGISTERED") names = [domain["name"] for domain in all_domains["domainInfos"]]
all_domains.should.have.key("domainInfos").being.length_of(3) assert names == ["a-test-domain", "b-test-domain", "c-test-domain"]
names = [domain["name"] for domain in all_domains["domainInfos"]]
names.should.equal(["a-test-domain", "b-test-domain", "c-test-domain"]) @mock_swf
def test_list_domains_reverse_order_boto3():
client = boto3.client("swf", region_name="us-west-1")
@mock_swf client.register_domain(
def test_list_domains_reverse_order_boto3(): name="b-test-domain", workflowExecutionRetentionPeriodInDays="60"
client = boto3.client("swf", region_name="us-west-1") )
client.register_domain( client.register_domain(
name="b-test-domain", workflowExecutionRetentionPeriodInDays="60" name="a-test-domain", workflowExecutionRetentionPeriodInDays="60"
) )
client.register_domain( client.register_domain(
name="a-test-domain", workflowExecutionRetentionPeriodInDays="60" name="c-test-domain", workflowExecutionRetentionPeriodInDays="60"
) )
client.register_domain(
name="c-test-domain", workflowExecutionRetentionPeriodInDays="60" all_domains = client.list_domains(
) registrationStatus="REGISTERED", reverseOrder=True
)
all_domains = client.list_domains( assert len(all_domains["domainInfos"]) == 3
registrationStatus="REGISTERED", reverseOrder=True
) names = [domain["name"] for domain in all_domains["domainInfos"]]
all_domains.should.have.key("domainInfos").being.length_of(3) assert names == ["c-test-domain", "b-test-domain", "a-test-domain"]
names = [domain["name"] for domain in all_domains["domainInfos"]]
names.should.equal(["c-test-domain", "b-test-domain", "a-test-domain"]) # DeprecateDomain endpoint
@mock_swf
def test_deprecate_domain_boto3():
# DeprecateDomain endpoint client = boto3.client("swf", region_name="us-west-1")
@mock_swf client.register_domain(
def test_deprecate_domain_boto3(): name="test-domain", workflowExecutionRetentionPeriodInDays="60"
client = boto3.client("swf", region_name="us-west-1") )
client.register_domain( client.deprecate_domain(name="test-domain")
name="test-domain", workflowExecutionRetentionPeriodInDays="60"
) all_domains = client.list_domains(registrationStatus="REGISTERED")
client.deprecate_domain(name="test-domain") assert len(all_domains["domainInfos"]) == 0
all_domains = client.list_domains(registrationStatus="REGISTERED") all_domains = client.list_domains(registrationStatus="DEPRECATED")
all_domains.should.have.key("domainInfos").being.length_of(0) assert len(all_domains["domainInfos"]) == 1
all_domains = client.list_domains(registrationStatus="DEPRECATED") domain = all_domains["domainInfos"][0]
all_domains.should.have.key("domainInfos").being.length_of(1) assert domain["name"] == "test-domain"
domain = all_domains["domainInfos"][0]
domain["name"].should.equal("test-domain") @mock_swf
def test_deprecate_already_deprecated_domain_boto3():
client = boto3.client("swf", region_name="us-west-1")
@mock_swf client.register_domain(
def test_deprecate_already_deprecated_domain_boto3(): name="test-domain", workflowExecutionRetentionPeriodInDays="60"
client = boto3.client("swf", region_name="us-west-1") )
client.register_domain( client.deprecate_domain(name="test-domain")
name="test-domain", workflowExecutionRetentionPeriodInDays="60"
) with pytest.raises(ClientError) as ex:
client.deprecate_domain(name="test-domain") client.deprecate_domain(name="test-domain")
assert ex.value.response["Error"]["Code"] == "DomainDeprecatedFault"
with pytest.raises(ClientError) as ex: assert ex.value.response["Error"]["Message"] == "test-domain"
client.deprecate_domain(name="test-domain") assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
ex.value.response["Error"]["Code"].should.equal("DomainDeprecatedFault")
ex.value.response["Error"]["Message"].should.equal("test-domain")
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) @mock_swf
def test_deprecate_non_existent_domain_boto3():
client = boto3.client("swf", region_name="us-west-1")
@mock_swf
def test_deprecate_non_existent_domain_boto3(): with pytest.raises(ClientError) as ex:
client = boto3.client("swf", region_name="us-west-1") client.deprecate_domain(name="non-existent")
assert ex.value.response["Error"]["Code"] == "UnknownResourceFault"
with pytest.raises(ClientError) as ex: assert ex.value.response["Error"]["Message"] == "Unknown domain: non-existent"
client.deprecate_domain(name="non-existent") assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
ex.value.response["Error"]["Code"].should.equal("UnknownResourceFault")
ex.value.response["Error"]["Message"].should.equal("Unknown domain: non-existent")
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) # UndeprecateDomain endpoint
@mock_swf
def test_undeprecate_domain():
# UndeprecateDomain endpoint client = boto3.client("swf", region_name="us-east-1")
@mock_swf client.register_domain(
def test_undeprecate_domain(): name="test-domain", workflowExecutionRetentionPeriodInDays="60"
client = boto3.client("swf", region_name="us-east-1") )
client.register_domain( client.deprecate_domain(name="test-domain")
name="test-domain", workflowExecutionRetentionPeriodInDays="60" client.undeprecate_domain(name="test-domain")
)
client.deprecate_domain(name="test-domain") resp = client.describe_domain(name="test-domain")
client.undeprecate_domain(name="test-domain")
assert resp["domainInfo"]["status"] == "REGISTERED"
resp = client.describe_domain(name="test-domain")
resp["domainInfo"]["status"].should.equal("REGISTERED") @mock_swf
def test_undeprecate_already_undeprecated_domain():
client = boto3.client("swf", region_name="us-east-1")
@mock_swf client.register_domain(
def test_undeprecate_already_undeprecated_domain(): name="test-domain", workflowExecutionRetentionPeriodInDays="60"
client = boto3.client("swf", region_name="us-east-1") )
client.register_domain( client.deprecate_domain(name="test-domain")
name="test-domain", workflowExecutionRetentionPeriodInDays="60" client.undeprecate_domain(name="test-domain")
)
client.deprecate_domain(name="test-domain") with pytest.raises(ClientError):
client.undeprecate_domain(name="test-domain") client.undeprecate_domain(name="test-domain")
client.undeprecate_domain.when.called_with(name="test-domain").should.throw(
ClientError @mock_swf
) def test_undeprecate_never_deprecated_domain():
client = boto3.client("swf", region_name="us-east-1")
client.register_domain(
@mock_swf name="test-domain", workflowExecutionRetentionPeriodInDays="60"
def test_undeprecate_never_deprecated_domain(): )
client = boto3.client("swf", region_name="us-east-1")
client.register_domain( with pytest.raises(ClientError):
name="test-domain", workflowExecutionRetentionPeriodInDays="60" client.undeprecate_domain(name="test-domain")
)
client.undeprecate_domain.when.called_with(name="test-domain").should.throw( @mock_swf
ClientError def test_undeprecate_non_existent_domain():
) client = boto3.client("swf", region_name="us-east-1")
with pytest.raises(ClientError):
@mock_swf client.undeprecate_domain(name="non-existent")
def test_undeprecate_non_existent_domain():
client = boto3.client("swf", region_name="us-east-1")
# DescribeDomain endpoint
client.undeprecate_domain.when.called_with(name="non-existent").should.throw( @mock_swf
ClientError def test_describe_domain_boto3():
) client = boto3.client("swf", region_name="us-east-1")
client.register_domain(
name="test-domain",
# DescribeDomain endpoint workflowExecutionRetentionPeriodInDays="60",
@mock_swf description="A test domain",
def test_describe_domain_boto3(): )
client = boto3.client("swf", region_name="us-east-1")
client.register_domain( domain = client.describe_domain(name="test-domain")
name="test-domain", assert domain["configuration"]["workflowExecutionRetentionPeriodInDays"] == "60"
workflowExecutionRetentionPeriodInDays="60", assert domain["domainInfo"]["description"] == "A test domain"
description="A test domain", assert domain["domainInfo"]["name"] == "test-domain"
) assert domain["domainInfo"]["status"] == "REGISTERED"
domain = client.describe_domain(name="test-domain")
domain["configuration"]["workflowExecutionRetentionPeriodInDays"].should.equal("60") @mock_swf
domain["domainInfo"]["description"].should.equal("A test domain") def test_describe_non_existent_domain_boto3():
domain["domainInfo"]["name"].should.equal("test-domain") client = boto3.client("swf", region_name="us-west-1")
domain["domainInfo"]["status"].should.equal("REGISTERED")
with pytest.raises(ClientError) as ex:
client.describe_domain(name="non-existent")
@mock_swf assert ex.value.response["Error"]["Code"] == "UnknownResourceFault"
def test_describe_non_existent_domain_boto3(): assert ex.value.response["Error"]["Message"] == "Unknown domain: non-existent"
client = boto3.client("swf", region_name="us-west-1") assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
with pytest.raises(ClientError) as ex:
client.describe_domain(name="non-existent")
ex.value.response["Error"]["Code"].should.equal("UnknownResourceFault")
ex.value.response["Error"]["Message"].should.equal("Unknown domain: non-existent")
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400)

View File

@ -1,8 +1,8 @@
from datetime import datetime from datetime import datetime
from unittest import SkipTest
from dateutil.parser import parse as dtparse from dateutil.parser import parse as dtparse
from freezegun import freeze_time from freezegun import freeze_time
import sure # noqa # pylint: disable=unused-import
from unittest import SkipTest
from moto import mock_swf, settings from moto import mock_swf, settings
@ -35,7 +35,7 @@ def test_activity_task_heartbeat_timeout_boto3():
domain="test-domain", domain="test-domain",
execution={"runId": client.run_id, "workflowId": "uid-abcd1234"}, execution={"runId": client.run_id, "workflowId": "uid-abcd1234"},
) )
resp["events"][-1]["eventType"].should.equal("ActivityTaskStarted") assert resp["events"][-1]["eventType"] == "ActivityTaskStarted"
with freeze_time("2015-01-01 12:05:30 UTC"): with freeze_time("2015-01-01 12:05:30 UTC"):
# => Activity Task Heartbeat timeout reached!! # => Activity Task Heartbeat timeout reached!!
@ -44,13 +44,13 @@ def test_activity_task_heartbeat_timeout_boto3():
execution={"runId": client.run_id, "workflowId": "uid-abcd1234"}, execution={"runId": client.run_id, "workflowId": "uid-abcd1234"},
) )
resp["events"][-2]["eventType"].should.equal("ActivityTaskTimedOut") assert resp["events"][-2]["eventType"] == "ActivityTaskTimedOut"
attrs = resp["events"][-2]["activityTaskTimedOutEventAttributes"] attrs = resp["events"][-2]["activityTaskTimedOutEventAttributes"]
attrs["timeoutType"].should.equal("HEARTBEAT") assert attrs["timeoutType"] == "HEARTBEAT"
# checks that event has been emitted at 12:05:00, not 12:05:30 # checks that event has been emitted at 12:05:00, not 12:05:30
resp["events"][-2]["eventTimestamp"].should.be.a(datetime) assert isinstance(resp["events"][-2]["eventTimestamp"], datetime)
ts = resp["events"][-2]["eventTimestamp"] ts = resp["events"][-2]["eventTimestamp"]
ts.should.equal(dtparse("2015-01-01 12:05:00 UTC")) assert ts == dtparse("2015-01-01 12:05:00 UTC")
# Decision Task Start to Close timeout # Decision Task Start to Close timeout
@ -71,9 +71,11 @@ def test_decision_task_start_to_close_timeout_boto3():
) )
event_types = [evt["eventType"] for evt in resp["events"]] event_types = [evt["eventType"] for evt in resp["events"]]
event_types.should.equal( assert event_types == [
["WorkflowExecutionStarted", "DecisionTaskScheduled", "DecisionTaskStarted"] "WorkflowExecutionStarted",
) "DecisionTaskScheduled",
"DecisionTaskStarted",
]
with freeze_time("2015-01-01 12:05:30 UTC"): with freeze_time("2015-01-01 12:05:30 UTC"):
# => Decision Task Start to Close timeout reached!! # => Decision Task Start to Close timeout reached!!
@ -83,27 +85,23 @@ def test_decision_task_start_to_close_timeout_boto3():
) )
event_types = [evt["eventType"] for evt in resp["events"]] event_types = [evt["eventType"] for evt in resp["events"]]
event_types.should.equal( assert event_types == [
[ "WorkflowExecutionStarted",
"WorkflowExecutionStarted", "DecisionTaskScheduled",
"DecisionTaskScheduled", "DecisionTaskStarted",
"DecisionTaskStarted", "DecisionTaskTimedOut",
"DecisionTaskTimedOut", "DecisionTaskScheduled",
"DecisionTaskScheduled", ]
]
)
attrs = resp["events"][-2]["decisionTaskTimedOutEventAttributes"] attrs = resp["events"][-2]["decisionTaskTimedOutEventAttributes"]
attrs.should.equal( assert attrs == {
{ "scheduledEventId": 2,
"scheduledEventId": 2, "startedEventId": 3,
"startedEventId": 3, "timeoutType": "START_TO_CLOSE",
"timeoutType": "START_TO_CLOSE", }
}
)
# checks that event has been emitted at 12:05:00, not 12:05:30 # checks that event has been emitted at 12:05:00, not 12:05:30
resp["events"][-2]["eventTimestamp"].should.be.a(datetime) assert isinstance(resp["events"][-2]["eventTimestamp"], datetime)
ts = resp["events"][-2]["eventTimestamp"] ts = resp["events"][-2]["eventTimestamp"]
ts.should.equal(dtparse("2015-01-01 12:05:00 UTC")) assert ts == dtparse("2015-01-01 12:05:00 UTC")
# Workflow Execution Start to Close timeout # Workflow Execution Start to Close timeout
@ -122,7 +120,7 @@ def test_workflow_execution_start_to_close_timeout_boto3():
) )
event_types = [evt["eventType"] for evt in resp["events"]] event_types = [evt["eventType"] for evt in resp["events"]]
event_types.should.equal(["WorkflowExecutionStarted", "DecisionTaskScheduled"]) assert event_types == ["WorkflowExecutionStarted", "DecisionTaskScheduled"]
with freeze_time("2015-01-01 14:00:30 UTC"): with freeze_time("2015-01-01 14:00:30 UTC"):
# => Workflow Execution Start to Close timeout reached!! # => Workflow Execution Start to Close timeout reached!!
@ -132,16 +130,14 @@ def test_workflow_execution_start_to_close_timeout_boto3():
) )
event_types = [evt["eventType"] for evt in resp["events"]] event_types = [evt["eventType"] for evt in resp["events"]]
event_types.should.equal( assert event_types == [
[ "WorkflowExecutionStarted",
"WorkflowExecutionStarted", "DecisionTaskScheduled",
"DecisionTaskScheduled", "WorkflowExecutionTimedOut",
"WorkflowExecutionTimedOut", ]
]
)
attrs = resp["events"][-1]["workflowExecutionTimedOutEventAttributes"] attrs = resp["events"][-1]["workflowExecutionTimedOutEventAttributes"]
attrs.should.equal({"childPolicy": "ABANDON", "timeoutType": "START_TO_CLOSE"}) assert attrs == {"childPolicy": "ABANDON", "timeoutType": "START_TO_CLOSE"}
# checks that event has been emitted at 14:00:00, not 14:00:30 # checks that event has been emitted at 14:00:00, not 14:00:30
resp["events"][-1]["eventTimestamp"].should.be.a(datetime) assert isinstance(resp["events"][-1]["eventTimestamp"], datetime)
ts = resp["events"][-1]["eventTimestamp"] ts = resp["events"][-1]["eventTimestamp"]
ts.should.equal(dtparse("2015-01-01 14:00:00 UTC")) assert ts == dtparse("2015-01-01 14:00:00 UTC")

View File

@ -1,8 +1,7 @@
import boto3
from botocore.exceptions import ClientError
from datetime import datetime, timedelta from datetime import datetime, timedelta
import sure # noqa # pylint: disable=unused-import import boto3
from botocore.exceptions import ClientError
import pytest import pytest
from moto import mock_swf from moto import mock_swf
@ -41,7 +40,7 @@ def test_start_workflow_execution_boto3():
workflowId="uid-abcd1234", workflowId="uid-abcd1234",
workflowType={"name": "test-workflow", "version": "v1.0"}, workflowType={"name": "test-workflow", "version": "v1.0"},
) )
wf.should.have.key("runId") assert "runId" in wf
@mock_swf @mock_swf
@ -66,7 +65,7 @@ def test_signal_workflow_execution_boto3():
domain="test-domain", execution={"runId": run_id, "workflowId": "uid-abcd1234"} domain="test-domain", execution={"runId": run_id, "workflowId": "uid-abcd1234"}
) )
wfe["openCounts"]["openDecisionTasks"].should.equal(2) assert wfe["openCounts"]["openDecisionTasks"] == 2
@mock_swf @mock_swf
@ -91,7 +90,7 @@ def test_signal_workflow_execution_without_runId():
) )
types = [evt["eventType"] for evt in resp["events"]] types = [evt["eventType"] for evt in resp["events"]]
types.should.contain("WorkflowExecutionSignaled") assert "WorkflowExecutionSignaled" in types
@mock_swf @mock_swf
@ -109,11 +108,9 @@ def test_start_already_started_workflow_execution_boto3():
workflowId="uid-abcd1234", workflowId="uid-abcd1234",
workflowType={"name": "test-workflow", "version": "v1.0"}, workflowType={"name": "test-workflow", "version": "v1.0"},
) )
ex.value.response["Error"]["Code"].should.equal( assert ex.value.response["Error"]["Code"] == "WorkflowExecutionAlreadyStartedFault"
"WorkflowExecutionAlreadyStartedFault" assert ex.value.response["Error"]["Message"] == "Already Started"
) assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
ex.value.response["Error"]["Message"].should.equal("Already Started")
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400)
@mock_swf @mock_swf
@ -129,11 +126,11 @@ def test_start_workflow_execution_on_deprecated_type_boto3():
workflowId="uid-abcd1234", workflowId="uid-abcd1234",
workflowType={"name": "test-workflow", "version": "v1.0"}, workflowType={"name": "test-workflow", "version": "v1.0"},
) )
ex.value.response["Error"]["Code"].should.equal("TypeDeprecatedFault") assert ex.value.response["Error"]["Code"] == "TypeDeprecatedFault"
ex.value.response["Error"]["Message"].should.equal( assert ex.value.response["Error"]["Message"] == (
"WorkflowType=[name=test-workflow, version=v1.0]" "WorkflowType=[name=test-workflow, version=v1.0]"
) )
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
# DescribeWorkflowExecution endpoint # DescribeWorkflowExecution endpoint
@ -150,8 +147,8 @@ def test_describe_workflow_execution_boto3():
wfe = client.describe_workflow_execution( wfe = client.describe_workflow_execution(
domain="test-domain", execution={"runId": run_id, "workflowId": "uid-abcd1234"} domain="test-domain", execution={"runId": run_id, "workflowId": "uid-abcd1234"}
) )
wfe["executionInfo"]["execution"]["workflowId"].should.equal("uid-abcd1234") assert wfe["executionInfo"]["execution"]["workflowId"] == "uid-abcd1234"
wfe["executionInfo"]["executionStatus"].should.equal("OPEN") assert wfe["executionInfo"]["executionStatus"] == "OPEN"
@mock_swf @mock_swf
@ -163,11 +160,11 @@ def test_describe_non_existent_workflow_execution_boto3():
domain="test-domain", domain="test-domain",
execution={"runId": "wrong-run-id", "workflowId": "uid-abcd1234"}, execution={"runId": "wrong-run-id", "workflowId": "uid-abcd1234"},
) )
ex.value.response["Error"]["Code"].should.equal("UnknownResourceFault") assert ex.value.response["Error"]["Code"] == "UnknownResourceFault"
ex.value.response["Error"]["Message"].should.equal( assert ex.value.response["Error"]["Message"] == (
"Unknown execution: WorkflowExecution=[workflowId=uid-abcd1234, runId=wrong-run-id]" "Unknown execution: WorkflowExecution=[workflowId=uid-abcd1234, runId=wrong-run-id]"
) )
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
# GetWorkflowExecutionHistory endpoint # GetWorkflowExecutionHistory endpoint
@ -185,7 +182,7 @@ def test_get_workflow_execution_history_boto3():
domain="test-domain", execution={"runId": run_id, "workflowId": "uid-abcd1234"} domain="test-domain", execution={"runId": run_id, "workflowId": "uid-abcd1234"}
) )
types = [evt["eventType"] for evt in resp["events"]] types = [evt["eventType"] for evt in resp["events"]]
types.should.equal(["WorkflowExecutionStarted", "DecisionTaskScheduled"]) assert types == ["WorkflowExecutionStarted", "DecisionTaskScheduled"]
@mock_swf @mock_swf
@ -204,7 +201,7 @@ def test_get_workflow_execution_history_with_reverse_order_boto3():
reverseOrder=True, reverseOrder=True,
) )
types = [evt["eventType"] for evt in resp["events"]] types = [evt["eventType"] for evt in resp["events"]]
types.should.equal(["DecisionTaskScheduled", "WorkflowExecutionStarted"]) assert types == ["DecisionTaskScheduled", "WorkflowExecutionStarted"]
@mock_swf @mock_swf
@ -216,11 +213,11 @@ def test_get_workflow_execution_history_on_non_existent_workflow_execution_boto3
domain="test-domain", domain="test-domain",
execution={"runId": "wrong-run-id", "workflowId": "wrong-workflow-id"}, execution={"runId": "wrong-run-id", "workflowId": "wrong-workflow-id"},
) )
ex.value.response["Error"]["Code"].should.equal("UnknownResourceFault") assert ex.value.response["Error"]["Code"] == "UnknownResourceFault"
ex.value.response["Error"]["Message"].should.equal( assert ex.value.response["Error"]["Message"] == (
"Unknown execution: WorkflowExecution=[workflowId=wrong-workflow-id, runId=wrong-run-id]" "Unknown execution: WorkflowExecution=[workflowId=wrong-workflow-id, runId=wrong-run-id]"
) )
ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
# ListOpenWorkflowExecutions endpoint # ListOpenWorkflowExecutions endpoint
@ -255,16 +252,14 @@ def test_list_open_workflow_executions_boto3():
executionFilter={"workflowId": "test-workflow"}, executionFilter={"workflowId": "test-workflow"},
) )
execution_infos = response["executionInfos"] execution_infos = response["executionInfos"]
len(execution_infos).should.equal(1) assert len(execution_infos) == 1
open_workflow = execution_infos[0] open_workflow = execution_infos[0]
open_workflow["workflowType"].should.equal( assert open_workflow["workflowType"] == {"version": "v1.0", "name": "test-workflow"}
{"version": "v1.0", "name": "test-workflow"} assert "startTimestamp" in open_workflow
) assert open_workflow["execution"]["workflowId"] == "uid-abcd1234"
open_workflow.should.contain("startTimestamp") assert "runId" in open_workflow["execution"]
open_workflow["execution"]["workflowId"].should.equal("uid-abcd1234") assert open_workflow["cancelRequested"] is False
open_workflow["execution"].should.contain("runId") assert open_workflow["executionStatus"] == "OPEN"
open_workflow["cancelRequested"].should.be(False)
open_workflow["executionStatus"].should.equal("OPEN")
# ListClosedWorkflowExecutions endpoint # ListClosedWorkflowExecutions endpoint
@ -299,16 +294,14 @@ def test_list_closed_workflow_executions_boto3():
executionFilter={"workflowId": "test-workflow"}, executionFilter={"workflowId": "test-workflow"},
) )
execution_infos = response["executionInfos"] execution_infos = response["executionInfos"]
len(execution_infos).should.equal(1) assert len(execution_infos) == 1
open_workflow = execution_infos[0] open_workflow = execution_infos[0]
open_workflow["workflowType"].should.equal( assert open_workflow["workflowType"] == {"version": "v1.0", "name": "test-workflow"}
{"version": "v1.0", "name": "test-workflow"} assert "startTimestamp" in open_workflow
) assert open_workflow["execution"]["workflowId"] == "uid-abcd12345"
open_workflow.should.contain("startTimestamp") assert "runId" in open_workflow["execution"]
open_workflow["execution"]["workflowId"].should.equal("uid-abcd12345") assert open_workflow["cancelRequested"] is False
open_workflow["execution"].should.contain("runId") assert open_workflow["executionStatus"] == "CLOSED"
open_workflow["cancelRequested"].should.be(False)
open_workflow["executionStatus"].should.equal("CLOSED")
# TerminateWorkflowExecution endpoint # TerminateWorkflowExecution endpoint
@ -333,11 +326,11 @@ def test_terminate_workflow_execution_boto3():
domain="test-domain", execution={"runId": run_id, "workflowId": "uid-abcd1234"} domain="test-domain", execution={"runId": run_id, "workflowId": "uid-abcd1234"}
) )
evt = resp["events"][-1] evt = resp["events"][-1]
evt["eventType"].should.equal("WorkflowExecutionTerminated") assert evt["eventType"] == "WorkflowExecutionTerminated"
attrs = evt["workflowExecutionTerminatedEventAttributes"] attrs = evt["workflowExecutionTerminatedEventAttributes"]
attrs["details"].should.equal("some details") assert attrs["details"] == "some details"
attrs["reason"].should.equal("a more complete reason") assert attrs["reason"] == "a more complete reason"
attrs["cause"].should.equal("OPERATOR_INITIATED") assert attrs["cause"] == "OPERATOR_INITIATED"
@mock_swf @mock_swf
@ -357,8 +350,8 @@ def test_terminate_workflow_execution_with_wrong_workflow_or_run_id_boto3():
client.terminate_workflow_execution( client.terminate_workflow_execution(
domain="test-domain", workflowId="uid-abcd1234", runId=run_id domain="test-domain", workflowId="uid-abcd1234", runId=run_id
) )
ex.value.response["Error"]["Code"].should.equal("UnknownResourceFault") assert ex.value.response["Error"]["Code"] == "UnknownResourceFault"
ex.value.response["Error"]["Message"].should.equal( assert ex.value.response["Error"]["Message"] == (
f"Unknown execution: WorkflowExecution=[workflowId=uid-abcd1234, runId={run_id}]" f"Unknown execution: WorkflowExecution=[workflowId=uid-abcd1234, runId={run_id}]"
) )
@ -367,8 +360,8 @@ def test_terminate_workflow_execution_with_wrong_workflow_or_run_id_boto3():
client.terminate_workflow_execution( client.terminate_workflow_execution(
domain="test-domain", workflowId="uid-abcd1234" domain="test-domain", workflowId="uid-abcd1234"
) )
ex.value.response["Error"]["Code"].should.equal("UnknownResourceFault") assert ex.value.response["Error"]["Code"] == "UnknownResourceFault"
ex.value.response["Error"]["Message"].should.equal( assert ex.value.response["Error"]["Message"] == (
"Unknown execution, workflowId = uid-abcd1234" "Unknown execution, workflowId = uid-abcd1234"
) )
@ -377,8 +370,8 @@ def test_terminate_workflow_execution_with_wrong_workflow_or_run_id_boto3():
client.terminate_workflow_execution( client.terminate_workflow_execution(
domain="test-domain", workflowId="uid-non-existent" domain="test-domain", workflowId="uid-non-existent"
) )
ex.value.response["Error"]["Code"].should.equal("UnknownResourceFault") assert ex.value.response["Error"]["Code"] == "UnknownResourceFault"
ex.value.response["Error"]["Message"].should.equal( assert ex.value.response["Error"]["Message"] == (
"Unknown execution, workflowId = uid-non-existent" "Unknown execution, workflowId = uid-non-existent"
) )
@ -387,7 +380,7 @@ def test_terminate_workflow_execution_with_wrong_workflow_or_run_id_boto3():
client.terminate_workflow_execution( client.terminate_workflow_execution(
domain="test-domain", workflowId="uid-abcd1234", runId="foo" domain="test-domain", workflowId="uid-abcd1234", runId="foo"
) )
ex.value.response["Error"]["Code"].should.equal("UnknownResourceFault") assert ex.value.response["Error"]["Code"] == "UnknownResourceFault"
ex.value.response["Error"]["Message"].should.equal( assert ex.value.response["Error"]["Message"] == (
"Unknown execution: WorkflowExecution=[workflowId=uid-abcd1234, runId=foo]" "Unknown execution: WorkflowExecution=[workflowId=uid-abcd1234, runId=foo]"
) )

View File

@ -1,4 +1,3 @@
import sure # noqa # pylint: disable=unused-import
import boto3 import boto3
import pytest import pytest
@ -21,8 +20,8 @@ def test_register_workflow_type_boto3():
domain="test-domain", registrationStatus="REGISTERED" domain="test-domain", registrationStatus="REGISTERED"
) )
actype = types["typeInfos"][0] actype = types["typeInfos"][0]
actype["workflowType"]["name"].should.equal("test-workflow") assert actype["workflowType"]["name"] == "test-workflow"
actype["workflowType"]["version"].should.equal("v1.0") assert actype["workflowType"]["version"] == "v1.0"
@mock_swf @mock_swf
@ -39,8 +38,8 @@ def test_register_already_existing_workflow_type_boto3():
client.register_workflow_type( client.register_workflow_type(
domain="test-domain", name="test-workflow", version="v1.0" domain="test-domain", name="test-workflow", version="v1.0"
) )
ex.value.response["Error"]["Code"].should.equal("TypeAlreadyExistsFault") assert ex.value.response["Error"]["Code"] == "TypeAlreadyExistsFault"
ex.value.response["Error"]["Message"].should.equal( assert ex.value.response["Error"]["Message"] == (
"WorkflowType=[name=test-workflow, version=v1.0]" "WorkflowType=[name=test-workflow, version=v1.0]"
) )
@ -69,7 +68,7 @@ def test_list_workflow_types_boto3():
activity_type["workflowType"]["name"] activity_type["workflowType"]["name"]
for activity_type in all_workflow_types["typeInfos"] for activity_type in all_workflow_types["typeInfos"]
] ]
names.should.equal(["a-test-workflow", "b-test-workflow", "c-test-workflow"]) assert names == ["a-test-workflow", "b-test-workflow", "c-test-workflow"]
# ListWorkflowTypes endpoint # ListWorkflowTypes endpoint
@ -96,7 +95,7 @@ def test_list_workflow_types_reverse_order_boto3():
activity_type["workflowType"]["name"] activity_type["workflowType"]["name"]
for activity_type in all_workflow_types["typeInfos"] for activity_type in all_workflow_types["typeInfos"]
] ]
names.should.equal(["c-test-workflow", "b-test-workflow", "a-test-workflow"]) assert names == ["c-test-workflow", "b-test-workflow", "a-test-workflow"]
# DeprecateWorkflowType endpoint # DeprecateWorkflowType endpoint
@ -117,8 +116,8 @@ def test_deprecate_workflow_type_boto3():
domain="test-domain", registrationStatus="DEPRECATED" domain="test-domain", registrationStatus="DEPRECATED"
) )
actype = actypes["typeInfos"][0] actype = actypes["typeInfos"][0]
actype["workflowType"]["name"].should.equal("test-workflow") assert actype["workflowType"]["name"] == "test-workflow"
actype["workflowType"]["version"].should.equal("v1.0") assert actype["workflowType"]["version"] == "v1.0"
@mock_swf @mock_swf
@ -139,8 +138,8 @@ def test_deprecate_already_deprecated_workflow_type_boto3():
domain="test-domain", domain="test-domain",
workflowType={"name": "test-workflow", "version": "v1.0"}, workflowType={"name": "test-workflow", "version": "v1.0"},
) )
ex.value.response["Error"]["Code"].should.equal("TypeDeprecatedFault") assert ex.value.response["Error"]["Code"] == "TypeDeprecatedFault"
ex.value.response["Error"]["Message"].should.equal( assert ex.value.response["Error"]["Message"] == (
"WorkflowType=[name=test-workflow, version=v1.0]" "WorkflowType=[name=test-workflow, version=v1.0]"
) )
@ -157,8 +156,8 @@ def test_deprecate_non_existent_workflow_type_boto3():
domain="test-domain", domain="test-domain",
workflowType={"name": "test-workflow", "version": "v1.0"}, workflowType={"name": "test-workflow", "version": "v1.0"},
) )
ex.value.response["Error"]["Code"].should.equal("UnknownResourceFault") assert ex.value.response["Error"]["Code"] == "UnknownResourceFault"
ex.value.response["Error"]["Message"].should.equal( assert ex.value.response["Error"]["Message"] == (
"Unknown type: WorkflowType=[name=test-workflow, version=v1.0]" "Unknown type: WorkflowType=[name=test-workflow, version=v1.0]"
) )
@ -183,7 +182,7 @@ def test_undeprecate_workflow_type():
resp = client.describe_workflow_type( resp = client.describe_workflow_type(
domain="test-domain", workflowType={"name": "test-workflow", "version": "v1.0"} domain="test-domain", workflowType={"name": "test-workflow", "version": "v1.0"}
) )
resp["typeInfo"]["status"].should.equal("REGISTERED") assert resp["typeInfo"]["status"] == "REGISTERED"
@mock_swf @mock_swf
@ -202,9 +201,11 @@ def test_undeprecate_already_undeprecated_workflow_type():
domain="test-domain", workflowType={"name": "test-workflow", "version": "v1.0"} domain="test-domain", workflowType={"name": "test-workflow", "version": "v1.0"}
) )
client.undeprecate_workflow_type.when.called_with( with pytest.raises(ClientError):
domain="test-domain", workflowType={"name": "test-workflow", "version": "v1.0"} client.undeprecate_workflow_type(
).should.throw(ClientError) domain="test-domain",
workflowType={"name": "test-workflow", "version": "v1.0"},
)
@mock_swf @mock_swf
@ -217,9 +218,11 @@ def test_undeprecate_never_deprecated_workflow_type():
domain="test-domain", name="test-workflow", version="v1.0" domain="test-domain", name="test-workflow", version="v1.0"
) )
client.undeprecate_workflow_type.when.called_with( with pytest.raises(ClientError):
domain="test-domain", workflowType={"name": "test-workflow", "version": "v1.0"} client.undeprecate_workflow_type(
).should.throw(ClientError) domain="test-domain",
workflowType={"name": "test-workflow", "version": "v1.0"},
)
@mock_swf @mock_swf
@ -229,9 +232,11 @@ def test_undeprecate_non_existent_workflow_type():
name="test-domain", workflowExecutionRetentionPeriodInDays="60" name="test-domain", workflowExecutionRetentionPeriodInDays="60"
) )
client.undeprecate_workflow_type.when.called_with( with pytest.raises(ClientError):
domain="test-domain", workflowType={"name": "test-workflow", "version": "v1.0"} client.undeprecate_workflow_type(
).should.throw(ClientError) domain="test-domain",
workflowType={"name": "test-workflow", "version": "v1.0"},
)
# DescribeWorkflowType endpoint # DescribeWorkflowType endpoint
@ -258,16 +263,16 @@ def test_describe_workflow_type_full_boto3():
resp = client.describe_workflow_type( resp = client.describe_workflow_type(
domain="test-domain", workflowType={"name": "test-workflow", "version": "v1.0"} domain="test-domain", workflowType={"name": "test-workflow", "version": "v1.0"}
) )
resp["typeInfo"]["workflowType"]["name"].should.equal("test-workflow") assert resp["typeInfo"]["workflowType"]["name"] == "test-workflow"
resp["typeInfo"]["workflowType"]["version"].should.equal("v1.0") assert resp["typeInfo"]["workflowType"]["version"] == "v1.0"
resp["typeInfo"]["status"].should.equal("REGISTERED") assert resp["typeInfo"]["status"] == "REGISTERED"
resp["typeInfo"]["description"].should.equal("Test workflow.") assert resp["typeInfo"]["description"] == "Test workflow."
resp["configuration"]["defaultTaskStartToCloseTimeout"].should.equal("20") assert resp["configuration"]["defaultTaskStartToCloseTimeout"] == "20"
resp["configuration"]["defaultExecutionStartToCloseTimeout"].should.equal("60") assert resp["configuration"]["defaultExecutionStartToCloseTimeout"] == "60"
resp["configuration"]["defaultTaskList"]["name"].should.equal("foo") assert resp["configuration"]["defaultTaskList"]["name"] == "foo"
resp["configuration"]["defaultTaskPriority"].should.equal("-2") assert resp["configuration"]["defaultTaskPriority"] == "-2"
resp["configuration"]["defaultChildPolicy"].should.equal("ABANDON") assert resp["configuration"]["defaultChildPolicy"] == "ABANDON"
resp["configuration"]["defaultLambdaRole"].should.equal("arn:bar") assert resp["configuration"]["defaultLambdaRole"] == "arn:bar"
@mock_swf @mock_swf
@ -282,7 +287,7 @@ def test_describe_non_existent_workflow_type_boto3():
domain="test-domain", domain="test-domain",
workflowType={"name": "non-existent", "version": "v1.0"}, workflowType={"name": "non-existent", "version": "v1.0"},
) )
ex.value.response["Error"]["Code"].should.equal("UnknownResourceFault") assert ex.value.response["Error"]["Code"] == "UnknownResourceFault"
ex.value.response["Error"]["Message"].should.equal( assert ex.value.response["Error"]["Message"] == (
"Unknown type: WorkflowType=[name=non-existent, version=v1.0]" "Unknown type: WorkflowType=[name=non-existent, version=v1.0]"
) )

View File

@ -1,6 +1,5 @@
import sure # noqa # pylint: disable=unused-import
import json import json
import re
from moto.swf.exceptions import ( from moto.swf.exceptions import (
SWFClientError, SWFClientError,
@ -21,132 +20,116 @@ from moto.swf.models import WorkflowType
def test_swf_client_error(): def test_swf_client_error():
ex = SWFClientError("ASpecificType", "error message") ex = SWFClientError("ASpecificType", "error message")
ex.code.should.equal(400) assert ex.code == 400
json.loads(ex.get_body()).should.equal( assert json.loads(ex.get_body()) == {
{"__type": "ASpecificType", "message": "error message"} "__type": "ASpecificType",
) "message": "error message",
}
def test_swf_unknown_resource_fault(): def test_swf_unknown_resource_fault():
ex = SWFUnknownResourceFault("type", "detail") ex = SWFUnknownResourceFault("type", "detail")
ex.code.should.equal(400) assert ex.code == 400
json.loads(ex.get_body()).should.equal( assert json.loads(ex.get_body()) == {
{ "__type": "com.amazonaws.swf.base.model#UnknownResourceFault",
"__type": "com.amazonaws.swf.base.model#UnknownResourceFault", "message": "Unknown type: detail",
"message": "Unknown type: detail", }
}
)
def test_swf_unknown_resource_fault_with_only_one_parameter(): def test_swf_unknown_resource_fault_with_only_one_parameter():
ex = SWFUnknownResourceFault("foo bar baz") ex = SWFUnknownResourceFault("foo bar baz")
ex.code.should.equal(400) assert ex.code == 400
json.loads(ex.get_body()).should.equal( assert json.loads(ex.get_body()) == {
{ "__type": "com.amazonaws.swf.base.model#UnknownResourceFault",
"__type": "com.amazonaws.swf.base.model#UnknownResourceFault", "message": "Unknown foo bar baz",
"message": "Unknown foo bar baz", }
}
)
def test_swf_domain_already_exists_fault(): def test_swf_domain_already_exists_fault():
ex = SWFDomainAlreadyExistsFault("domain-name") ex = SWFDomainAlreadyExistsFault("domain-name")
ex.code.should.equal(400) assert ex.code == 400
json.loads(ex.get_body()).should.equal( assert json.loads(ex.get_body()) == {
{ "__type": "com.amazonaws.swf.base.model#DomainAlreadyExistsFault",
"__type": "com.amazonaws.swf.base.model#DomainAlreadyExistsFault", "message": "domain-name",
"message": "domain-name", }
}
)
def test_swf_domain_deprecated_fault(): def test_swf_domain_deprecated_fault():
ex = SWFDomainDeprecatedFault("domain-name") ex = SWFDomainDeprecatedFault("domain-name")
ex.code.should.equal(400) assert ex.code == 400
json.loads(ex.get_body()).should.equal( assert json.loads(ex.get_body()) == {
{ "__type": "com.amazonaws.swf.base.model#DomainDeprecatedFault",
"__type": "com.amazonaws.swf.base.model#DomainDeprecatedFault", "message": "domain-name",
"message": "domain-name", }
}
)
def test_swf_serialization_exception(): def test_swf_serialization_exception():
ex = SWFSerializationException("value") ex = SWFSerializationException("value")
ex.code.should.equal(400) assert ex.code == 400
json.loads(ex.get_body()).should.equal( assert json.loads(ex.get_body()) == {
{ "__type": "com.amazonaws.swf.base.model#SerializationException",
"__type": "com.amazonaws.swf.base.model#SerializationException", "message": (
"message": "class java.lang.Foo can not be converted to an String (not a real SWF exception ; happened on: value)", "class java.lang.Foo can not be converted to an String (not "
} "a real SWF exception ; happened on: value)"
) ),
}
def test_swf_type_already_exists_fault(): def test_swf_type_already_exists_fault():
wft = WorkflowType("wf-name", "wf-version") wft = WorkflowType("wf-name", "wf-version")
ex = SWFTypeAlreadyExistsFault(wft) ex = SWFTypeAlreadyExistsFault(wft)
ex.code.should.equal(400) assert ex.code == 400
json.loads(ex.get_body()).should.equal( assert json.loads(ex.get_body()) == {
{ "__type": "com.amazonaws.swf.base.model#TypeAlreadyExistsFault",
"__type": "com.amazonaws.swf.base.model#TypeAlreadyExistsFault", "message": "WorkflowType=[name=wf-name, version=wf-version]",
"message": "WorkflowType=[name=wf-name, version=wf-version]", }
}
)
def test_swf_type_deprecated_fault(): def test_swf_type_deprecated_fault():
wft = WorkflowType("wf-name", "wf-version") wft = WorkflowType("wf-name", "wf-version")
ex = SWFTypeDeprecatedFault(wft) ex = SWFTypeDeprecatedFault(wft)
ex.code.should.equal(400) assert ex.code == 400
json.loads(ex.get_body()).should.equal( assert json.loads(ex.get_body()) == {
{ "__type": "com.amazonaws.swf.base.model#TypeDeprecatedFault",
"__type": "com.amazonaws.swf.base.model#TypeDeprecatedFault", "message": "WorkflowType=[name=wf-name, version=wf-version]",
"message": "WorkflowType=[name=wf-name, version=wf-version]", }
}
)
def test_swf_workflow_execution_already_started_fault(): def test_swf_workflow_execution_already_started_fault():
ex = SWFWorkflowExecutionAlreadyStartedFault() ex = SWFWorkflowExecutionAlreadyStartedFault()
ex.code.should.equal(400) assert ex.code == 400
json.loads(ex.get_body()).should.equal( assert json.loads(ex.get_body()) == {
{ "__type": "com.amazonaws.swf.base.model#WorkflowExecutionAlreadyStartedFault",
"__type": "com.amazonaws.swf.base.model#WorkflowExecutionAlreadyStartedFault", "message": "Already Started",
"message": "Already Started", }
}
)
def test_swf_default_undefined_fault(): def test_swf_default_undefined_fault():
ex = SWFDefaultUndefinedFault("execution_start_to_close_timeout") ex = SWFDefaultUndefinedFault("execution_start_to_close_timeout")
ex.code.should.equal(400) assert ex.code == 400
json.loads(ex.get_body()).should.equal( assert json.loads(ex.get_body()) == {
{ "__type": "com.amazonaws.swf.base.model#DefaultUndefinedFault",
"__type": "com.amazonaws.swf.base.model#DefaultUndefinedFault", "message": "executionStartToCloseTimeout",
"message": "executionStartToCloseTimeout", }
}
)
def test_swf_validation_exception(): def test_swf_validation_exception():
ex = SWFValidationException("Invalid token") ex = SWFValidationException("Invalid token")
ex.code.should.equal(400) assert ex.code == 400
json.loads(ex.get_body()).should.equal( assert json.loads(ex.get_body()) == {
{ "__type": "com.amazon.coral.validate#ValidationException",
"__type": "com.amazon.coral.validate#ValidationException", "message": "Invalid token",
"message": "Invalid token", }
}
)
def test_swf_decision_validation_error(): def test_swf_decision_validation_error():
@ -165,16 +148,18 @@ def test_swf_decision_validation_error():
] ]
) )
ex.code.should.equal(400) assert ex.code == 400
ex.error_type.should.equal("com.amazon.coral.validate#ValidationException") assert ex.error_type == "com.amazon.coral.validate#ValidationException"
msg = ex.get_body() msg = ex.get_body()
msg.should.match(r"2 validation errors detected:") assert re.search(r"2 validation errors detected:", msg)
msg.should.match( assert re.search(
r"Value null at 'decisions.1.member.startTimerDecisionAttributes.startToFireTimeout' " r"Value null at 'decisions.1.member.startTimerDecisionAttributes.startToFireTimeout' "
r"failed to satisfy constraint: Member must not be null;" r"failed to satisfy constraint: Member must not be null;",
msg,
) )
msg.should.match( assert re.search(
r"Value 'FooBar' at 'decisions.1.member.decisionType' failed to satisfy constraint: " r"Value 'FooBar' at 'decisions.1.member.decisionType' failed to satisfy constraint: "
r"Member must satisfy enum value set: \[Foo, Bar, Baz\]" r"Member must satisfy enum value set: \[Foo, Bar, Baz\]",
msg,
) )

View File

@ -1,9 +1,7 @@
import sure # noqa # pylint: disable=unused-import from moto.swf.utils import decapitalize
from moto.swf.utils import decapitalize
def test_decapitalize():
cases = {"fooBar": "fooBar", "FooBar": "fooBar", "FOO BAR": "fOO BAR"}
def test_decapitalize(): for before, after in cases.items():
cases = {"fooBar": "fooBar", "FooBar": "fooBar", "FOO BAR": "fOO BAR"} assert decapitalize(before) == after
for before, after in cases.items():
decapitalize(before).should.equal(after)