diff --git a/moto/iot/models.py b/moto/iot/models.py index b2e6c205e46..a7386c3d1a7 100644 --- a/moto/iot/models.py +++ b/moto/iot/models.py @@ -48,6 +48,7 @@ def __init__( region_name: str, ): self.region_name = region_name + self.account_id = account_id self.thing_id = str(random.uuid4()) self.thing_name = thing_name self.thing_type = thing_type @@ -80,6 +81,7 @@ def to_dict( include_default_client_id: bool = False, include_connectivity: bool = False, include_thing_id: bool = False, + include_thing_group_names: bool = False, ) -> Dict[str, Any]: obj = { "thingName": self.thing_name, @@ -98,6 +100,14 @@ def to_dict( } if include_thing_id: obj["thingId"] = self.thing_id + if include_thing_group_names: + iot_backend = iot_backends[self.account_id][self.region_name] + + obj["thingGroupNames"] = [] + for thing_group in iot_backend.list_thing_groups(None, None, None): + if self.arn in thing_group.things: + obj["thingGroupNames"].append(thing_group.thing_group_name) + return obj @staticmethod @@ -2298,7 +2308,10 @@ def search_index(self, query_string: str) -> List[Dict[str, Any]]: things = [ thing for thing in self.things.values() if thing.matches(query_string) ] - return [t.to_dict(include_connectivity=True) for t in things] + return [ + t.to_dict(include_connectivity=True, include_thing_group_names=True) + for t in things + ] def create_role_alias( self, diff --git a/tests/test_iot/test_iot_search.py b/tests/test_iot/test_iot_search.py index 50c8884d201..6da5be2d13f 100644 --- a/tests/test_iot/test_iot_search.py +++ b/tests/test_iot/test_iot_search.py @@ -33,6 +33,25 @@ def test_search_things(query_string, results): assert thing["connectivity"] == {"connected": True} +@mock_aws +def test_search_things_include_group_names(): + client = boto3.client("iot", region_name="ap-northeast-1") + + thing_name = "test-thing-name" + client.create_thing(thingName=thing_name) + + client.create_thing_group(thingGroupName="TestGroup1") + client.create_thing_group(thingGroupName="AnotherGroup") + client.create_thing_group(thingGroupName="GroupWithoutMembers") + + client.add_thing_to_thing_group(thingName=thing_name, thingGroupName="TestGroup1") + client.add_thing_to_thing_group(thingName=thing_name, thingGroupName="AnotherGroup") + + resp = client.search_index(queryString=f"thingName:{thing_name}") + assert len(resp["things"]) == 1 + assert resp["things"][0]["thingGroupNames"] == ["TestGroup1", "AnotherGroup"] + + @mock_aws @pytest.mark.parametrize( "query_string,results",