diff --git a/README.md b/README.md index d782d9b..a399142 100644 --- a/README.md +++ b/README.md @@ -263,7 +263,7 @@ Methods available on both `SwgohComlink` and `SwgohComlinkAsync` (async methods | `get_guild(guild_id, include_recent_guild_activity_info, enums)` | Get guild data by guild ID | | `get_guilds_by_name(name, start_index, count, enums)` | Search guilds by name | | `get_guilds_by_criteria(search_criteria, start_index, count, enums)` | Search guilds by criteria | -| `get_game_data(version, include_pve_units, request_segment, enums, items, device_platform)` | Get game data collections (select them with `items=DataItems...`) | +| `get_game_data(version, include_pve_units, request_segment, enums, items, device_platform, *, strip_empty)` | Get game data collections (select them with `items=DataItems...`; `strip_empty=True` drops the empty ones) | | `get_game_metadata(client_specs, enums)` | Get current game and localization versions | | `get_localization(localization_id, locale, unzip, enums)` | Get localization bundles | | `get_enums(refresh)` | Get game data enums (cached per game data version) | diff --git a/examples/Async/get_game_data.py b/examples/Async/get_game_data.py index dd87137..c59cb61 100644 --- a/examples/Async/get_game_data.py +++ b/examples/Async/get_game_data.py @@ -23,6 +23,10 @@ async def main(): # The same call without the PVE units units_no_pve = await cl.get_game_data(items=DataItems.UNITS, include_pve_units=False) + # The response always holds every collection key, empty or null when not requested. + # strip_empty=True drops those, leaving only the collections that came back with data. + units_only = await cl.get_game_data(items=DataItems.UNITS, strip_empty=True) + # Combine collections with `|` (not `+`, which breaks for aliased members) skill_equipment = await cl.get_game_data(items=DataItems.SKILL | DataItems.EQUIPMENT) diff --git a/examples/Sync/get_game_data.py b/examples/Sync/get_game_data.py index ced8f14..2dfc1ac 100644 --- a/examples/Sync/get_game_data.py +++ b/examples/Sync/get_game_data.py @@ -20,6 +20,10 @@ # The same call without the PVE units units_no_pve = cl.get_game_data(items=DataItems.UNITS, include_pve_units=False) +# The response always holds every collection key, empty or null when not requested. +# strip_empty=True drops those, leaving only the collections that came back with data. +units_only = cl.get_game_data(items=DataItems.UNITS, strip_empty=True) + # Combine collections with `|` (not `+`, which breaks for aliased members) skill_equipment = cl.get_game_data(items=DataItems.SKILL | DataItems.EQUIPMENT) diff --git a/src/swgoh_comlink/_base.py b/src/swgoh_comlink/_base.py index 5c85045..4828cd1 100644 --- a/src/swgoh_comlink/_base.py +++ b/src/swgoh_comlink/_base.py @@ -649,6 +649,20 @@ def _build_game_data_payload( inner_payload["requestSegment"] = request_segment return payload + @staticmethod + def _strip_empty_collections(game_data: dict[str, Any]) -> dict[str, Any]: + """Return ``game_data`` without the keys whose value is ``None`` or an empty list or dict. + + ``/data`` returns every collection key, populating only the requested ones: unrequested list + collections come back as ``[]`` and unrequested single-object collections as ``None``. Falsy + scalars (``0``, ``False``, ``""``) are kept. + """ + return { + key: value + for key, value in game_data.items() + if value is not None and (value or not isinstance(value, (list, dict))) + } + @staticmethod def _build_unit_stats_endpoint(flags: list[str] | None = None, language: str | None = None) -> str: """Build the stats endpoint string with query parameters. diff --git a/src/swgoh_comlink/swgoh_comlink.py b/src/swgoh_comlink/swgoh_comlink.py index 33bf4e7..2838404 100644 --- a/src/swgoh_comlink/swgoh_comlink.py +++ b/src/swgoh_comlink/swgoh_comlink.py @@ -322,6 +322,8 @@ def get_game_data( enums: bool = False, items: str | DataItems | int | None = None, device_platform: str = "Android", + *, + strip_empty: bool = False, ) -> dict[str, Any]: """ Get game data. @@ -334,6 +336,8 @@ def get_game_data( items: string [Defaults to None] bitwise value indicating the collections to retrieve from game. NOTE: this parameter is mutually exclusive with request_segment. device_platform: string [Defaults to "Android"] + strip_empty: Keyword-only. Drop collections that came back empty (``[]``) or null, e.g. the ones + not selected by ``items``. [Defaults to False, which returns every collection key] Returns: A dictionary containing the game data. @@ -351,7 +355,8 @@ def get_game_data( items=items, device_platform=device_platform, ) - return cast(dict[str, Any], self._post(endpoint="data", payload=payload, timeout=GAME_DATA_TIMEOUT)) + game_data = cast(dict[str, Any], self._post(endpoint="data", payload=payload, timeout=GAME_DATA_TIMEOUT)) + return self._strip_empty_collections(game_data) if strip_empty else game_data # alias for non PEP usage of direct endpoint calls getGameData = get_game_data diff --git a/src/swgoh_comlink/swgoh_comlink_async.py b/src/swgoh_comlink/swgoh_comlink_async.py index c2c260d..8f7677e 100644 --- a/src/swgoh_comlink/swgoh_comlink_async.py +++ b/src/swgoh_comlink/swgoh_comlink_async.py @@ -321,6 +321,8 @@ async def get_game_data( enums: bool = False, items: str | DataItems | int | None = None, device_platform: str = "Android", + *, + strip_empty: bool = False, ) -> dict[str, Any]: """ Get game data. @@ -333,6 +335,8 @@ async def get_game_data( items: string [Defaults to None] bitwise value indicating the collections to retrieve from game. NOTE: this parameter is mutually exclusive with request_segment. device_platform: string [Defaults to "Android"] + strip_empty: Keyword-only. Drop collections that came back empty (``[]``) or null, e.g. the ones + not selected by ``items``. [Defaults to False, which returns every collection key] Returns: A dictionary containing the game data. @@ -350,7 +354,8 @@ async def get_game_data( items=items, device_platform=device_platform, ) - return cast(dict[str, Any], await self._post(endpoint="data", payload=payload, timeout=GAME_DATA_TIMEOUT)) + game_data = cast(dict[str, Any], await self._post(endpoint="data", payload=payload, timeout=GAME_DATA_TIMEOUT)) + return self._strip_empty_collections(game_data) if strip_empty else game_data # alias for non PEP usage of direct endpoint calls getGameData = get_game_data diff --git a/tests/unit/test_client_requests.py b/tests/unit/test_client_requests.py index 87925c7..a2308e2 100644 --- a/tests/unit/test_client_requests.py +++ b/tests/unit/test_client_requests.py @@ -9,6 +9,7 @@ import hashlib import hmac +import inspect import json from collections.abc import Awaitable, Callable from typing import Any @@ -259,6 +260,43 @@ async def test_get_guild_unwraps_guild_key( assert await call(comlink, "get_guild", guild_id="guild-1") == expected +GAME_DATA_RESPONSE = { + "units": [{"id": "U1"}], + "skill": [], + "category": {}, + "guildBanner": None, + "requestSegment": 0, + "version": "", +} + + +@pytest.mark.parametrize( + ("kwargs", "expected"), + [ + pytest.param({}, GAME_DATA_RESPONSE, id="default-keeps-everything"), + pytest.param({"strip_empty": False}, GAME_DATA_RESPONSE, id="false-keeps-everything"), + pytest.param( + {"strip_empty": True}, + {"units": [{"id": "U1"}], "requestSegment": 0, "version": ""}, + id="true-drops-empty-and-null-collections-only", + ), + ], +) +async def test_get_game_data_strip_empty( + comlink: Client, call: Call, httpx_mock: HTTPXMock, kwargs: dict[str, Any], expected: dict[str, Any] +) -> None: + httpx_mock.add_response(json=GAME_DATA_RESPONSE) + + assert await call(comlink, "get_game_data", version="v1", items="UNITS", **kwargs) == expected + + +async def test_get_game_data_strip_empty_is_keyword_only(comlink: Client) -> None: + parameter = inspect.signature(comlink.get_game_data).parameters["strip_empty"] + + assert parameter.kind is inspect.Parameter.KEYWORD_ONLY + assert parameter.default is False + + @pytest.mark.parametrize( ("method", "metadata", "endpoint", "payload_key", "version"), [