Skip to content

Commit

Permalink
Update search_index API - add thingGroupNames in a response
Browse files Browse the repository at this point in the history
  • Loading branch information
jsuchenia committed Nov 5, 2024
1 parent 7ed34fd commit 0189739
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
15 changes: 14 additions & 1 deletion moto/iot/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand Down
19 changes: 19 additions & 0 deletions tests/test_iot/test_iot_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down

0 comments on commit 0189739

Please sign in to comment.