diff --git a/examples/Async/get_language_bundle.py b/examples/Async/get_language_bundle.py index 5251a0b..5e605a8 100644 --- a/examples/Async/get_language_bundle.py +++ b/examples/Async/get_language_bundle.py @@ -1,7 +1,13 @@ # coding=utf-8 """ get_language_bundle.py -Sample script for retrieving a specific language bundle using the async client. +Sample script for retrieving a specific language bundle using the async client and decoding it by hand. + +To get the same lookup in one call, use the supported helper instead, which also skips comment +lines and applies resource limits: + + from swgoh_comlink.helpers import async_get_localization_dictionary + der_str_lookup = await async_get_localization_dictionary(cl, language="ger_de") """ import asyncio @@ -12,7 +18,7 @@ from swgoh_comlink import SwgohComlinkAsync -async def main(): +async def main() -> dict[str, str]: # Create a SwgohComlinkAsync instance async with SwgohComlinkAsync() as cl: # Retrieve the German language strings (Default is to collect data as a base64 encoded compressed string @@ -39,12 +45,21 @@ async def main(): der_obj_lines = der_obj_decoded.splitlines() # Each line has a key value and the corresponding text separated by a pipe ('|') + # The file also contains comment lines starting with '#' (e.g. '# Start Category: ...') and + # blank lines, which have no key/value pair. Values may themselves contain '|'. # To create a dictionary for easy mapping of strings from IDs used in game data collections, - # loop through the lines, split on the '|' character and store the information in an empty dict + # loop through the lines, skip comments and blank lines, split on the first '|' only and + # store the information in an empty dict der_str_lookup = {} for line in der_obj_lines: - key, value = line.split("|") - der_str_lookup[key] = value + if not line or line.startswith("#"): + continue + key, sep, value = line.partition("|") + if sep: + der_str_lookup[key] = value + + print(f"Built a lookup of {len(der_str_lookup)} German strings") + return der_str_lookup -asyncio.run(main()) +der_str_lookup = asyncio.run(main()) diff --git a/examples/Sync/get_language_bundle.py b/examples/Sync/get_language_bundle.py index e37ca16..d067a12 100644 --- a/examples/Sync/get_language_bundle.py +++ b/examples/Sync/get_language_bundle.py @@ -1,7 +1,13 @@ # coding=utf-8 """ get_language_bundle.py -Sample script for retrieving a specific language bundle. +Sample script for retrieving a specific language bundle and decoding it by hand. + +To get the same lookup in one call, use the supported helper instead, which also skips comment +lines and applies resource limits: + + from swgoh_comlink.helpers import get_localization_dictionary + der_str_lookup = get_localization_dictionary(cl, language="ger_de") """ import base64 @@ -37,9 +43,17 @@ der_obj_lines = der_obj_decoded.splitlines() # Each line has a key value and the corresponding text separated by a pipe ('|') +# The file also contains comment lines starting with '#' (e.g. '# Start Category: ...') and +# blank lines, which have no key/value pair. Values may themselves contain '|'. # To create a dictionary for easy mapping of strings from IDs used in game data collections, -# loop through the lines, split on the '|' character and store the information in an empty dict +# loop through the lines, skip comments and blank lines, split on the first '|' only and +# store the information in an empty dict der_str_lookup = {} for line in der_obj_lines: - key, value = line.split("|") - der_str_lookup[key] = value + if not line or line.startswith("#"): + continue + key, sep, value = line.partition("|") + if sep: + der_str_lookup[key] = value + +print(f"Built a lookup of {len(der_str_lookup)} German strings") diff --git a/tests/examples/test_get_language_bundle.py b/tests/examples/test_get_language_bundle.py new file mode 100644 index 0000000..e7c3fdd --- /dev/null +++ b/tests/examples/test_get_language_bundle.py @@ -0,0 +1,80 @@ +"""Tests for examples/{Sync,Async}/get_language_bundle.py. + +These test example scripts, not the library, so they live outside tests/unit/. + +Each script fetches a localization bundle and decodes it by hand at import time. The client +class is patched to return an in-memory bundle, the script is executed, and the string lookup +it builds is checked. Current bundles contain ``#`` comment lines with no ``|`` delimiter. +""" + +from __future__ import annotations + +import base64 +import importlib.util +import io +import zipfile +from pathlib import Path +from typing import Any +from unittest import mock + +import pytest + +_EXAMPLES = Path(__file__).resolve().parents[2] / "examples" + +# Shaped like a current Loc_GER_DE.txt: category comments, a bare "#", a blank line and a +# value that contains the delimiter. +_BUNDLE_TEXT = ( + "# Start Category: Star_Wars_Strategy_RPG\n" + "#\n" + "UNIT_VADER_NAME|Darth Vader\n" + "\n" + "UNIT_VADER_DESC|Sith-Lord|Imperium\n" + "EMPTY_VALUE|\n" + "# End Category: Star_Wars_Strategy_RPG (3 strings)\n" +) + +_EXPECTED = { + "UNIT_VADER_NAME": "Darth Vader", + "UNIT_VADER_DESC": "Sith-Lord|Imperium", + "EMPTY_VALUE": "", +} + + +def _localization_response() -> dict[str, str]: + """A get_localization() response whose bundle zips Loc_GER_DE.txt and Loc_Key_Mapping.txt.""" + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf: + zf.writestr("Loc_GER_DE.txt", _BUNDLE_TEXT) + zf.writestr("Loc_Key_Mapping.txt", "") + return {"localizationBundle": base64.b64encode(buf.getvalue()).decode("ascii")} + + +def _run_example(variant: str) -> Any: + """Execute examples//get_language_bundle.py against a patched client; return the module.""" + path = _EXAMPLES / variant / "get_language_bundle.py" + spec = importlib.util.spec_from_file_location(f"get_language_bundle_{variant.lower()}", path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + + if variant == "Sync": + patcher = mock.patch("swgoh_comlink.SwgohComlink") + with patcher as client_cls: + client_cls.return_value.get_localization.return_value = _localization_response() + spec.loader.exec_module(module) + client_cls.return_value.get_localization.assert_called_once_with(locale="ger_de") + else: + client = mock.MagicMock() + client.get_localization = mock.AsyncMock(return_value=_localization_response()) + with mock.patch("swgoh_comlink.SwgohComlinkAsync") as client_cls: + client_cls.return_value.__aenter__.return_value = client + spec.loader.exec_module(module) + client.get_localization.assert_awaited_once_with(locale="ger_de") + return module + + +@pytest.mark.parametrize("variant", ["Sync", "Async"]) +def test_builds_lookup_skipping_comment_lines(variant: str, capsys: pytest.CaptureFixture[str]): + module = _run_example(variant) + + assert module.der_str_lookup == _EXPECTED + assert f"{len(_EXPECTED)} German strings" in capsys.readouterr().out