Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
microsoft_teams_importer: Process paginated API responses.
PieterCKed2cdc808314
diff --git a/zerver/data_import/microsoft_teams.py b/zerver/data_import/microsoft_teams.pyindex 0a638c4bf8e..a6a2a4e0b35 100644--- a/zerver/data_import/microsoft_teams.py+++ b/zerver/data_import/microsoft_teams.py@@ -41,7 +41,7 @@ class ODataQueryParameter:# amount, type, and order of the data returned for the resource# identified by the URL.# https://learn.microsoft.com/en-us/graph/query-parameters?tabs=http- parameter: Literal["$filter", "$search", "$select"]+ parameter: Literal["$filter", "$search", "$select", "$top"]expression: str@@ -56,21 +56,36 @@ def get_microsoft_graph_api_data(if not kwargs.get("token"):raise AssertionError("Microsoft authorization token missing in kwargs")token = kwargs.pop("token")-+ accumulated_result = []parameters = {}if odata_parameters is not None:for parameter in odata_parameters:assert parameter.parameter not in parametersparameters[parameter.parameter] = parameter.expression- response = requests.get(- api_url, headers={"Authorization": f"Bearer {token}"}, params=parameters- )+ # If a request is paginated, "@odata.nextLink" will be included in the response,+ # it points to the next page of result. Even if the `$top` query is not specified,+ # depending on the endpoint and the result size, it may be paged by the server.+ # https://learn.microsoft.com/en-us/graph/paging?tabs=http#server-side-paging+ next_link: str | None = api_url+ while next_link is not None:+ response = requests.get(+ next_link, headers={"Authorization": f"Bearer {token}"}, params=parameters+ )++ if response.status_code != requests.codes.ok:+ logging.info("HTTP error: %s, Response: %s", response.status_code, response.text)+ raise Exception("HTTP error accessing the Microsoft Graph API.")++ response_data = response.json()+ accumulated_result.extend(response_data["value"])+ next_link = response_data.get("@odata.nextLink")++ # Don't apply initial request's parameters to subsequent paginated requests.+ if next_link is not None:+ parameters = {}- if response.status_code != requests.codes.ok:- logging.info("HTTP error: %s, Response: %s", response.status_code, response.text)- raise Exception("HTTP error accessing the Microsoft Graph API.")- return response.json()["value"]+ return accumulated_resultdef get_directory_roles(api_token: str) -> list[MicrosoftTeamsFieldsT]:diff --git a/zerver/tests/fixtures/microsoft_graph_api_response_fixtures/paginated_users_member.json b/zerver/tests/fixtures/microsoft_graph_api_response_fixtures/paginated_users_member.jsonnew file mode 100644index 00000000000..65b5a35b4ff--- /dev/null+++ b/zerver/tests/fixtures/microsoft_graph_api_response_fixtures/paginated_users_member.json@@ -0,0 +1,47 @@+{+ "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users",+ "@odata.nextLink": "https://graph.microsoft.com/v1.0/users?$filter=userType+eq+%27Member%27&$top=3&$skiptoken=RFNwdAoAAQAAAAAAAAAAFAAAAAIjPrZtIj1IsyACv_n3ZLsBAAAAAAAAAAAAAAAAAAAXMS4yLjg0MC4xMTM1NTYuMS40LjIzMzEGAAAAAAABttbVt5Wq-0aI2xDyNlaWGwG9AAAAAQAAAAA",+ "value": [+ {+ "businessPhones": [+ "16508158245"+ ],+ "displayName": "Alya Abbott",+ "givenName": "Alya",+ "jobTitle": null,+ "mail": "[email protected]",+ "mobilePhone": null,+ "officeLocation": null,+ "preferredLanguage": "en",+ "surname": "Abbott",+ "userPrincipalName": "[email protected]",+ "id": "3c6ee395-529d-4681-b5f7-582c707570f6"+ },+ {+ "businessPhones": [],+ "displayName": "Pieter K",+ "givenName": "Pieter",+ "jobTitle": null,+ "mail": "[email protected]",+ "mobilePhone": null,+ "officeLocation": null,+ "preferredLanguage": null,+ "surname": "K",+ "userPrincipalName": "[email protected]",+ "id": "88cbf3c2-0810-4d32-aa19-863c12bf7be9"+ },+ {+ "businessPhones": [],+ "displayName": "Cordelia",+ "givenName": "Cordelia",+ "jobTitle": null,+ "mail": "[email protected]",+ "mobilePhone": null,+ "officeLocation": null,+ "preferredLanguage": null,+ "surname": null,+ "userPrincipalName": "[email protected]",+ "id": "bcbf26d8-e24a-4298-b6fd-d2320ff09fa5"+ }+ ]+}diff --git a/zerver/tests/fixtures/microsoft_graph_api_response_fixtures/paginated_users_member_2.json b/zerver/tests/fixtures/microsoft_graph_api_response_fixtures/paginated_users_member_2.jsonnew file mode 100644index 00000000000..33f3995ccda--- /dev/null+++ b/zerver/tests/fixtures/microsoft_graph_api_response_fixtures/paginated_users_member_2.json@@ -0,0 +1,31 @@+{+ "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users",+ "value": [+ {+ "businessPhones": [],+ "displayName": "zoe",+ "givenName": "zoe",+ "jobTitle": null,+ "mail": "[email protected]",+ "mobilePhone": null,+ "officeLocation": null,+ "preferredLanguage": null,+ "surname": null,+ "userPrincipalName": "[email protected]",+ "id": "5dbe468a-1e96-4aaa-856d-cdf825081e11"+ },+ {+ "businessPhones": [],+ "displayName": "AARON",+ "givenName": "AARON",+ "jobTitle": "Business development specialist",+ "mail": "[email protected]",+ "mobilePhone": null,+ "officeLocation": null,+ "preferredLanguage": null,+ "surname": null,+ "userPrincipalName": "[email protected]",+ "id": "4dbd4c6f-163d-40b7-901b-e86b2f2141ae"+ }+ ]+}diff --git a/zerver/tests/test_microsoft_teams_importer.py b/zerver/tests/test_microsoft_teams_importer.pyindex c2b9348c148..9f836dc19d8 100644--- a/zerver/tests/test_microsoft_teams_importer.py+++ b/zerver/tests/test_microsoft_teams_importer.py@@ -15,6 +15,7 @@ from zerver.data_import.microsoft_teams import (MicrosoftTeamsFieldsT,MicrosoftTeamsUserIdToZulipUserIdT,MicrosoftTeamsUserRoleData,+ ODataQueryParameter,convert_users,do_convert_directory,get_microsoft_graph_api_data,@@ -347,3 +348,51 @@ class MicrosoftTeamsImporterUnitTest(MicrosoftTeamsImportTestCase):microsoft_teams_user_role_data.guest_user_ids,MICROSOFT_TEAMS_EXPORT_USER_ROLE_DATA.guest_user_ids,)++ @responses.activate+ def test_paginated_get_microsoft_graph_api_data(self) -> None:+ def paginated_graph_api_users_callback(request: PreparedRequest) -> ResponseTuple:+ assert request.url is not None+ parsed = urlsplit(request.url)+ query_params = parse_qs(parsed.query)+ queries = set(query_params.keys())++ if queries == {"$filter", "$top"}:+ body = self.fixture_data(+ "paginated_users_member.json",+ "microsoft_graph_api_response_fixtures",+ )+ elif queries == {"$filter", "$skiptoken", "$top"}:+ body = self.fixture_data(+ "paginated_users_member_2.json",+ "microsoft_graph_api_response_fixtures",+ )+ else:+ raise AssertionError("There is no response fixture for this request.")++ headers = {"Content-Type": "application/json"}+ return 200, headers, body++ responses.add_callback(+ responses.GET,+ "https://graph.microsoft.com/v1.0/users",+ callback=paginated_graph_api_users_callback,+ content_type="application/json",+ )++ odata_parameter = [+ ODataQueryParameter(parameter="$filter", expression="userType eq 'Member'"),+ ODataQueryParameter(parameter="$top", expression="3"),+ ]+ result = get_microsoft_graph_api_data(+ MICROSOFT_GRAPH_API_URL.format(endpoint="/users"),+ odata_parameter,+ token="MICROSOFT_GRAPH_API_TOKEN",+ )+ result_user_ids = {user["id"] for user in result}+ expected_member_users = {+ user["Id"]+ for user in self.get_exported_microsoft_teams_user_data()+ if user["Mail"] not in GUEST_USER_EMAILS+ }+ self.assertSetEqual(result_user_ids, expected_member_users)