Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down
4 changes: 4 additions & 0 deletions examples/Async/get_game_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
4 changes: 4 additions & 0 deletions examples/Sync/get_game_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
14 changes: 14 additions & 0 deletions src/swgoh_comlink/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
7 changes: 6 additions & 1 deletion src/swgoh_comlink/swgoh_comlink.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand All @@ -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
Expand Down
7 changes: 6 additions & 1 deletion src/swgoh_comlink/swgoh_comlink_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand All @@ -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
Expand Down
38 changes: 38 additions & 0 deletions tests/unit/test_client_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import hashlib
import hmac
import inspect
import json
from collections.abc import Awaitable, Callable
from typing import Any
Expand Down Expand Up @@ -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"),
[
Expand Down
Loading