Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(iot): word not-found errors as AWS does (#2193)

iot-rocketc236a9883066
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5c36a566..2a7d3f28 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **IoT — not-found messages match AWS** — a call naming a thing, thing type, thing group, certificate, CA certificate, principal, policy, policy version, job, job execution, job target or provisioning template that does not exist answered `ResourceNotFoundException` with a generic `<Resource> '<name>' not found`, and the device jobs plane (HTTP and MQTT `/rejected`) with `No job execution found for thing … and job …`; each now carries the wording AWS uses for that operation, with the same error code and status. Contributed by @iot-rocket.
- **IoT Jobs — terminal job executions on the device plane** — a device's `DescribeJobExecution` (HTTP and the MQTT `get` topic) of a SUCCEEDED, FAILED, REJECTED, TIMED_OUT, CANCELED or REMOVED execution answered with the execution; it now answers `TerminalStateException` (410) and `TerminalStateReached` over MQTT, as AWS does. `UpdateJobExecution` and `CancelJobExecution` of a terminal execution now refuse with AWS's messages (over MQTT `InvalidStateTransition` with the `executionState`), a refused status such as QUEUED is checked first, and a device that reports SUCCEEDED or FAILED straight from QUEUED now stamps `startedAt`. Contributed by @iot-rocket.
- **IoT / CloudFormation — stack tags and provisioning templates** — stack-level tags never reached IoT resources; they now reach thing types, thing groups, policies, topic rules, CA certificates and provisioning templates without the `aws:cloudformation:` tags (job templates get none, as on AWS), and an update that only changes tags no longer adds a policy version. An `AWS::IoT::ProvisioningTemplate` `Enabled` of `"false"` from a parameter or the template enabled the template; it now disables it. `CreateProvisioningTemplate` and the CloudFormation type accepted any certificate resource; they now refuse one without a `Status` of `Active` or `Inactive` (any case) or whose `CertificateId` is not a reference to `AWS::IoT::Certificate::Id`, a second certificate resource and a resource without `Properties`, with AWS's messages. Contributed by @iot-rocket.
### Added
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index 4539ad19..5d024c0a 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -510,10 +510,42 @@ def _parse_body(body: bytes) -> dict:
return parsed if isinstance(parsed, dict) else {}
-def _error_not_found(resource: str, name: str) -> tuple:
- return error_response_json(
- "ResourceNotFoundException", f"{resource} {name!r} not found", 404
- )
+# AWS's ResourceNotFoundException wording per resource, or per operation where it differs.
+_NOT_FOUND_MESSAGES = {
+ "Thing": "Thing {name} not found.",
+ "DescribeThing": "Thing {account}:{name} not found.",
+ "ListThingGroupsForThing": "thing does not exist",
+ "ListThingPrincipals": "Failed to list principals for thing{name} because the thing does not exist in your account",
+ "AttachThingPrincipal": "Failed to attach the principal {principal} to thing {name} because the thing does not "
+ "exist in your account",
+ "DetachThingPrincipal": "Failed to detach the principal {principal} from thing {name} because the thing does not "
+ "exist in your account",
+ "AttachThingPrincipal:principal": "Can't attach the principal {principal} to thing {name} because the principal "
+ "does not exist in your account",
+ "DetachThingPrincipal:principal": "Can't detach the principal {principal} from thing {name} because the principal "
+ "does not exist in your account",
+ "ListPrincipalThings": "Can't list things for the principal {name} because the principal does not exist in your "
+ "account",
+ "ThingType": "Thing Type {account}:{name} not found.",
+ "ThingGroup": "ThingGroup {account}:{name} not found.",
+ "UpdateThingGroup": "Group {name} does not exist",
+ "CreateThingGroup": "Cannot create group using non-existing group as parent : {name}",
+ "ThingGroupMember": "Cannot find requested thing group for accountId: {account} and thing group name: {name}",
+ "Certificate": "CertificateId {name} does not exist",
+ "CACertificate": "Requested CA Certificate does not exist.",
+ "Policy": "Policy not found",
+ "GetPolicy": "Policy default version not found",
+ "PolicyVersion": "Policy version does not exist (name={policy}, versionId={name})",
+ "Job": "Job {name} cannot be found.",
+ "JobExecution": "Job execution for thing {thing} cannot be found within job {name}.",
+ "JobExecution:job": "Job execution cannot be found as the Job {name} does not exist.",
+}
+
+
+def _error_not_found(resource: str, name: str, **fields) -> tuple:
+ template = _NOT_FOUND_MESSAGES.get(resource, "{resource} {name!r} not found")
+ message = template.format(resource=resource, name=name, account=get_account_id(), **fields)
+ return error_response_json("ResourceNotFoundException", message, 404)
def _qp_bool(qp: dict, name: str, default: bool = False) -> bool:
@@ -1369,7 +1401,7 @@ def _create_thing(name: str, payload: dict) -> tuple:
def _describe_thing(name: str) -> tuple:
thing = _things.get(name)
if thing is None:
- return _error_not_found("Thing", name)
+ return _error_not_found("DescribeThing", name)
body = {
"thingName": thing["thingName"],
"thingId": thing["thingId"],
@@ -1712,7 +1744,7 @@ def _create_thing_group(name: str, payload: dict) -> tuple:
attr_payload = props.get("attributePayload") or {}
parent = payload.get("parentGroupName")
if parent and parent not in _thing_groups:
- return _error_not_found("ThingGroup", parent)
+ return _error_not_found("CreateThingGroup", parent)
record = {
"thingGroupName": name,
"thingGroupId": new_uuid(),
@@ -1765,7 +1797,7 @@ def _list_things_in_thing_group(path: str) -> tuple:
middle = path[len("/thing-groups/"):-len("/things")]
g = _thing_groups.get(middle)
if g is None:
- return _error_not_found("ThingGroup", middle)
+ return _error_not_found("ThingGroupMember", middle)
return json_response({"things": list(g.get("things", []))})
@@ -1787,7 +1819,7 @@ def _list_thing_groups_for_thing(path: str) -> tuple:
)
thing = _things.get(middle)
if thing is None:
- return _error_not_found("Thing", middle)
+ return _error_not_found("ListThingGroupsForThing", middle)
return json_response({
"thingGroups": [
{"groupName": g, "groupArn": _thing_group_arn(g)}
@@ -1802,7 +1834,7 @@ def _list_thing_groups_for_thing(path: str) -> tuple:
def _update_thing_group(name: str, payload: dict) -> tuple:
g = _thing_groups.get(name)
if g is None:
- return _error_not_found("ThingGroup", name)
+ return _error_not_found("UpdateThingGroup", name)
props = payload.get("thingGroupProperties") or {}
if props:
g["thingGroupProperties"].update({
@@ -1855,7 +1887,7 @@ async def _add_thing_to_group(payload: dict) -> tuple:
)
group = _thing_groups.get(gname)
if group is None:
- return _error_not_found("ThingGroup", gname)
+ return _error_not_found("ThingGroupMember", gname)
thing = _things.get(tname)
if thing is None:
return _error_not_found("Thing", tname)
@@ -2220,7 +2252,7 @@ def _update_provisioning_template(name: str, payload: dict) -> tuple:
def _delete_provisioning_template(name: str) -> tuple:
if _provisioning_templates.get(name) is None:
- return _provisioning_template_not_found(name)
+ return error_response_json("ResourceNotFoundException", "Unable to delete template, template not found", 404)
_tags.pop(_provisioning_templates.pop(name)["templateArn"], None)
logger.info("IoT provisioning template deleted: %s", name)
return json_response({})
@@ -3448,8 +3480,9 @@ def _handle_thing_principals(method: str, path: str, headers: dict, body: bytes,
)
name = middle
thing = _things.get(name)
+ operation = {"PUT": "AttachThingPrincipal", "DELETE": "DetachThingPrincipal"}.get(method, "ListThingPrincipals")
if thing is None:
- return _error_not_found("Thing", name)
+ return _error_not_found(operation, name, principal=headers.get("x-amzn-principal") or qp.get("principal"))
if method == "GET":
return json_response({"principals": list(thing.get("principals", []))})
@@ -3463,7 +3496,7 @@ def _handle_thing_principals(method: str, path: str, headers: dict, body: bytes,
cert_id = principal.rsplit("/", 1)[-1]
cert = _certificates.get(cert_id)
if cert is None:
- return _error_not_found("Principal", principal)
+ return _error_not_found(f"{operation}:principal", name, principal=principal)
if method == "PUT":
if principal not in thing.setdefault("principals", []):
@@ -3496,7 +3529,7 @@ def _list_principal_things(headers: dict, qp: dict) -> tuple:
cert_id = principal.rsplit("/", 1)[-1]
cert = _certificates.get(cert_id)
if cert is None:
- return _error_not_found("Principal", principal)
+ return _error_not_found("ListPrincipalThings", principal)
things = []
for arn in cert.get("attachedThings", []):
tname = _thing_name_from_arn(arn)
@@ -3598,7 +3631,7 @@ def _create_policy(name: str, payload: dict) -> tuple:
def _get_policy(name: str) -> tuple:
p = _policies.get(name)
if p is None:
- return _error_not_found("Policy", name)
+ return _error_not_found("GetPolicy", name)
default_id = p["defaultVersionId"]
return json_response({
"policyName": name,
@@ -3685,7 +3718,7 @@ def _get_policy_version(name: str, version_id: str) -> tuple:
return _error_not_found("Policy", name)
v = p["versions"].get(version_id)
if v is None:
- return _error_not_found("PolicyVersion", version_id)
+ return _error_not_found("PolicyVersion", version_id, policy=name)
return json_response({
"policyArn": p["policyArn"],
"policyDocument": v["document"],
@@ -3716,7 +3749,7 @@ def _delete_policy_version(name: str, version_id: str) -> tuple:
if p is None:
return _error_not_found("Policy", name)
if version_id not in p["versions"]:
- return _error_not_found("PolicyVersion", version_id)
+ return _error_not_found("PolicyVersion", version_id, policy=name)
if p["defaultVersionId"] == version_id:
return error_response_json(
"DeleteConflictException",
@@ -5993,6 +6026,12 @@ def _job_arn(job_id: str) -> str:
return f"arn:aws:iot:{get_region()}:{get_account_id()}:job/{job_id}"
+def _job_target_not_found(arn: str) -> str:
+ """AWS's message for a job target thing or thing group that does not exist."""
+ kind, _, name = arn.rpartition(":")[2].partition("/")
+ return f"{'Thing Group' if kind == 'thinggroup' else 'Thing'} {name} cannot be found."
+
+
def _job_target_resolve(arn: str) -> list[str] | None:
"""Thing names one job target ARN resolves to, under the caller's scope.
@@ -6715,7 +6754,7 @@ async def _create_job(job_id: str, payload: dict) -> tuple:
resolved = _job_target_resolve(arn)
if resolved is None:
return error_response_json(
- "ResourceNotFoundException", f"Job target {arn} not found", 404
+ "ResourceNotFoundException", _job_target_not_found(arn), 404
)
target_things.update(resolved)
document = payload.get("document")
@@ -7689,7 +7728,7 @@ def _describe_job_execution(thing: str, job_id: str, qp: dict) -> tuple:
None,
)
if execution is None:
- return _error_not_found("Job execution", f"{thing}/{job_id}")
+ return _error_not_found("JobExecution" if job_id in _jobs else "JobExecution:job", job_id, thing=thing)
view = {
"jobId": execution["jobId"],
"status": execution["status"],
@@ -7713,7 +7752,7 @@ async def _cancel_job_execution(
_jobs_materialize_executions(job_id)
execution = _job_executions.get((thing, job_id))
if execution is None:
- return _error_not_found("Job execution", f"{thing}/{job_id}")
+ return _error_not_found("JobExecution" if job_id in _jobs else "JobExecution:job", job_id, thing=thing)
error = _jobs_check_expected_version(
execution, payload.get("expectedVersion"), "VersionConflictException"
)
@@ -8070,7 +8109,7 @@ def jobs_update_execution(
if execution is None:
return None, error_response_json(
"ResourceNotFoundException",
- f"No job execution found for thing {thing_name} and job {job_id}",
+ f"Job {job_id} not found for {thing_name}",
404,
)
error = _jobs_check_expected_version(
@@ -9443,7 +9482,7 @@ async def _handle_jobs_publish(
"rejected",
_jobs_rejected(
"ResourceNotFound",
- f"No job execution found for thing {thing} and job {job_id}",
+ f"Job {job_id} not found for {thing}",
client_token,
),
)
diff --git a/ministack/services/iot_jobs_data.py b/ministack/services/iot_jobs_data.py
index e3213dec..992ff8f2 100644
--- a/ministack/services/iot_jobs_data.py
+++ b/ministack/services/iot_jobs_data.py
@@ -180,7 +180,7 @@ def _describe_execution(thing: str, job_id: str, qp: dict) -> tuple:
if execution is None:
return error_response_json(
"ResourceNotFoundException",
- f"No job execution found for thing {thing} and job {job_id}",
+ f"Job {job_id} not found for {thing}",
404,
)
execution_number = qp.get("executionNumber")
@@ -196,8 +196,7 @@ def _describe_execution(thing: str, job_id: str, qp: dict) -> tuple:
if execution_number != execution["executionNumber"]:
return error_response_json(
"ResourceNotFoundException",
- f"No job execution {execution_number} found for thing {thing} "
- f"and job {job_id}",
+ f"Job {job_id} not found for {thing}",
404,
)
error = _iot_module.jobs_reject_terminal_describe(execution)
@@ -224,8 +223,7 @@ async def _update_execution(thing: str, job_id: str, payload: dict) -> tuple:
if current is not None and execution_number != current["executionNumber"]:
return error_response_json(
"ResourceNotFoundException",
- f"No job execution {execution_number} found for thing {thing} "
- f"and job {job_id}", 404,
+ f"Job {job_id} not found for {thing}", 404,
)
prev_next = _iot_module.jobs_first_pending_job_id(thing)
execution, error = _iot_module.jobs_update_execution(
diff --git a/tests/test_iot.py b/tests/test_iot.py
index 71a3d5de..5d3cf8a3 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -512,6 +512,99 @@ def test_iot_describe_unknown_thing_404(iot_client):
assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
+_NO_PRINCIPAL = "because the principal does not exist in your account"
+
+
[email protected]("operation, kwargs, message", [
+ ("describe_thing", {"thingName": "{nothing}"}, "Thing {account}:{nothing} not found."),
+ ("update_thing", {"thingName": "{nothing}"}, "Thing {nothing} not found."),
+ ("list_thing_principals", {"thingName": "{nothing}"},
+ "Failed to list principals for thing{nothing} because the thing does not exist in your account"),
+ ("attach_thing_principal", {"thingName": "{nothing}", "principal": "{cert}"},
+ "Failed to attach the principal {cert} to thing {nothing} because the thing does not exist in your account"),
+ ("detach_thing_principal", {"thingName": "{nothing}", "principal": "{cert}"},
+ "Failed to detach the principal {cert} from thing {nothing} because the thing does not exist in your account"),
+ ("attach_thing_principal", {"thingName": "{thing}", "principal": "{nocert}"},
+ "Can't attach the principal {nocert} to thing {thing} " + _NO_PRINCIPAL),
+ ("detach_thing_principal", {"thingName": "{thing}", "principal": "{nocert}"},
+ "Can't detach the principal {nocert} from thing {thing} " + _NO_PRINCIPAL),
+ ("list_principal_things", {"principal": "{nocert}"},
+ "Can't list things for the principal {nocert} " + _NO_PRINCIPAL),
+ ("list_thing_groups_for_thing", {"thingName": "{nothing}"}, "thing does not exist"),
+ ("create_thing", {"thingName": "{nothing}", "thingTypeName": "{notype}"},
+ "Thing Type {account}:{notype} not found."),
+ ("update_thing", {"thingName": "{thing}", "thingTypeName": "{notype}"},
+ "Thing Type {account}:{notype} not found."),
+ ("describe_thing_type", {"thingTypeName": "{notype}"}, "Thing Type {account}:{notype} not found."),
+ ("deprecate_thing_type", {"thingTypeName": "{notype}"}, "Thing Type {account}:{notype} not found."),
+ ("describe_thing_group", {"thingGroupName": "{nogroup}"}, "ThingGroup {account}:{nogroup} not found."),
+ ("update_thing_group", {"thingGroupName": "{nogroup}", "thingGroupProperties": {}},
+ "Group {nogroup} does not exist"),
+ ("create_thing_group", {"thingGroupName": "{nothing}", "parentGroupName": "{nogroup}"},
+ "Cannot create group using non-existing group as parent : {nogroup}"),
+ ("list_things_in_thing_group", {"thingGroupName": "{nogroup}"},
+ "Cannot find requested thing group for accountId: {account} and thing group name: {nogroup}"),
+ ("add_thing_to_thing_group", {"thingGroupName": "{nogroup}", "thingName": "{thing}"},
+ "Cannot find requested thing group for accountId: {account} and thing group name: {nogroup}"),
+ ("add_thing_to_thing_group", {"thingGroupName": "{group}", "thingName": "{nothing}"},
+ "Thing {nothing} not found."),
+ ("remove_thing_from_thing_group", {"thingGroupName": "{group}", "thingName": "{nothing}"},
+ "Thing {nothing} not found."),
+ ("describe_certificate", {"certificateId": "{nocert_id}"}, "CertificateId {nocert_id} does not exist"),
+ ("update_certificate", {"certificateId": "{nocert_id}", "newStatus": "INACTIVE"},
+ "CertificateId {nocert_id} does not exist"),
+ ("delete_certificate", {"certificateId": "{nocert_id}"}, "CertificateId {nocert_id} does not exist"),
+ ("describe_ca_certificate", {"certificateId": "{nocert_id}"},
+ "Requested CA Certificate does not exist."),
+ ("update_ca_certificate", {"certificateId": "{nocert_id}", "newStatus": "INACTIVE"},
+ "Requested CA Certificate does not exist."),
+ ("delete_ca_certificate", {"certificateId": "{nocert_id}"}, "Requested CA Certificate does not exist."),
+ ("get_policy", {"policyName": "{nopolicy}"}, "Policy default version not found"),
+ ("delete_policy", {"policyName": "{nopolicy}"}, "Policy not found"),
+ ("create_policy_version", {"policyName": "{nopolicy}", "policyDocument": "{document}"},
+ "Policy not found"),
+ ("get_policy_version", {"policyName": "{nopolicy}", "policyVersionId": "1"}, "Policy not found"),
+ ("list_policy_versions", {"policyName": "{nopolicy}"}, "Policy not found"),
+ ("delete_policy_version", {"policyName": "{nopolicy}", "policyVersionId": "1"}, "Policy not found"),
+ ("attach_policy", {"policyName": "{nopolicy}", "target": "{cert}"}, "Policy not found"),
+ ("list_targets_for_policy", {"policyName": "{nopolicy}"}, "Policy not found"),
+ ("get_policy_version", {"policyName": "{policy}", "policyVersionId": "9"},
+ "Policy version does not exist (name={policy}, versionId=9)"),
+ ("delete_policy_version", {"policyName": "{policy}", "policyVersionId": "9"},
+ "Policy version does not exist (name={policy}, versionId=9)"),
+ ("delete_provisioning_template", {"templateName": "{nothing}"},
+ "Unable to delete template, template not found"),
+])
+def test_iot_not_found_messages(iot_client, operation, kwargs, message):
+ """A call naming a registry resource that does not exist answers in AWS's words."""
+ thing, group, policy = _unique("thing"), _unique("group"), _unique("policy")
+ document = json.dumps({"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": "iot:Connect", "Resource": "*"}]})
+ arn = iot_client.create_thing(thingName=thing)["thingArn"]
+ iot_client.create_thing_group(thingGroupName=group)
+ iot_client.create_policy(policyName=policy, policyDocument=document)
+ cert = iot_client.create_keys_and_certificate(setAsActive=False)
+ head, account = arn.rsplit(":", 1)[0], arn.split(":")[4]
+ names = {
+ "thing": thing, "group": group, "policy": policy, "cert": cert["certificateArn"],
+ "nothing": _unique("nothing"), "nogroup": _unique("nogroup"), "notype": _unique("notype"),
+ "nopolicy": _unique("nopolicy"), "nocert_id": "ab" * 32, "nocert": f"{head}:cert/{'ab' * 32}",
+ "account": account, "document": document,
+ }
+ try:
+ with pytest.raises(ClientError) as ei:
+ getattr(iot_client, operation)(**{
+ key: value.format(**names) if isinstance(value, str) else value for key, value in kwargs.items()})
+ error = ei.value.response["Error"]
+ status = ei.value.response["ResponseMetadata"]["HTTPStatusCode"]
+ assert (status, error["Code"], error["Message"]) == (404, "ResourceNotFoundException", message.format(**names))
+ finally:
+ iot_client.delete_certificate(certificateId=cert["certificateId"])
+ iot_client.delete_policy(policyName=policy)
+ iot_client.delete_thing_group(thingGroupName=group)
+ iot_client.delete_thing(thingName=thing)
+
+
def test_iot_update_thing_increments_version(iot_client):
name = _unique("thing")
iot_client.create_thing(thingName=name)
diff --git a/tests/test_iot_jobs_data.py b/tests/test_iot_jobs_data.py
index f4c9392a..28c0baca 100644
--- a/tests/test_iot_jobs_data.py
+++ b/tests/test_iot_jobs_data.py
@@ -3436,6 +3436,49 @@ def test_iot_jobs_unknown_job_is_not_found_on_every_path(
_cleanup(iot_client, things=[thing])
[email protected]("operation, kwargs, message", [
+ ("describe_job", {"jobId": "{nojob}"}, "Job {nojob} cannot be found."),
+ ("get_job_document", {"jobId": "{nojob}"}, "Job {nojob} cannot be found."),
+ ("cancel_job", {"jobId": "{nojob}"}, "Job {nojob} cannot be found."),
+ ("delete_job", {"jobId": "{nojob}"}, "Job {nojob} cannot be found."),
+ ("describe_job_execution", {"jobId": "{nojob}", "thingName": "{thing}"},
+ "Job execution cannot be found as the Job {nojob} does not exist."),
+ ("cancel_job_execution", {"jobId": "{nojob}", "thingName": "{thing}"},
+ "Job execution cannot be found as the Job {nojob} does not exist."),
+ ("describe_job_execution", {"jobId": "{job}", "thingName": "{nothing}"},
+ "Job execution for thing {nothing} cannot be found within job {job}."),
+ ("cancel_job_execution", {"jobId": "{job}", "thingName": "{nothing}"},
+ "Job execution for thing {nothing} cannot be found within job {job}."),
+ ("describe_job_execution", {"jobId": "{job}", "thingName": "{thing}", "executionNumber": 9},
+ "Job execution for thing {thing} cannot be found within job {job}."),
+ ("create_job", {"jobId": "{nojob}", "targets": ["{head}:thing/{nothing}"], "document": "{{}}"},
+ "Thing {nothing} cannot be found."),
+ ("create_job", {"jobId": "{nojob}", "targets": ["{head}:thinggroup/{nothing}"], "document": "{{}}"},
+ "Thing Group {nothing} cannot be found."),
+])
+def test_iot_jobs_not_found_messages(iot_client, operation, kwargs, message):
+ """Control-plane job calls on a job, thing or execution that does not exist answer in AWS's words."""
+ thing, job = _unique("jobs-thing"), _unique("job")
+ try:
+ arn = _create_thing(iot_client, thing)
+ iot_client.create_job(jobId=job, targets=[arn], document=_DOCUMENT)
+ names = {"thing": thing, "job": job, "nothing": _unique("nothing"), "nojob": _unique("nojob"),
+ "head": arn.rsplit(":", 1)[0]}
+
+ def fill(value):
+ if isinstance(value, list):
+ return [fill(v) for v in value]
+ return value.format(**names) if isinstance(value, str) else value
+
+ with pytest.raises(ClientError) as ei:
+ getattr(iot_client, operation)(**{key: fill(value) for key, value in kwargs.items()})
+ response = ei.value.response
+ assert (response["ResponseMetadata"]["HTTPStatusCode"], response["Error"]["Code"],
+ response["Error"]["Message"]) == (404, "ResourceNotFoundException", message.format(**names))
+ finally:
+ _cleanup(iot_client, jobs=[job], things=[thing])
+
+
def test_iot_jobs_list_executions_for_thing_filters(iot_client, iot_jobs_data):
"""ListJobExecutionsForThing narrows by `status` (modeled) and by `jobId`
(a MiniStack convenience the `iot` model does not declare, so only raw HTTP
@@ -4160,6 +4203,47 @@ def test_jobs_mqtt_update_unknown_job_rejected(iot_client, iot_data_client):
assert doc["clientToken"] == "tok-x"
[email protected]("transport, verb, thing, job, number", [
+ ("http", "describe", "{thing}", "{nojob}", None),
+ ("http", "describe", "{nothing}", "{job}", None),
+ ("http", "describe", "{thing}", "{job}", 9),
+ ("http", "update", "{thing}", "{nojob}", None),
+ ("http", "update", "{nothing}", "{job}", None),
+ ("http", "update", "{thing}", "{job}", 9),
+ ("mqtt", "get", "{thing}", "{nojob}", None),
+ ("mqtt", "get", "{nothing}", "{job}", None),
+ ("mqtt", "update", "{thing}", "{nojob}", None),
+ ("mqtt", "update", "{nothing}", "{job}", None),
+])
+def test_iot_jobs_data_not_found_messages(iot_client, iot_jobs_data, transport, verb, thing, job, number):
+ """The device plane words an unknown job, thing or execution number as AWS does, on HTTP and MQTT."""
+ names = {"thing": _unique("jobs-thing"), "job": _unique("job"), "nothing": _unique("nothing"),
+ "nojob": _unique("nojob")}
+ thing, job = thing.format(**names), job.format(**names)
+ try:
+ arn = _create_thing(iot_client, names["thing"])
+ iot_client.create_job(jobId=names["job"], targets=[arn], document=_DOCUMENT)
+ extra = {} if number is None else {"executionNumber": number}
+ if transport == "http":
+ if verb == "update":
+ extra["status"] = "IN_PROGRESS"
+ with pytest.raises(ClientError) as ei:
+ getattr(iot_jobs_data, f"{verb}_job_execution")(thingName=thing, jobId=job, **extra)
+ response = ei.value.response
+ got = (response["ResponseMetadata"]["HTTPStatusCode"], response["Error"]["Code"],
+ response["Error"]["Message"])
+ assert got == (404, "ResourceNotFoundException", f"Job {job} not found for {thing}")
+ else:
+ topic = f"$aws/things/{thing}/jobs/{job}/{verb}"
+ payload = {"clientToken": "tok"} if verb == "get" else {"clientToken": "tok", "status": "IN_PROGRESS"}
+ received = _collect_shadow_frames(
+ f"{topic}/rejected", lambda: _mqtt_publish(topic=topic, payload=json.dumps(payload).encode()), want=1)
+ doc = _frames_by_topic(received)[f"{topic}/rejected"]
+ assert (doc["code"], doc["message"]) == ("ResourceNotFound", f"Job {job} not found for {thing}")
+ finally:
+ _cleanup(iot_client, jobs=[names["job"]], things=[names["thing"]])
+
+
def test_jobs_mqtt_next_sentinel_get(iot_client, iot_data_client):
"""``$next`` as the jobId on the get topic resolves the front of the
pending queue WITHOUT starting it — the documented MQTT counterpart of