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
feat(iot): add ListThingGroupsForThing (#1537)
iot-rockete4bcb44ff159
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 44881e4e..e83e6f67 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **Aurora DSQL — foreign key constraints** — every `REFERENCES` / `FOREIGN KEY` clause was refused `0A000`, so a schema with referential integrity could not be created at all; Aurora DSQL has supported foreign keys since 2026-08-26. They now reach the backend as written — the five referential actions, `MATCH FULL` / `MATCH SIMPLE`, self-references, composite keys and deferrability — with the two DSQL-specific rules enforced, measured against a live cluster (eu-central-1, 2026-08-30): `ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY` must use `NOT VALID` (as `CHECK` already did, with `ALTER TABLE ASYNC ... VALIDATE CONSTRAINT` validating it as a job afterwards), and `DEFERRABLE` is refused on any other kind of constraint, in the service's three wordings (`DEFERRABLE constraint not supported`, `CHECK constraints cannot be marked DEFERRABLE`, and `ALTER TABLE / ADD CONSTRAINT UNIQUE / DEFERRED / INITIALLY DEFERRED not supported`), DSQL restricting it to foreign keys; `NOT DEFERRABLE` and `INITIALLY IMMEDIATE` declare no deferral and are accepted anywhere. Referential integrity is the backend's, so a referencing write racing a change to the referenced key waits on a row lock instead of failing the loser with `40001` (OC000). Contributed by @vivedo.- **Aurora DSQL — `SELECT ... FOR KEY SHARE`** — the clause was refused `0A000` alongside `FOR SHARE` and `FOR NO KEY UPDATE`, which matched a live cluster in August but not the service since 2026-08-25; it is now forwarded, and only `FOR SHARE` and `FOR NO KEY UPDATE` are refused. Contributed by @vivedo.- **Aurora DSQL — change data capture streams, and `GetVpcEndpointServiceName`** — `CreateStream` and the three other CDC operations answered `ValidationException` (`Unknown path`), so an application that provisions a stream alongside its cluster could not be pointed at MiniStack at all; CDC went GA on 2026-07-08. Streams now create, describe, list, page, tag and delete with the API's shapes and defaults — `clientToken` idempotency, the 5-per-cluster quota as `ServiceQuotaExceededException` (`You have reached the stream limit.`), and a cluster's streams going with it on delete. Metadata only: no change record reaches the Kinesis target, so a stream is `ACTIVE` on creation unless its target is one MiniStack can see is broken — an absent Kinesis stream, or a role that cannot be assumed under `AUTH=true` — which lands `FAILED` carrying the service's `statusReason` error code. `GetVpcEndpointServiceName`, missing since the emulator landed, answers a stable per-cluster `com.amazonaws.<region>.dsql-<suffix>`. Contributed by @vivedo.+- **IoT Core — `ListThingGroupsForThing`** — `GET /things/{thingName}/thing-groups` answered `400 InvalidRequestException: Unsupported IoT path`, so resolving which groups a thing belongs to meant running `ListThingsInThingGroup` over every group; the forward lookup existed, the reverse one did not. The membership store was already bidirectional, so the operation now reads the thing record's group names and returns `{groupName, groupArn}` pairs, with `ResourceNotFoundException` for an unknown thing. The full list comes back in one page — `maxResults` / `nextToken` are deliberately not honored, like the other IoT list operations here. Contributed by @iot-rocket.### Fixed- **Aurora DSQL — the `ALTER TABLE` refusals answer what the service answers** — measuring the emulator against a live cluster (eu-central-1, 2026-08-30) found four statements answered differently. A refused `ADD CONSTRAINT` — `PRIMARY KEY`, an inline `UNIQUE`, `EXCLUDE`, or a `CHECK`/`FOREIGN KEY` without `NOT VALID` — drew three invented messages where DSQL answers one, `unsupported ALTER TABLE ADD CONSTRAINT statement`. `ADD COLUMN` refused only `DEFAULT` and `NOT NULL` and let `REFERENCES`, `UNIQUE`, `CHECK`, `GENERATED ... STORED` and an inline identity through, where DSQL takes `name type [STORAGE mode]` and nothing else (`ALTER TABLE ADD COLUMN with constraint not supported`, a bare `NULL` apart, and `COLLATE clause not supported` for a collation); `ALTER COLUMN ... ADD GENERATED AS IDENTITY` on an existing column is unaffected. `ALTER TABLE ASYNC ... VALIDATE CONSTRAINT` over rows that break the constraint relayed the backend's `23503` at submit time, where DSQL hands back a `job_id` and fails the job — `sys.jobs` now reports `failed` with the violation as `details` and `sys.wait_for_job` answers false. Adding several columns in one statement also read the second action as part of the first column's type. Contributed by @vivedo.diff --git a/README.md b/README.mdindex 0896c1c8..7d8b7358 100644--- a/README.md+++ b/README.md@@ -587,7 +587,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i| **AppConfig** | CreateApplication, GetApplication, ListApplications, UpdateApplication, DeleteApplication, CreateEnvironment, GetEnvironment, ListEnvironments, UpdateEnvironment, DeleteEnvironment, CreateConfigurationProfile, GetConfigurationProfile, ListConfigurationProfiles, UpdateConfigurationProfile, DeleteConfigurationProfile, CreateHostedConfigurationVersion, GetHostedConfigurationVersion, ListHostedConfigurationVersions, DeleteHostedConfigurationVersion, CreateDeploymentStrategy, GetDeploymentStrategy, ListDeploymentStrategies, UpdateDeploymentStrategy, DeleteDeploymentStrategy, StartDeployment, GetDeployment, ListDeployments, StopDeployment, TagResource, UntagResource, ListTagsForResource, StartConfigurationSession, GetLatestConfiguration | 33 operations; control plane + data plane; hosted configuration versions; deployments complete immediately; session-based configuration retrieval with token rotation || **Transfer Family** | CreateServer, DescribeServer, DeleteServer, ListServers, StartServer, StopServer, CreateUser, DescribeUser, DeleteUser, ListUsers, ImportSshPublicKey, DeleteSshPublicKey | 12 operations; **real SFTP listener** on `:2222` (override with `SFTP_PORT`) backed by S3 — `ls`, `put`, `get`, `mkdir`, `rename` work end-to-end against the local S3 emulator; `SFTP_PORT_PER_SERVER=1` allocates one port per `CreateServer` from `SFTP_BASE_PORT` (default 2300); SSH key auth scans every user across every server and account; `LOGICAL` and `PATH` home-directory mappings; host key persists across restarts when `PERSIST_STATE=1` || **IoT Jobs** | Control plane (`iot`): CreateJob, DescribeJob, ListJobs, GetJobDocument, CancelJob, DeleteJob, ListJobExecutionsForThing, DescribeJobExecution, CancelJobExecution; data plane (`iot-jobs-data`): GetPendingJobExecutions, StartNextPendingJobExecution, DescribeJobExecution (incl. the `$next` sentinel), UpdateJobExecution | 9 control-plane + 4 device data-plane operations sharing one store. Executions walk `QUEUED → IN_PROGRESS → {SUCCEEDED, FAILED, REJECTED, CANCELED}`; the remaining AWS terminal statuses (`TIMED_OUT`, `REMOVED`) are modeled and counted in `jobProcessDetails` but nothing sets them — there are no execution timeouts, and deleting a thing DELETES its executions (freeing a job that was only waiting on that thing) rather than marking them `REMOVED`. `versionNumber` gives optimistic concurrency: every transition bumps it and a stale `expectedVersion` is rejected with a 409 whose message carries the current version — coded `VersionConflictException` on the control plane and `InvalidStateTransitionException` on the device plane, each as its own service model declares. `executionNumber` is write-once (always 1: an execution is never re-queued). Devices may only report `IN_PROGRESS` / `SUCCEEDED` / `FAILED` / `REJECTED` via `UpdateJobExecution`; targets are thing or thing-group ARNs — `SNAPSHOT` jobs resolve group membership once at creation, `CONTINUOUS` jobs also pick up things added to a target group later, and a target must name a thing or thing group in the caller's own account and region (anything else is `ResourceNotFoundException`, since it would resolve to no devices at all); a non-continuous job auto-`COMPLETED`s (with `jobProcessDetails` counts) once every execution is terminal. **`documentSource` is not fetched**: a job created with an S3 `documentSource` serves a `{"documentSource": "<url>"}` placeholder as its document rather than the object's content, so the lifecycle still runs — pass `document` when the content matters. **Timestamp units differ by plane, as on AWS**: control-plane responses use `timestamp` shapes (epoch seconds — boto3 parses them to datetimes) while `iot-jobs-data` responses carry raw epoch-**millisecond** `long`s. Job state persists with the IoT store when `PERSIST_STATE=1` |-| **IoT Core** | CreateThing, DescribeThing, ListThings, UpdateThing, DeleteThing, CreateThingType, CreateThingGroup, AddThingToThingGroup, ListThingsInThingGroup, CreateKeysAndCertificate, RegisterCertificate, RegisterCertificateWithoutCA, UpdateCertificate, DeleteCertificate, GetRegistrationCode, DeleteRegistrationCode, RegisterCACertificate, DescribeCACertificate, UpdateCACertificate, ListCACertificates, DeleteCACertificate, CreateProvisioningTemplate, DescribeProvisioningTemplate, ListProvisioningTemplates, UpdateProvisioningTemplate, DeleteProvisioningTemplate, AttachThingPrincipal, DetachThingPrincipal, ListThingPrincipals, ListPrincipalThings, CreatePolicy, CreatePolicyVersion, AttachPolicy, DetachPolicy, ListAttachedPolicies, ListTargetsForPolicy, AttachPrincipalPolicy, DetachPrincipalPolicy, ListPrincipalPolicies, ListPolicyPrincipals, CreateTopicRule, GetTopicRule, ReplaceTopicRule, DeleteTopicRule, ListTopicRules, UpdateIndexingConfiguration, GetIndexingConfiguration, DescribeIndex, ListIndices, SearchIndex, DescribeEndpoint, Publish (HTTP), MQTT-over-WebSocket pub/sub | 51 operations + **MQTT 3.1.1 and 5.0 over WebSocket** (negotiated per connection) on the gateway port — clients use the address returned by `DescribeEndpoint`; local CA signs `CreateKeysAndCertificate` certificates (CA persists across restarts when `PERSIST_STATE=1`); multi-tenancy via transparent topic prefixing (same pattern as Transfer Family's shared SFTP listener); no plain TCP 1883 (real AWS IoT requires TLS or SigV4 on every connection), but a **native mTLS MQTT listener on 8883** serves device SDK binaries by default — the client certificate is optional (no certificate means the default account, like an unsigned WebSocket upgrade) and, when presented, must be registered `ACTIVE` in exactly one account, which then serves the session; unknown, inactive or doubly-registered certificates get a "not authorized" CONNACK (see `IOT_MTLS_PORT` in the environment table); local CA cert available at `GET /_ministack/iot/ca.pem` for SDK trust configuration; IoT policies are stored but **not enforced** on the data plane; **fleet indexing** works the way it does on AWS — `UpdateIndexingConfiguration` turns the `AWS_Things` index on (Terraform `aws_iot_indexing_configuration`), and searching while `thingIndexingMode` is `OFF` answers `ResourceNotFoundException`; `SearchIndex` then queries the live registry + classic shadows with `AND`-separated `thingName` / `thingTypeName` / `thingGroupNames` / `attributes.*` / `shadow.reported.*` / `shadow.desired.*` terms (`*` / `?` wildcards, `maxResults` / `nextToken` paging) — there is no projection to build, so hits are always current; the deprecated principal-policy family (`AttachPrincipalPolicy` / `DetachPrincipalPolicy` / `ListPrincipalPolicies` / `ListPolicyPrincipals`) maps 1:1 onto the modern policy-target store; **topic rules fire on matching publishes** (incl. Basic Ingest `$aws/rules/<name>`) with SQL SELECT projection (`topic()`, `timestamp()`, `encode()`, `newuuid()`, `replace()`, `clientid()`, `isUndefined()`), **WHERE-clause evaluation** (comparisons, `IN`, `LIKE`, `BETWEEN`, `IS NULL`, `regexp_matches`, bare boolean attributes, composed with `AND` / `OR` and parenthesised grouping; missing attributes fail closed as on AWS; unparseable SQL → `SqlParseException`), and `lambda` / `republish` / `dynamoDBv2` / `sns` / `sqs` actions dispatched in-process with the rule's `errorAction` on failure; **device shadows over MQTT** — the `$aws/things/<thing>/shadow[/name/<name>]/{get,update,delete}` reserved topics drive the shadow store and reply on `accepted` / `rejected` (with `delta` and `documents` on update); a **CA-certificate registry** (`RegisterCACertificate` and friends) with the just-in-time-registration `registered` event on `$aws/events/certificates/registered/{caCertificateId}`; a **provisioning-template registry** (`CreateProvisioningTemplate` and friends) — storage + CRUD only, so `provisioningRoleArn` is presence-checked but not resolved and the fleet-provisioning MQTT workflow (`$aws/provisioning-templates/...`) is not implemented; and `SearchIndex` answers `connectivity.connected` / `connectivity.timestamp` / `connectivity.disconnectReason` when `thingConnectivityIndexingMode` is `STATUS`, deriving `connected` from the live session registry |+| **IoT Core** | CreateThing, DescribeThing, ListThings, UpdateThing, DeleteThing, CreateThingType, CreateThingGroup, AddThingToThingGroup, ListThingsInThingGroup, ListThingGroupsForThing, CreateKeysAndCertificate, RegisterCertificate, RegisterCertificateWithoutCA, UpdateCertificate, DeleteCertificate, GetRegistrationCode, DeleteRegistrationCode, RegisterCACertificate, DescribeCACertificate, UpdateCACertificate, ListCACertificates, DeleteCACertificate, CreateProvisioningTemplate, DescribeProvisioningTemplate, ListProvisioningTemplates, UpdateProvisioningTemplate, DeleteProvisioningTemplate, AttachThingPrincipal, DetachThingPrincipal, ListThingPrincipals, ListPrincipalThings, CreatePolicy, CreatePolicyVersion, AttachPolicy, DetachPolicy, ListAttachedPolicies, ListTargetsForPolicy, AttachPrincipalPolicy, DetachPrincipalPolicy, ListPrincipalPolicies, ListPolicyPrincipals, CreateTopicRule, GetTopicRule, ReplaceTopicRule, DeleteTopicRule, ListTopicRules, UpdateIndexingConfiguration, GetIndexingConfiguration, DescribeIndex, ListIndices, SearchIndex, DescribeEndpoint, Publish (HTTP), MQTT-over-WebSocket pub/sub | 52 operations + **MQTT 3.1.1 and 5.0 over WebSocket** (negotiated per connection) on the gateway port — clients use the address returned by `DescribeEndpoint`; local CA signs `CreateKeysAndCertificate` certificates (CA persists across restarts when `PERSIST_STATE=1`); multi-tenancy via transparent topic prefixing (same pattern as Transfer Family's shared SFTP listener); no plain TCP 1883 (real AWS IoT requires TLS or SigV4 on every connection), but a **native mTLS MQTT listener on 8883** serves device SDK binaries by default — the client certificate is optional (no certificate means the default account, like an unsigned WebSocket upgrade) and, when presented, must be registered `ACTIVE` in exactly one account, which then serves the session; unknown, inactive or doubly-registered certificates get a "not authorized" CONNACK (see `IOT_MTLS_PORT` in the environment table); local CA cert available at `GET /_ministack/iot/ca.pem` for SDK trust configuration; IoT policies are stored but **not enforced** on the data plane; **fleet indexing** works the way it does on AWS — `UpdateIndexingConfiguration` turns the `AWS_Things` index on (Terraform `aws_iot_indexing_configuration`), and searching while `thingIndexingMode` is `OFF` answers `ResourceNotFoundException`; `SearchIndex` then queries the live registry + classic shadows with `AND`-separated `thingName` / `thingTypeName` / `thingGroupNames` / `attributes.*` / `shadow.reported.*` / `shadow.desired.*` terms (`*` / `?` wildcards, `maxResults` / `nextToken` paging) — there is no projection to build, so hits are always current; the deprecated principal-policy family (`AttachPrincipalPolicy` / `DetachPrincipalPolicy` / `ListPrincipalPolicies` / `ListPolicyPrincipals`) maps 1:1 onto the modern policy-target store; **topic rules fire on matching publishes** (incl. Basic Ingest `$aws/rules/<name>`) with SQL SELECT projection (`topic()`, `timestamp()`, `encode()`, `newuuid()`, `replace()`, `clientid()`, `isUndefined()`), **WHERE-clause evaluation** (comparisons, `IN`, `LIKE`, `BETWEEN`, `IS NULL`, `regexp_matches`, bare boolean attributes, composed with `AND` / `OR` and parenthesised grouping; missing attributes fail closed as on AWS; unparseable SQL → `SqlParseException`), and `lambda` / `republish` / `dynamoDBv2` / `sns` / `sqs` actions dispatched in-process with the rule's `errorAction` on failure; **device shadows over MQTT** — the `$aws/things/<thing>/shadow[/name/<name>]/{get,update,delete}` reserved topics drive the shadow store and reply on `accepted` / `rejected` (with `delta` and `documents` on update); a **CA-certificate registry** (`RegisterCACertificate` and friends) with the just-in-time-registration `registered` event on `$aws/events/certificates/registered/{caCertificateId}`; a **provisioning-template registry** (`CreateProvisioningTemplate` and friends) — storage + CRUD only, so `provisioningRoleArn` is presence-checked but not resolved and the fleet-provisioning MQTT workflow (`$aws/provisioning-templates/...`) is not implemented; and `SearchIndex` answers `connectivity.connected` / `connectivity.timestamp` / `connectivity.disconnectReason` when `thingConnectivityIndexingMode` is `STATUS`, deriving `connected` from the live session registry || **EventBridge Scheduler** | CreateSchedule, GetSchedule, UpdateSchedule, DeleteSchedule, ListSchedules, CreateScheduleGroup, GetScheduleGroup, DeleteScheduleGroup, ListScheduleGroups, TagResource, UntagResource, ListTagsForResource | 12 actions; schedules **fire their targets** — a background sweep invokes each enabled schedule's target (Lambda, SQS, SNS, Step Functions) when due, honoring `State`, `StartDate`/`EndDate`, and `ActionAfterCompletion: DELETE`; schedule groups with cascading deletes; `rate()`, `cron()`, `at()` expressions; group/prefix/state filters on list; default group auto-created; CFN `AWS::Scheduler::Schedule` and `AWS::Scheduler::ScheduleGroup` supported || **EKS** | CreateCluster, DescribeCluster, ListClusters, DeleteCluster, CreateNodegroup, DescribeNodegroup, ListNodegroups, DeleteNodegroup, CreateAddon, DescribeAddon, ListAddons, UpdateAddon, DeleteAddon, AssociateEncryptionConfig, CreateAccessEntry, DescribeAccessEntry, ListAccessEntries, UpdateAccessEntry, DeleteAccessEntry, AssociateAccessPolicy, DisassociateAccessPolicy, ListAssociatedAccessPolicies, AssociateIdentityProviderConfig, DescribeIdentityProviderConfig, DisassociateIdentityProviderConfig, ListIdentityProviderConfigs, TagResource, UntagResource, ListTagsForResource | `CreateCluster` spawns a real **k3s** container (75 MB) with a full Kubernetes API server; `kubectl`, Helm, and any K8s tooling work out of the box; cascading delete removes nodegroups and k3s container; addon CRUD (e.g. `vpc-cni`, `coredns`, `kube-proxy`, `aws-ebs-csi-driver`) at `/clusters/{name}/addons` flips status to `ACTIVE` on create / update; `AssociateEncryptionConfig` at `/clusters/{name}/encryption-config/associate` records KMS encryption config (rejects re-association, AWS-shape `update` envelope); **Access Entries** (modern post-1.29 IAM bindings — replaces aws-auth ConfigMap) at `/clusters/{name}/access-entries[/{principalArn}[/access-policies[/{policyArn}]]]` for Crossplane / Terraform `aws_eks_access_entry` + `aws_eks_access_policy_association`; OIDC discovery + JWKS served at the cluster's `identity.oidc.issuer` URL so Terraform's `aws_iam_openid_connect_provider` (IRSA) works against ministack; **OIDC Identity Provider Config** (`AssociateIdentityProviderConfig` / `DescribeIdentityProviderConfig` / `DisassociateIdentityProviderConfig` / `ListIdentityProviderConfigs`) at `/clusters/{name}/identity-provider-configs[/{verb}]` — one OIDC IdP per cluster, issuer + clientId + claims forwarded to the k3s API server via `--kube-apiserver-arg=oidc-*` flags, tags reachable via `ListTagsForResource`; CFN `AWS::EKS::Cluster` and `AWS::EKS::Nodegroup` supported || **OpenSearch Service** | CreateDomain, DescribeDomain, DescribeDomains, DeleteDomain, ListDomainNames, UpdateDomainConfig, DescribeDomainConfig, DescribeDomainChangeProgress, ListVersions, GetCompatibleVersions, AddTags, ListTags, RemoveTags | Management plane on `/2021-01-01/*` (`boto3.client("opensearch")`, SigV4 scope `es`). Default data plane is a stub endpoint (`<domain>.ministack.local:9200`) — set `OPENSEARCH_DATAPLANE=1` to spawn one real `opensearchproject/opensearch` container per `CreateDomain` (same pattern as ElastiCache/RDS); `DescribeDomain.Endpoint` then points at that container and `_cluster/health`/`/_search` work end-to-end. Add `OPENSEARCH_DASHBOARDS=1` (with dataplane on) to also spawn a per-domain `opensearch-dashboards` sidecar; `DescribeDomain.DashboardEndpoint` is populated. ARNs follow `arn:aws:es:<region>:<account>:domain/<name>`; Terraform `aws_opensearch_domain` resource compatible. |diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex dd0bcb53..b1a07be9 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -481,6 +481,10 @@ async def handle_request(# Principal lives at /things/{name}/principals — must come BEFORE generic /things/{name}if path.startswith("/things/") and path.endswith("/principals"):return _handle_thing_principals(method, path, hdr, body, qp)+ # Group membership lives at /things/{name}/thing-groups — like /principals,+ # must come BEFORE the generic /things/{name} branch.+ if path.startswith("/things/") and path.endswith("/thing-groups") and method == "GET":+ return _list_thing_groups_for_thing(path)# Job executions live at /things/{name}/jobs[/{jobId}[/cancel]] — like# /principals, must come BEFORE the generic /things/{name} branch. The# `jobs` segment only counts when a thing name precedes it: `/things/jobs`@@ -1026,6 +1030,36 @@ def _list_things_in_thing_group(path: str) -> tuple:return json_response({"things": list(g.get("things", []))})+def _list_thing_groups_for_thing(path: str) -> tuple:+ """``GET /things/{thingName}/thing-groups``.++ The reverse of ``ListThingsInThingGroup``: the forward lookup existed, but+ resolving which groups a *thing* belongs to meant scanning every group. The+ membership store is bidirectional, so this reads the thing record's+ ``thingGroupNames`` directly.++ ``maxResults`` / ``nextToken`` are not honored — the full list is returned+ in one page, like the other IoT list operations here.+ """+ middle = path[len("/things/"):-len("/thing-groups")]+ if "/" in middle:+ return error_response_json(+ "InvalidRequestException", f"Unsupported IoT path: GET {path}", 400+ )+ thing = _things.get(middle)+ if thing is None:+ return _error_not_found("Thing", middle)+ return json_response({+ "thingGroups": [+ {"groupName": g, "groupArn": _thing_group_arn(g)}+ for g in thing.get("thingGroupNames", [])+ # Membership is kept consistent on both sides, but a group deleted+ # out from under a stale reference must not surface here.+ if g in _thing_groups+ ]+ })++def _update_thing_group(name: str, payload: dict) -> tuple:g = _thing_groups.get(name)if g is None:diff --git a/tests/test_iot.py b/tests/test_iot.pyindex ae147008..76621f96 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -292,6 +292,37 @@ def test_iot_thing_group_membership(iot_client):iot_client.delete_thing_group(thingGroupName=gname)+def test_iot_list_thing_groups_for_thing(iot_client):+ tname = _unique("thing")+ g1 = _unique("group")+ g2 = _unique("group")+ iot_client.create_thing(thingName=tname)+ iot_client.create_thing_group(thingGroupName=g1)+ iot_client.create_thing_group(thingGroupName=g2)++ # A thing in no groups answers an empty list, not an error.+ assert iot_client.list_thing_groups_for_thing(thingName=tname)["thingGroups"] == []++ iot_client.add_thing_to_thing_group(thingGroupName=g1, thingName=tname)+ iot_client.add_thing_to_thing_group(thingGroupName=g2, thingName=tname)+ groups = iot_client.list_thing_groups_for_thing(thingName=tname)["thingGroups"]+ assert {g["groupName"] for g in groups} == {g1, g2}+ for g in groups:+ assert g["groupArn"].endswith(":thinggroup/" + g["groupName"])++ iot_client.remove_thing_from_thing_group(thingGroupName=g1, thingName=tname)+ remaining = iot_client.list_thing_groups_for_thing(thingName=tname)["thingGroups"]+ assert [g["groupName"] for g in remaining] == [g2]++ with pytest.raises(ClientError) as ei:+ iot_client.list_thing_groups_for_thing(thingName=_unique("absent"))+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"++ iot_client.delete_thing(thingName=tname)+ iot_client.delete_thing_group(thingGroupName=g1)+ iot_client.delete_thing_group(thingGroupName=g2)++# ---------------------------------------------------------------------------# Certificates (issued via the Local CA)# ---------------------------------------------------------------------------