Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(stepfunctions): support aws-sdk:scheduler tasks (#2474)
Kacper Harabaszaae65b9589bc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1fa87434..b9365c7c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **Aurora DSQL — `AWS IAM GRANT` and `AWS IAM REVOKE`** — with `DSQL_STRICT=1` both were a syntax error, so a migration that maps a Postgres role to an IAM role stopped there. Sent on their own over the simple query protocol (psql, psycopg2), a GRANT maps one or more ARNs to a role and a REVOKE unmaps them; the mappings read back through `sys.iam_pg_role_mappings` with DSQL's six columns and types, a rollback undoes a GRANT, and a GRANT after other DDL in the same transaction answers DSQL's `0A000`. Re-granting raises DSQL's NOTICE and revoking a missing mapping its WARNING; an unknown role answers `42704`, a value that is not an ARN `0P000`, and granting the signed-in role to itself `42501`. Contributed by @toby6578.### Fixed+- **Step Functions — `aws-sdk:scheduler` tasks** — a Task with `arn:aws:states:::aws-sdk:scheduler:<action>` failed with `States.Runtime` ("Service 'scheduler' is not supported in MiniStack aws-sdk integrations"). `createSchedule`, `getSchedule`, `updateSchedule`, `deleteSchedule`, `listSchedules`, `createScheduleGroup`, `getScheduleGroup`, `deleteScheduleGroup` and `listScheduleGroups` now call EventBridge Scheduler in the execution's account and region, as on AWS. The output keeps Scheduler's member names, timestamps are ISO-8601 UTC strings, `StartDate`/`EndDate` are read from ISO-8601 strings with `Z` or a `+hh:mm` offset (cut to milliseconds), `listSchedules` filters by `GroupName`, `NamePrefix` and `State`, and a JSON object or array given as `Target.Input` is sent as compact JSON text. A failed call reports `Scheduler.<ErrorCode>` with the cause suffix `(Service: Scheduler, Status Code: <status>, Request ID: <id>) (SDK Attempt Count: 1)`. Contributed by @kharabasz.+- **EventBridge Scheduler — schedule error messages** — `GetSchedule`, `UpdateSchedule` and `DeleteSchedule` for a missing schedule now answer `Schedule <name> does not exist.`, and a duplicate `CreateSchedule` answers `Schedule <name> already exists.`, as on AWS; the messages no longer name the group. Contributed by @kharabasz.- **RDS — Aurora cluster Performance Insights inheritance** — explicit cluster PI settings now round-trip through create/modify/describe and propagate to existing and future members. Instance-managed clusters retain their independent settings until an explicit cluster handoff. Enabled responses include the retention and PI KMS key; cluster disablement survives removal of all members.- **Athena — the result file is saved at the reported `OutputLocation`** — a query's `<id>.csv` and `<id>.csv.metadata` are now saved directly under the result location, at the path that `GetQueryExecution` reports, as AWS does. Before, they were saved one folder too deep, at `<location>/<id>.csv/<id>.csv`, so a client that read the reported path got `NoSuchKey`.- **Athena — an enforced workgroup overrides the client-side result location** — when a workgroup has `EnforceWorkGroupConfiguration: true`, `StartQueryExecution` now writes results to the workgroup's `OutputLocation`, even when the request gives its own `ResultConfiguration.OutputLocation`, as AWS does. Before, the request's location was used.diff --git a/ministack/services/scheduler.py b/ministack/services/scheduler.pyindex 0402c7bc..f190924c 100644--- a/ministack/services/scheduler.py+++ b/ministack/services/scheduler.py@@ -157,7 +157,7 @@ def _create_schedule(name, body):if key in _schedules:return _error(409, "ConflictException",- f"Schedule {name} already exists in group {group}.")+ f"Schedule {name} already exists.")# Validate required fieldsif not body.get("ScheduleExpression"):@@ -210,7 +210,7 @@ def _update_schedule(name, body):if key not in _schedules:return _error(404, "ResourceNotFoundException",- f"Schedule {name} does not exist in group {group}.")+ f"Schedule {name} does not exist.")if not body.get("ScheduleExpression"):return _error(400, "ValidationException",@@ -254,7 +254,7 @@ def _get_schedule(name, query):sched = _schedules.get(key)if not sched:return _error(404, "ResourceNotFoundException",- f"Schedule {name} does not exist in group {group}.")+ f"Schedule {name} does not exist.")result = {k: v for k, v in sched.items() if v is not None}return _json_resp(200, result)@@ -296,7 +296,7 @@ def _delete_schedule(name, query):if key not in _schedules:return _error(404, "ResourceNotFoundException",- f"Schedule {name} does not exist in group {group}.")+ f"Schedule {name} does not exist.")arn = _schedules[key]["Arn"]del _schedules[key]diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.pyindex 2f1b0120..32c2565a 100644--- a/ministack/services/stepfunctions.py+++ b/ministack/services/stepfunctions.py@@ -40,7 +40,7 @@ import timefrom concurrent.futures import ThreadPoolExecutorfrom concurrent.futures import TimeoutError as FutureTimeoutErrorfrom concurrent.futures import wait as futures_wait-from datetime import datetime, timezone+from datetime import datetime, timedelta, timezonetry:import jsonata@@ -4114,6 +4114,7 @@ _AWS_SDK_SERVICE_MAP = {"s3": {"protocol": "rest-xml", "service_key": "s3"},"route53": {"protocol": "rest-xml", "service_key": "route53"},"lambda": {"protocol": "rest"},+ "scheduler": {"protocol": "rest"},}# Map lowercase service names used in aws-sdk ARNs to the PascalCase prefix@@ -4144,6 +4145,7 @@ _AWS_SDK_ERROR_PREFIX = {"rdsdata": "RdsData","s3": "S3","lambda": "Lambda",+ "scheduler": "Scheduler",}_AWS_SDK_ERROR_CODE_OVERRIDES = {@@ -5136,6 +5138,147 @@ def _dispatch_aws_sdk_lambda_rest(service_info, service_name, action, input_datareturn output+# EventBridge Scheduler REST routes: action -> (method, path, {member: querystring}).+# The other members go in the JSON body for POST/PUT. Task output keeps the+# Scheduler member names unchanged.+_SCHEDULER_ROUTES = {+ "CreateSchedule": ("POST", "/schedules/{Name}", {}),+ "GetSchedule": ("GET", "/schedules/{Name}", {"GroupName": "groupName"}),+ "UpdateSchedule": ("PUT", "/schedules/{Name}", {}),+ "DeleteSchedule": ("DELETE", "/schedules/{Name}", {"GroupName": "groupName"}),+ "ListSchedules": ("GET", "/schedules", {+ "GroupName": "ScheduleGroup", "NamePrefix": "NamePrefix", "State": "State"}),+ "CreateScheduleGroup": ("POST", "/schedule-groups/{Name}", {}),+ "GetScheduleGroup": ("GET", "/schedule-groups/{Name}", {}),+ "DeleteScheduleGroup": ("DELETE", "/schedule-groups/{Name}", {}),+ "ListScheduleGroups": ("GET", "/schedule-groups", {"NamePrefix": "NamePrefix"}),+}++_SCHEDULER_TIMESTAMPS = ("CreationDate", "LastModificationDate", "StartDate", "EndDate")+++def _scheduler_timestamp_out(value):+ """Epoch seconds as the ISO-8601 UTC string a task outputs (milliseconds only when non-zero)."""+ if not isinstance(value, (int, float)) or isinstance(value, bool):+ return value+ try:+ millis = int(round(value * 1000))+ text = datetime.fromtimestamp(millis // 1000, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%S")+ except (ValueError, OverflowError, OSError):+ # A number from Parameters outside the datetime range is shown as it was stored.+ return value+ if millis % 1000:+ text += f".{millis % 1000:03d}"+ return text + "Z"+++_SCHEDULER_TIMESTAMP_IN = re.compile(+ r"(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.(\d+))?(Z|[+-]\d\d:[0-5]\d)")+++def _scheduler_timestamp_in(value):+ """An ISO-8601 timestamp string from Parameters as epoch seconds, cut to milliseconds."""+ match = _SCHEDULER_TIMESTAMP_IN.fullmatch(value) if isinstance(value, str) else None+ if not match:+ return value+ year, month, day, hour, minute, second, fraction, zone = match.groups()+ offset = timedelta(0)+ if zone != "Z":+ offset = timedelta(hours=int(zone[1:3]), minutes=int(zone[4:6])) * (1 if zone[0] == "+" else -1)+ try:+ # An impossible date, an offset of a day or more, or an instant outside+ # years 1-9999 in UTC is left for Scheduler.+ parsed = datetime(int(year), int(month), int(day), int(hour), int(minute), int(second),+ tzinfo=timezone(offset)).astimezone(timezone.utc)+ except (ValueError, OverflowError):+ return value+ millis = int((fraction or "").ljust(3, "0")[:3])+ return int(parsed.timestamp()) + millis / 1000+++def _dispatch_aws_sdk_scheduler_rest(service_info, service_name, action, input_data):+ """Dispatch the EventBridge Scheduler REST aws-sdk calls."""+ from urllib.parse import quote++ from ministack import app++ service_key = service_info.get("service_key", service_name)+ handler = app.SERVICE_HANDLERS.get(service_key)+ if not handler:+ raise _ExecutionError(+ "States.Runtime",+ f"Service '{service_key}' is not available in MiniStack",+ )++ pascal_action = action[0].upper() + action[1:] if action else action+ route = _SCHEDULER_ROUTES.get(pascal_action)+ if route is None:+ raise _ExecutionError(+ "States.Runtime",+ f"aws-sdk:{service_name}:{action} is not yet implemented in MiniStack "+ "(scheduler dispatcher covers createSchedule, getSchedule, updateSchedule, "+ "deleteSchedule, listSchedules, createScheduleGroup, getScheduleGroup, "+ "deleteScheduleGroup, and listScheduleGroups)",+ )+ method, path, query_members = route++ members = dict(input_data or {})+ if "{Name}" in path:+ path = path.replace("{Name}", quote(str(members.pop("Name", "")), safe=""))+ query_params = {+ wire: str(members.pop(member))+ for member, wire in query_members.items()+ if member in members+ }+ for member in ("StartDate", "EndDate"):+ if member in members:+ members[member] = _scheduler_timestamp_in(members[member])+ target = members.get("Target")+ if isinstance(target, dict) and isinstance(target.get("Input"), (dict, list)):+ # Target.Input is a string member; a JSON object or array is sent as compact JSON text.+ members["Target"] = {**target, "Input": json.dumps(+ target["Input"], separators=(",", ":"), ensure_ascii=False)}+ body = json.dumps(members).encode("utf-8") if method in ("POST", "PUT") else b""++ # Same account and region as the execution; see _dispatch_aws_sdk_lambda_rest.+ caller_account = get_account_id()+ headers = {+ "content-type": "application/json",+ "host": f"{service_key}.{get_region()}.amazonaws.com",+ "authorization": (+ f"AWS4-HMAC-SHA256 Credential={caller_account}/20260101/"+ f"{get_region()}/{service_key}/aws4_request"+ ),+ }++ status, _resp_headers, resp_body = app.call_service_handler_sync(+ handler, method, path, headers, body, query_params)++ decoded = resp_body.decode("utf-8") if isinstance(resp_body, bytes) else resp_body+ if status >= 400:+ try:+ err_data = json.loads(decoded)+ code = err_data.get("__type") or "ServiceException"+ msg = err_data.get("Message") or decoded+ except Exception:+ code, msg = "ServiceException", decoded+ raise _ExecutionError(+ _prefix_sdk_error(service_name, code),+ f"{msg} (Service: Scheduler, Status Code: {status}, Request ID: {new_uuid()}) "+ "(SDK Attempt Count: 1)",+ )++ result = json.loads(decoded) if decoded else {}+ records = [result]+ for list_key in ("Schedules", "ScheduleGroups"):+ records.extend(result.get(list_key) or [])+ for record in records:+ for member in _SCHEDULER_TIMESTAMPS:+ if member in record:+ record[member] = _scheduler_timestamp_out(record[member])+ return result++# ---------------------------------------------------------------------------# REST-XML aws-sdk dispatch (S3)# ---------------------------------------------------------------------------@@ -5551,6 +5694,8 @@ def _invoke_aws_sdk_integration(resource, input_data):return _dispatch_aws_sdk_rest_xml(service_info, service_name, action, input_data)elif protocol == "rest" and service_name == "lambda":return _dispatch_aws_sdk_lambda_rest(service_info, service_name, action, input_data)+ elif protocol == "rest" and service_name == "scheduler":+ return _dispatch_aws_sdk_scheduler_rest(service_info, service_name, action, input_data)else:raise _ExecutionError("States.Runtime",diff --git a/tests/test_scheduler.py b/tests/test_scheduler.pyindex 2be87fe8..60b43cc7 100644--- a/tests/test_scheduler.py+++ b/tests/test_scheduler.py@@ -882,3 +882,39 @@ def test_scheduler_tag_apis_reject_invalid_resource_arns_before_touching_tags(_assert_error(resp, expected_status, expected_code)assert scheduler_mod._tags.get(good_arn, {}) == baselineassert scheduler_mod._tags.get(arn) is None+++def test_scheduler_schedule_error_messages(scheduler):+ """Real AWS (us-east-1, #2467 r2 q12/q13/q15/q16/q17): schedule messages do not name the group."""+ import uuid as _uuid++ group = f"msg-grp-{_uuid.uuid4().hex[:8]}"+ name, missing = f"msg-{_uuid.uuid4().hex[:8]}", f"msg-missing-{_uuid.uuid4().hex[:8]}"+ scheduler.create_schedule_group(Name=group)+ common = {+ "GroupName": group,+ "ScheduleExpression": "at(2030-01-01T00:00:00)",+ "FlexibleTimeWindow": {"Mode": "OFF"},+ "Target": {"Arn": "arn:aws:sqs:us-east-1:000000000000:q", "RoleArn": "arn:aws:iam::000000000000:role/r"},+ }+ try:+ scheduler.create_schedule(Name=name, **common)+ calls = [+ (lambda: scheduler.get_schedule(Name=missing, GroupName=group), "ResourceNotFoundException",+ f"Schedule {missing} does not exist."),+ (lambda: scheduler.create_schedule(Name=name, **common), "ConflictException",+ f"Schedule {name} already exists."),+ (lambda: scheduler.update_schedule(Name=missing, **common), "ResourceNotFoundException",+ f"Schedule {missing} does not exist."),+ (lambda: scheduler.delete_schedule(Name=missing, GroupName=group), "ResourceNotFoundException",+ f"Schedule {missing} does not exist."),+ (lambda: scheduler.get_schedule(Name=name), "ResourceNotFoundException",+ f"Schedule {name} does not exist."),+ ]+ for call, code, message in calls:+ with pytest.raises(ClientError) as exc:+ call()+ assert exc.value.response["Error"]["Code"] == code+ assert exc.value.response["Error"]["Message"] == message+ finally:+ scheduler.delete_schedule_group(Name=group)diff --git a/tests/test_stepfunctions_aws_sdk_scheduler.py b/tests/test_stepfunctions_aws_sdk_scheduler.pynew file mode 100644index 00000000..c1db8df0--- /dev/null+++ b/tests/test_stepfunctions_aws_sdk_scheduler.py@@ -0,0 +1,299 @@+"""Step Functions aws-sdk:scheduler tasks (issue #2467).++Capture keys (rN pNN / qNN) refer to real AWS runs against us-east-1 with+Standard state machines whose single Task state calls+arn:aws:states:::aws-sdk:scheduler:<action>.+"""+import datetime+import json+import re+import uuid++import pytest++ROLE = "arn:aws:iam::000000000000:role/sfn-role"+TARGET_ROLE = "arn:aws:iam::000000000000:role/scheduler-role"+BUS = "arn:aws:events:us-east-1:000000000000:event-bus/default"+AT = "at(2030-01-01T00:00:00)"+ISO_MILLIS = re.compile(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d{3})?Z$")+CAUSE_SUFFIX = re.compile(+ r" \(Service: Scheduler, Status Code: (\d{3}), Request ID: "+ r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\) \(SDK Attempt Count: 1\)$"+)+TARGET = {+ "Arn": BUS,+ "RoleArn": TARGET_ROLE,+ "EventBridgeParameters": {"DetailType": "delayed-event-publish", "Source": "ministack.verify"},+ "Input": '{"run": "x"}',+}+++def run_task(sfn_sync):+ machines = []++ def run(action, parameters=None, arguments=None, sm_input=None):+ state = {"Type": "Task", "Resource": f"arn:aws:states:::aws-sdk:scheduler:{action}", "End": True}+ definition = {"StartAt": "Call", "States": {"Call": state}}+ if arguments is not None:+ definition["QueryLanguage"] = "JSONata"+ state["Arguments"] = arguments+ else:+ state["Parameters"] = parameters+ arn = sfn_sync.create_state_machine(+ name=f"sdk-scheduler-{uuid.uuid4().hex[:8]}",+ definition=json.dumps(definition),+ roleArn=ROLE,+ )["stateMachineArn"]+ machines.append(arn)+ return sfn_sync.start_sync_execution(stateMachineArn=arn, input=json.dumps(sm_input or {}))++ yield run+ for arn in machines:+ sfn_sync.delete_state_machine(stateMachineArn=arn)+++def group(scheduler):+ name = f"sfn-sdk-grp-{uuid.uuid4().hex[:8]}"+ scheduler.create_schedule_group(Name=name)+ yield name+ try:+ scheduler.delete_schedule_group(Name=name)+ except scheduler.exceptions.ResourceNotFoundException:+ pass+++def _output(resp):+ assert resp["status"] == "SUCCEEDED", f"{resp.get('error')}: {resp.get('cause')}"+ return json.loads(resp["output"])+++def _failure(resp):+ assert resp["status"] == "FAILED"+ match = CAUSE_SUFFIX.search(resp["cause"])+ assert match, resp["cause"]+ return resp["error"], resp["cause"][:match.start()], int(match.group(1))+++def _schedule(name, group, **extra):+ return {"Name": name, "GroupName": group, "ScheduleExpression": AT,+ "FlexibleTimeWindow": {"Mode": "OFF"}, "Target": TARGET, **extra}+++def test_schedule_group_tasks(run_task, scheduler):+ """r1 p01 createScheduleGroup, p02 getScheduleGroup, p03 listScheduleGroups, p19 deleteScheduleGroup."""+ name = f"sfn-sdk-grp-{uuid.uuid4().hex[:8]}"+ created = _output(run_task("createScheduleGroup", {+ "Name": name, "Tags": [{"Key": "Owner", "Value": "ministack"}]}))+ assert created == {"ScheduleGroupArn": f"arn:aws:scheduler:us-east-1:000000000000:schedule-group/{name}"}++ got = _output(run_task("getScheduleGroup", {"Name": name}))+ assert set(got) == {"Arn", "CreationDate", "LastModificationDate", "Name", "State"}+ assert got["Arn"] == created["ScheduleGroupArn"]+ assert got["Name"] == name+ assert got["State"] == "ACTIVE"+ assert ISO_MILLIS.match(got["CreationDate"])+ assert ISO_MILLIS.match(got["LastModificationDate"])++ listed = _output(run_task("listScheduleGroups", {"NamePrefix": name}))+ assert listed == {"ScheduleGroups": [got]}++ assert _output(run_task("deleteScheduleGroup", {"Name": name})) == {}+++def test_create_and_get_schedule_tasks(run_task, scheduler, group):+ """r1 p04 createSchedule outputs ScheduleArn; p05 getSchedule outputs the Scheduler+ members unchanged with ISO-8601 UTC timestamps."""+ name = f"s-{uuid.uuid4().hex[:8]}"+ created = _output(run_task("createSchedule", _schedule(name, group, ActionAfterCompletion="DELETE")))+ arn = f"arn:aws:scheduler:us-east-1:000000000000:schedule/{group}/{name}"+ assert created == {"ScheduleArn": arn}++ got = _output(run_task("getSchedule", {"Name": name, "GroupName": group}))+ assert ISO_MILLIS.match(got.pop("CreationDate"))+ assert ISO_MILLIS.match(got.pop("LastModificationDate"))+ for key, value in {+ "ActionAfterCompletion": "DELETE",+ "Arn": arn,+ "FlexibleTimeWindow": {"Mode": "OFF"},+ "GroupName": group,+ "Name": name,+ "ScheduleExpression": AT,+ "ScheduleExpressionTimezone": "UTC",+ "State": "ENABLED",+ }.items():+ assert got[key] == value+ assert {k: got["Target"][k] for k in TARGET} == TARGET++ # r1 p16: the JSONata Arguments form sends the same request.+ assert _output(run_task("getSchedule", arguments={"Name": name, "GroupName": group}))["Arn"] == arn+++def test_list_schedules_task(run_task, scheduler, group):+ """r1 p07 listSchedules by GroupName and p08 by NamePrefix; r3 t01 by State."""+ name = f"s-{uuid.uuid4().hex[:8]}"+ _output(run_task("createSchedule", _schedule(name, group)))+ for parameters in ({"GroupName": group}, {"NamePrefix": name}):+ listed = _output(run_task("listSchedules", parameters))+ assert len(listed["Schedules"]) == 1+ item = listed["Schedules"][0]+ assert set(item) == {"Arn", "CreationDate", "GroupName", "LastModificationDate", "Name",+ "State", "Target"}+ assert item["Name"] == name+ assert item["GroupName"] == group+ assert item["State"] == "ENABLED"+ assert item["Target"] == {"Arn": BUS}+ assert ISO_MILLIS.match(item["CreationDate"])++ disabled = f"s-{uuid.uuid4().hex[:8]}"+ _output(run_task("createSchedule", _schedule(disabled, group, State="DISABLED")))+ listed = _output(run_task("listSchedules", {"GroupName": group, "State": "DISABLED"}))+ assert [item["Name"] for item in listed["Schedules"]] == [disabled]+++def test_update_and_delete_schedule_tasks(run_task, scheduler, group):+ """r1 p14 updateSchedule outputs ScheduleArn and replaces the schedule; p17 deleteSchedule outputs {}."""+ name = f"s-{uuid.uuid4().hex[:8]}"+ _output(run_task("createSchedule", _schedule(name, group, ActionAfterCompletion="DELETE")))+ updated = _output(run_task("updateSchedule", _schedule(+ name, group, State="DISABLED",+ FlexibleTimeWindow={"Mode": "FLEXIBLE", "MaximumWindowInMinutes": 5})))+ assert updated == {"ScheduleArn": f"arn:aws:scheduler:us-east-1:000000000000:schedule/{group}/{name}"}+ got = scheduler.get_schedule(Name=name, GroupName=group)+ assert got["State"] == "DISABLED"+ assert got["FlexibleTimeWindow"] == {"Mode": "FLEXIBLE", "MaximumWindowInMinutes": 5}+ assert got["ActionAfterCompletion"] == "NONE"++ assert _output(run_task("deleteSchedule", {"Name": name, "GroupName": group})) == {}+ with pytest.raises(scheduler.exceptions.ResourceNotFoundException):+ scheduler.get_schedule(Name=name, GroupName=group)+++def test_schedule_timestamps_round_trip(run_task, scheduler, group):+ """r2 q06/q07: StartDate and EndDate are ISO-8601 strings in Parameters and in the+ getSchedule output (milliseconds only when non-zero); q08: an offset is read as that instant."""+ name, other = f"s-{uuid.uuid4().hex[:8]}", f"s-{uuid.uuid4().hex[:8]}"+ _output(run_task("createSchedule", _schedule(+ name, group, ScheduleExpression="rate(1 day)", Description="round2",+ StartDate="2030-01-02T03:04:05Z", EndDate="2030-01-06T03:04:05.000Z")))+ direct = scheduler.get_schedule(Name=name, GroupName=group)+ assert direct["StartDate"] == datetime.datetime(2030, 1, 2, 3, 4, 5, tzinfo=datetime.timezone.utc)+ assert direct["EndDate"] == datetime.datetime(2030, 1, 6, 3, 4, 5, tzinfo=datetime.timezone.utc)++ got = _output(run_task("getSchedule", {"Name": name, "GroupName": group}))+ assert got["StartDate"] == "2030-01-02T03:04:05Z"+ assert got["EndDate"] == "2030-01-06T03:04:05Z"+ assert got["Description"] == "round2"++ _output(run_task("createSchedule", _schedule(+ other, group, ScheduleExpression="rate(1 day)", StartDate="2030-01-02T05:04:05+02:00")))+ direct = scheduler.get_schedule(Name=other, GroupName=group)+ assert direct["StartDate"] == datetime.datetime(2030, 1, 2, 3, 4, 5, tzinfo=datetime.timezone.utc)++[email protected]("start, millis", [+ ("2030-01-02T03:04:05.500Z", 500), # r3 t11+ ("2030-01-02T03:04:05.5Z", 500), # r3 t12 (and t08 from a .$ path)+ ("2030-01-02T03:04:05.123456Z", 123), # r3 t10: cut to milliseconds+ ("2030-01-02T03:04:05.1239Z", 123), # r4 u01: cut, not rounded (literal; same via path, t08)+ ("2030-01-02T03:04:05.9999Z", 999), # r4 u02 (literal; same via path, t08)+])+def test_schedule_start_date_fractions(run_task, scheduler, group, start, millis):+ """r3 t08/t10/t11/t12, r4 u01/u02: fractional seconds of any length are read and cut to milliseconds;+ t14: getSchedule outputs all three digits (.500Z)."""+ name = f"s-{uuid.uuid4().hex[:8]}"+ _output(run_task("createSchedule", {**_schedule(name, group, ScheduleExpression="rate(1 day)"),+ "StartDate.$": "$.start"}, sm_input={"start": start}))+ direct = scheduler.get_schedule(Name=name, GroupName=group)+ assert direct["StartDate"] == datetime.datetime(+ 2030, 1, 2, 3, 4, 5, millis * 1000, tzinfo=datetime.timezone.utc)+ got = _output(run_task("getSchedule", {"Name": name, "GroupName": group}))+ assert got["StartDate"] == f"2030-01-02T03:04:05.{millis:03d}Z"+++def test_target_input_object_is_sent_as_compact_json(run_task, scheduler, group):+ """r2 q11 (and r1 p13): Target.Input from a JSON object path is stored as compact JSON text."""+ name = f"s-{uuid.uuid4().hex[:8]}"+ _output(run_task("createSchedule", {+ "Name": name, "GroupName": group, "ScheduleExpression": AT,+ "FlexibleTimeWindow": {"Mode": "OFF"},+ "Target": {"Arn": BUS, "RoleArn": TARGET_ROLE, "Input.$": "$.payload"},+ }, sm_input={"payload": {"run": "x", "n": 1}}))+ assert scheduler.get_schedule(Name=name, GroupName=group)["Target"]["Input"] == '{"run":"x","n":1}'++[email protected]("value, stored", [+ ([1, "a", {"b": 2}], '[1,"a",{"b":2}]'), # r3 t02+ ({"k": "zażółć €"}, '{"k":"zażółć €"}'), # r3 t04: non-ASCII text is kept+])+def test_target_input_array_and_unicode(run_task, scheduler, group, value, stored):+ """r3 t02/t04: a JSON array or object as Target.Input is stored as compact JSON text."""+ name = f"s-{uuid.uuid4().hex[:8]}"+ _output(run_task("createSchedule", {+ "Name": name, "GroupName": group, "ScheduleExpression": AT,+ "FlexibleTimeWindow": {"Mode": "OFF"},+ "Target": {"Arn": BUS, "RoleArn": TARGET_ROLE, "Input.$": "$.v"},+ }, sm_input={"v": value}))+ assert scheduler.get_schedule(Name=name, GroupName=group)["Target"]["Input"] == stored+++def test_schedule_task_errors(run_task, scheduler, group):+ """Error name, message and cause suffix of failed scheduler tasks:+ r1 p09 duplicate, p10 get missing, p06 get without GroupName, p15 update missing,+ p18 delete missing; r2 q05 create in a missing group."""+ name = f"s-{uuid.uuid4().hex[:8]}"+ missing = f"s-{uuid.uuid4().hex[:8]}"+ nogroup = f"g-{uuid.uuid4().hex[:8]}"+ _output(run_task("createSchedule", _schedule(name, group)))++ cases = [+ (run_task("createSchedule", _schedule(name, group)),+ ("Scheduler.ConflictException", f"Schedule {name} already exists.", 409)),+ (run_task("getSchedule", {"Name": missing, "GroupName": group}),+ ("Scheduler.ResourceNotFoundException", f"Schedule {missing} does not exist.", 404)),+ (run_task("getSchedule", {"Name": name}),+ ("Scheduler.ResourceNotFoundException", f"Schedule {name} does not exist.", 404)),+ (run_task("updateSchedule", _schedule(missing, group)),+ ("Scheduler.ResourceNotFoundException", f"Schedule {missing} does not exist.", 404)),+ (run_task("deleteSchedule", {"Name": missing, "GroupName": group}),+ ("Scheduler.ResourceNotFoundException", f"Schedule {missing} does not exist.", 404)),+ (run_task("createSchedule", _schedule(missing, nogroup)),+ ("Scheduler.ResourceNotFoundException", f"Schedule group {nogroup} does not exist.", 404)),+ ]+ for resp, expected in cases:+ assert _failure(resp) == expected+++def test_schedule_group_task_errors(run_task, group):+ """r2 q02 duplicate group, q03 getScheduleGroup missing, q04 deleteScheduleGroup missing."""+ nogroup = f"g-{uuid.uuid4().hex[:8]}"+ assert _failure(run_task("createScheduleGroup", {"Name": group})) == (+ "Scheduler.ConflictException", f"Schedule group {group} already exists.", 409)+ for action in ("getScheduleGroup", "deleteScheduleGroup"):+ assert _failure(run_task(action, {"Name": nogroup})) == (+ "Scheduler.ResourceNotFoundException", f"Schedule group {nogroup} does not exist.", 404)+++def test_scheduler_task_error_can_be_caught(sfn_sync, group):+ """The r1 p09 error name, Scheduler.ConflictException, matches a Catch on that name.++ The Catch itself is generic Step Functions behaviour (inference; not captured for scheduler).+ """+ name = f"s-{uuid.uuid4().hex[:8]}"+ create = {"Type": "Task", "Resource": "arn:aws:states:::aws-sdk:scheduler:createSchedule",+ "Parameters": _schedule(name, group)}+ definition = {"StartAt": "First", "States": {+ "First": {**create, "ResultPath": None, "Next": "Again"},+ "Again": {**create, "Catch": [{"ErrorEquals": ["Scheduler.ConflictException"],+ "ResultPath": "$.error", "Next": "Caught"}], "End": True},+ "Caught": {"Type": "Pass", "End": True},+ }}+ arn = sfn_sync.create_state_machine(name=f"sdk-scheduler-{uuid.uuid4().hex[:8]}",+ definition=json.dumps(definition), roleArn=ROLE)["stateMachineArn"]+ try:+ resp = sfn_sync.start_sync_execution(stateMachineArn=arn, input="{}")+ assert resp["status"] == "SUCCEEDED", resp.get("cause")+ assert json.loads(resp["output"])["error"]["Error"] == "Scheduler.ConflictException"+ finally:+ sfn_sync.delete_state_machine(stateMachineArn=arn)