From d79193a90341acfffc9a687b715003726d9d21dd Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Mon, 9 Nov 2026 13:58:16 -0500 Subject: [PATCH 1/3] feat(statcalc): apply a named datacron's stat affixes to characters A player owns many datacrons and picks one per squad, so stats are asked for "with this datacron" rather than "with datacrons". calc_player_stats takes a datacron_id from the player's own collection; calc_roster_stats and calc_char_stats take the datacron object. The acalc_* wrappers on StatCalcAsync pass the same arguments through. Each character gains a `datacron` bucket beside `final`, never summed into it. The bucket is the last link of the percent-conversion chain, so `final + datacron` is correct for every stat, including the non-linear percentage stats such as Armor and Resistance. Ships get no bucket. Affixes are gated on the unit's gear tier and encoded relic tier; a unit with no relic sits at the locked tier rather than 0, so it still gets the affixes that require no relic. Ability affixes are skipped. Percent affixes expand onto their target stats through the mapping the mod path already uses, now shared from the new _datacron module, and resolve against base plus gear, excluding mods. A stat's affix percentages are summed and then rounded to the two decimals the datacron card shows, which is what in-game readings match. Without a datacron argument nothing changes: no bucket appears and the output is identical to before. Co-Authored-By: Claude Opus 5.5 --- docs/api/statcalc.md | 62 +- src/swgoh_comlink/StatCalc/_datacron.py | 134 ++++ src/swgoh_comlink/StatCalc/calculator.py | 102 ++- .../StatCalc/calculator_async.py | 19 +- tests/statcalc/test_datacron.py | 699 ++++++++++++++++++ tests/unit/test_statcalc_async.py | 42 ++ 6 files changed, 1023 insertions(+), 35 deletions(-) create mode 100644 src/swgoh_comlink/StatCalc/_datacron.py create mode 100644 tests/statcalc/test_datacron.py diff --git a/docs/api/statcalc.md b/docs/api/statcalc.md index 229c814..e57b3cb 100644 --- a/docs/api/statcalc.md +++ b/docs/api/statcalc.md @@ -100,6 +100,62 @@ gp = calc.calc_char_gp(unit) ship_gp = calc.calc_ship_gp(ship_unit, crew_list) ``` +### Apply a datacron + +A player owns many datacrons and picks one per squad when they deploy, so there +is no such thing as "this unit's stats with datacrons", only "this unit's stats +with *this* datacron". Name the one you mean: + +```python +player = comlink.get_player(allycode=245866537) +datacron_id = player["datacron"][0]["id"] +calc.calc_player_stats(player, datacron_id=datacron_id) + +unit = player["rosterUnit"][0] +print(unit["stats"]["final"]) # unchanged by the datacron +print(unit["stats"]["datacron"]) # what the datacron adds to this unit +``` + +`calc_player_stats` takes a datacron **id** and looks it up in the player's own +`datacron` collection, raising `KeyError` if the player does not own it. +`calc_roster_stats` and `calc_char_stats` take the datacron **object**, having +no player to look it up in: + +```python +datacron = next(d for d in player["datacron"] if d["id"] == datacron_id) +calc.calc_char_stats(unit, datacron) +``` + +Leave the argument out and nothing changes: no `datacron` key appears and the +output is the same as before. + +#### Combining the buckets + +The `datacron` bucket is deliberately **not** summed into `final`. Add the two +to get a unit's stats as it would fight with that datacron: + +```python +stats = unit["stats"] +combined = {name: value + stats["datacron"].get(name, 0) for name, value in stats["final"].items()} +``` + +That addition is correct for **every** stat, including ones reported as +percentages such as Armor and Resistance. Those are converted non-linearly, so +a raw percentage could not simply be added to them; the bucket instead holds +the amount the datacron actually adds on top of everything else. + +Worth knowing: + +- **Ships never get a bucket.** Datacrons are a squad mechanic and no game mode + applies one to a fleet battle, so ship stats are unaffected. +- **Affixes are gated per unit.** Each affix requires a gear tier and a relic + tier, so the same datacron adds different amounts to different units. Relic + tiers in the game data count the locked and unlocked states as their first + two values, so a `requiredRelicTier` of 5 means relic 3 as a player counts it. +- **Percentages apply as the datacron card shows them.** A stat's affix + percentages are summed, rounded to two decimals, and then applied to the + unit's base plus gear stats. Mods do not count toward that total. + ## Async Usage (`StatCalcAsync`) Use the async `create()` factory to fetch game data without blocking the event @@ -109,10 +165,10 @@ guild does not stall the loop (for example a Discord bot's gateway heartbeat). | Async method | Runs | |--------------|------| -| `await calc.acalc_char_stats(unit)` | `calc_char_stats` | +| `await calc.acalc_char_stats(unit, datacron=None)` | `calc_char_stats` | | `await calc.acalc_ship_stats(ship, crew)` | `calc_ship_stats` | -| `await calc.acalc_roster_stats(units)` | `calc_roster_stats` | -| `await calc.acalc_player_stats(players)` | `calc_player_stats` | +| `await calc.acalc_roster_stats(units, datacron=None)` | `calc_roster_stats` | +| `await calc.acalc_player_stats(players, datacron_id=None)` | `calc_player_stats` | ```python from swgoh_comlink import SwgohComlinkAsync, StatCalcAsync diff --git a/src/swgoh_comlink/StatCalc/_datacron.py b/src/swgoh_comlink/StatCalc/_datacron.py new file mode 100644 index 0000000..04ed41a --- /dev/null +++ b/src/swgoh_comlink/StatCalc/_datacron.py @@ -0,0 +1,134 @@ +"""Datacron stat resolution. + +Pure computation: no instance state, no game data, no I/O. Datacron stat affixes +carry no unit scope of any kind, so resolving them needs nothing beyond the +datacron itself, the unit it is applied to, and that unit's stats before the +datacron is considered. + +Values are in unscaled space throughout: raw game-data fixed point, where ``1e8`` +represents ``1.0``. Callers scale for display afterwards. +""" + +from __future__ import annotations + +import math +from typing import Any + +__all__ = [ + "STAT_PERCENT_OF_BASE", + "STAT_SPLITS", + "resolve_datacron_stats", +] + +# Percent-additive stat ids do not name the stat they affect: they expand onto one +# or more real target stats. Mods and datacrons expand the same ids onto the same +# targets, so the mapping is shared. The arithmetic is not (mods resolve against +# base alone, datacrons against base plus gear), but two copies of the mapping +# could drift apart and silently credit the wrong stat. + +#: Stat ids that add their value to each of several stats (e.g. 41, Offense, adds to 6 and 7). +STAT_SPLITS: dict[int, tuple[str, ...]] = { + 41: ("6", "7"), + 42: ("8", "9"), + 53: ("21", "22"), + 54: ("35", "36"), +} + +#: Percent stat ids that add a share of an existing stat to each target, floored to whole units. +STAT_PERCENT_OF_BASE: dict[int, tuple[str, ...]] = { + 48: ("6", "7"), + 49: ("8", "9"), + 55: ("1",), + 56: ("28",), + 57: ("5",), +} + +# Relic tiers are encoded with their two base states, locked and unlocked, taking +# the first two values, so the relic number a player sees is two lower than the +# encoded one: an encoded 5 is relic 3. An affix's ``requiredRelicTier`` and a +# unit's ``currentTier`` both use this encoding, so they are compared directly. +_LOCKED_RELIC_TIER = 1 + +_UNIT = 1e8 + + +def resolve_datacron_stats( + datacron: dict[str, Any], + unit: dict[str, Any], + unmodded_total: dict[str, float], +) -> dict[str, float]: + """Resolve one datacron's stat contribution to one unit. + + Args: + datacron: A datacron from a player's ``datacron`` collection. + unit: A normalized character, with ``gear`` and ``relic`` keys. + unmodded_total: The unit's per-stat base plus gear totals, excluding mods, + in unscaled space. Datacron percentages resolve against this total; + in-game readings show mods are not part of it. + + Returns: + Per-stat contributions keyed by stat id, in unscaled space. Empty when the + datacron grants the unit nothing. + """ + gear_tier = int(unit.get("gear") or 0) + relic_tier = _relic_tier(unit) + + totals: dict[int, float] = {} + for affix in datacron.get("affix") or (): + # An ability affix grants an ability, not a stat. It reports stat type 1 + # with value 0 today; skipping it by its ability keeps a future non-zero + # value from being counted as Health. + if affix.get("abilityId"): + continue + if gear_tier < int(affix.get("requiredUnitTier") or 0): + continue + if relic_tier < int(affix.get("requiredRelicTier") or 0): + continue + if not (stat_id := int(affix.get("statType") or 0)): + continue + totals[stat_id] = totals.get(stat_id, 0.0) + float(affix.get("statValue") or 0) + + return _expand({stat_id: _as_displayed(value) for stat_id, value in totals.items()}, unmodded_total) + + +def _as_displayed(value: float) -> float: + """Round a stat's summed percentage to the two decimals the datacron card shows. + + In-game readings match the displayed percentage, not the six-decimal stored + one. Affixes are summed before rounding: two affixes of 2.828575% and + 19.515055% apply as 22.34%, not as 22.35%, the sum of the rounded parts. + """ + return round(value / 1e6, 2) * 1e6 + + +def _expand(totals: dict[int, float], unmodded_total: dict[str, float]) -> dict[str, float]: + """Resolve percent-additive stat ids onto the stats they actually modify.""" + expanded: dict[str, float] = {} + for stat_id, value in totals.items(): + if (targets := STAT_SPLITS.get(stat_id)) is not None: + for target in targets: + expanded[target] = expanded.get(target, 0.0) + value + elif (targets := STAT_PERCENT_OF_BASE.get(stat_id)) is not None: + for target in targets: + # Floored to whole units, as the mod path floors its own percentage growth. + current = expanded.get(target, 0.0) + grown = current + unmodded_total.get(target, 0.0) * 1e-8 * value + expanded[target] = math.floor(grown / _UNIT) * _UNIT + else: + key = str(stat_id) + expanded[key] = expanded.get(key, 0.0) + value + return expanded + + +def _relic_tier(unit: dict[str, Any]) -> int: + """Return the unit's encoded relic tier. + + A unit with no relic reports ``relic`` as ``None`` rather than a zeroed + structure, and sits at the locked base state. Treating it as 0 would fail + even the baseline relic requirement every affix carries and silently drop + the datacron's contribution to every relic-less unit. + """ + relic = unit.get("relic") + if not isinstance(relic, dict) or relic.get("currentTier") is None: + return _LOCKED_RELIC_TIER + return int(relic["currentTier"]) diff --git a/src/swgoh_comlink/StatCalc/calculator.py b/src/swgoh_comlink/StatCalc/calculator.py index 4482bca..95a1504 100644 --- a/src/swgoh_comlink/StatCalc/calculator.py +++ b/src/swgoh_comlink/StatCalc/calculator.py @@ -12,6 +12,9 @@ from ..exceptions import SwgohComlinkValueError from ..helpers._stat_data import STATS as _CANONICAL_STATS +from ._datacron import STAT_PERCENT_OF_BASE as _MOD_STAT_PERCENT_OF_BASE +from ._datacron import STAT_SPLITS as _MOD_STAT_SPLITS +from ._datacron import resolve_datacron_stats # Largest game data body accepted, counted after any Content-Encoding is decoded # (gameData.json is about 1.6 MB). @@ -20,22 +23,6 @@ _SHA256_HEX = re.compile(r"[0-9a-f]{64}") -# Mod stats that add their value to each of several stats (e.g. 41, Offense, adds to 6 and 7). -_MOD_STAT_SPLITS: dict[int, tuple[str, ...]] = { - 41: ("6", "7"), - 42: ("8", "9"), - 53: ("21", "22"), - 54: ("35", "36"), -} -# Percent mod stats that add a share of the unit's base stat to each target stat, floored to 8 digits. -_MOD_STAT_PERCENT_OF_BASE: dict[int, tuple[str, ...]] = { - 48: ("6", "7"), - 49: ("8", "9"), - 55: ("1",), - 56: ("28",), - 57: ("5",), -} - # Character stat ids whose final value is added to another stat (Physical and Special Critical # Chance to Critical Rating, Physical and Special Critical Avoidance to Critical Avoidance Rating). _FLAT_STAT_IDS: dict[str, str] = {"21": "14", "22": "15", "35": "39", "36": "40"} @@ -245,12 +232,17 @@ def set_game_data(self, game_data: dict[str, Any]) -> None: len(self._mod_set_data), ) - def calc_char_stats(self, unit: dict[str, Any]) -> dict[str, Any]: + def calc_char_stats(self, unit: dict[str, Any], datacron: dict[str, Any] | None = None) -> dict[str, Any]: """Calculate stats and GP for a character unit. Args: unit: Character object in either normalized (`defId`) or raw game format (`definitionId`). + datacron: Optional datacron object, as found in a player's + `datacron` collection. When given, `stats` gains a `datacron` + bucket holding what that datacron adds to this unit. The bucket + is not summed into `final`; `final + datacron` is the unit's + value with the datacron applied, for every stat. Returns: The input unit with `stats` and `gp` keys added, containing the calculated stats and GP. @@ -262,6 +254,8 @@ def calc_char_stats(self, unit: dict[str, Any]) -> dict[str, Any]: stats: dict[str, Any] = self._get_char_raw_stats(char) stats = self._calculate_base_stats(stats, char["level"], char["defId"]) stats["mods"] = self._calculate_mod_stats(stats["base"], char) + if datacron is not None: + stats["datacron"] = resolve_datacron_stats(datacron, char, self._unmodded_total(stats)) stats = self._format_stats(stats, char["level"]) stats = self._rename_stats(stats) @@ -300,11 +294,15 @@ def calc_ship_stats(self, unit: dict[str, Any], crew_member: list[dict[str, Any] return unit - def calc_roster_stats(self, units: Any) -> Any: + def calc_roster_stats(self, units: Any, datacron: dict[str, Any] | None = None) -> Any: """Calculate stats for all units in a roster-like payload. Args: units: Either a list of units or a legacy dict keyed by unit id. + datacron: Optional datacron object to apply to every character, as + in :meth:`calc_char_stats`. Ships get no `datacron` bucket and + their stats are unchanged: no game mode applies a datacron to + a fleet. Returns: Input object with `stats` and `gp` fields added for each unit. Ships @@ -330,7 +328,7 @@ def calc_roster_stats(self, units: Any) -> Any: ships.append((unit, def_id, meta)) else: crew[def_id] = unit - unit = self.calc_char_stats(unit) + unit = self.calc_char_stats(unit, datacron) for ship, def_id, meta in ships: crw = [crew[cid] for cid in meta["crew"] if cid in crew] @@ -360,7 +358,7 @@ def calc_roster_stats(self, units: Any) -> Any: "mods": unit.get("equippedStatMod"), "skills": unit.get("skill", []), } - temp_unit = self.calc_char_stats(temp_unit) + temp_unit = self.calc_char_stats(temp_unit, datacron) if "stats" in temp_unit: unit["stats"] = temp_unit["stats"] if "gp" in temp_unit: @@ -369,12 +367,18 @@ def calc_roster_stats(self, units: Any) -> Any: return units def calc_player_stats( - self, players: dict[str, Any] | list[dict[str, Any]] + self, players: dict[str, Any] | list[dict[str, Any]], datacron_id: str | None = None ) -> dict[str, Any] | list[dict[str, Any]]: """Calculate stats for one or more player payloads. Args: players: One player object, or a list of player objects, each with a `rosterUnit` element. + datacron_id: Optional id of a datacron in each player's own + `datacron` collection. When given, every character gains a + `datacron` stat bucket, as in :meth:`calc_char_stats`. This + method takes an id because the collection to look it up in is + part of the player payload; :meth:`calc_roster_stats` and + :meth:`calc_char_stats` take the datacron object itself. Returns: The input object with `stats` and `gp` fields added for each player's roster. @@ -382,6 +386,8 @@ def calc_player_stats( Raises: RuntimeError: If a dict player is missing a 'rosterUnit' key. TypeError: If the input object is not a list or dict. + KeyError: If `datacron_id` is given and a player has no `datacron` + collection or does not own that datacron. """ if not isinstance(players, (list, dict)): raise TypeError("Expected a list or dict of players") @@ -391,13 +397,39 @@ def calc_player_stats( if isinstance(players, list): for player in players: - self.calc_roster_stats(player.get("rosterUnit")) + self.calc_roster_stats(player.get("rosterUnit"), self._select_datacron(player, datacron_id)) return players if "rosterUnit" not in players: raise RuntimeError("Expected a dict with a 'rosterUnit' key") - self.calc_roster_stats(players["rosterUnit"]) + self.calc_roster_stats(players["rosterUnit"], self._select_datacron(players, datacron_id)) return players + @staticmethod + def _select_datacron(player: dict[str, Any], datacron_id: str | None) -> dict[str, Any] | None: + """Return the datacron *datacron_id* from *player*'s collection, or None if no id is given.""" + if datacron_id is None: + return None + collection = player.get("datacron") + if collection is None: + # A player who owns no datacrons reports an empty list, not a missing key. + raise KeyError("Player payload has no 'datacron' collection to look the datacron id up in") + for datacron in collection: + if datacron.get("id") == datacron_id: + return datacron + raise KeyError(f"Datacron {datacron_id!r} is not among the player's {len(collection)} datacrons") + + @staticmethod + def _unmodded_total(stats: dict[str, Any]) -> dict[str, float]: + """Return the per-stat sum of base and gear, excluding mods, in unscaled space. + + Datacron percentages resolve against this total; in-game readings show + that mods do not count toward it. + """ + total = dict(stats["base"]) + for stat_id, value in stats.get("gear", {}).items(): + total[stat_id] = total.get(stat_id, 0) + value + return total + def calc_char_gp(self, char: dict[str, Any]) -> int: """Calculate GP for a character. @@ -871,6 +903,9 @@ def _format_stats(self, stats: dict[str, Any], level: int) -> dict[str, Any]: if mods: for stat_id, value in mods.items(): mods[stat_id] = value * scale + if datacron := stats.get("datacron"): + for stat_id, value in datacron.items(): + datacron[stat_id] = value * scale if self._FIXED_PERCENT_VALS or self._FIXED_GAME_STYLE: percent_scale = scale * 1e8 @@ -920,6 +955,14 @@ def crit_avoidance(val: float) -> float: mod_values = stats["mods"] or {} stat_ids |= dict.fromkeys(stats["mods"]) gs_stats["mods"] = stats["mods"] + if "datacron" in stats: + # Kept beside final, never summed into it, and keyed the way final is so the + # two can be added stat by stat. + datacron_values: dict[str, Any] = {} + for stat_id, value in stats["datacron"].items(): + key = _FLAT_STAT_IDS.get(stat_id, stat_id) + datacron_values[key] = datacron_values.get(key, 0) + value + gs_stats["datacron"] = datacron_values for stat_id in stat_ids: key = _FLAT_STAT_IDS.get(stat_id, stat_id) @@ -957,8 +1000,9 @@ def _convert_percent(stats: dict[str, Any], conversions: Iterable[tuple[str, Cal """Convert each flat stat to a percent with its converter, in order. The base value becomes the percent of the base flat value. A ship's crew value, or a - character's gear and then mods value, becomes the percent it adds on top of the - values before it. + character's gear, mods and then datacron value, becomes the percent it adds on top + of the values before it. The datacron comes last, so ``final + datacron`` is the + converted value of the whole flat total. """ # The stat dicts are only updated in place, so they are looked up once for all conversions. base = stats["base"] @@ -966,6 +1010,7 @@ def _convert_percent(stats: dict[str, Any], conversions: Iterable[tuple[str, Cal crew = stats.get("crew") gear = stats.get("gear") mods = stats.get("mods") + datacron = stats.get("datacron") for sid, convert_func in conversions: flat = base.get(sid, 0) percent = convert_func(flat) @@ -984,7 +1029,12 @@ def _convert_percent(stats: dict[str, Any], conversions: Iterable[tuple[str, Cal last = percent if mods and (mod_value := mods.get(sid, 0)): flat = flat + mod_value - mods[sid] = convert_func(flat) - last + percent = convert_func(flat) + mods[sid] = percent - last + last = percent + if datacron and (datacron_value := datacron.get(sid, 0)): + flat = flat + datacron_value + datacron[sid] = convert_func(flat) - last def _calc_char_gp(self, char: dict[str, Any]) -> int: assert self._gp_tables is not None # type narrowing: set_game_data() set it; _require_game_data() ran diff --git a/src/swgoh_comlink/StatCalc/calculator_async.py b/src/swgoh_comlink/StatCalc/calculator_async.py index 8224b2b..da801ad 100644 --- a/src/swgoh_comlink/StatCalc/calculator_async.py +++ b/src/swgoh_comlink/StatCalc/calculator_async.py @@ -99,17 +99,18 @@ async def create( cls._LOGGER.debug("Using caller-provided game data") return cls(game_data=game_data) - async def acalc_char_stats(self, unit: dict[str, Any]) -> dict[str, Any]: + async def acalc_char_stats(self, unit: dict[str, Any], datacron: dict[str, Any] | None = None) -> dict[str, Any]: """Run :meth:`calc_char_stats` in a worker thread. Args: unit: Character object in either normalized (`defId`) or raw game format (`definitionId`). + datacron: Optional datacron object to apply, as in :meth:`calc_char_stats`. Returns: The input unit with `stats` and `gp` keys added. """ - return await asyncio.to_thread(self.calc_char_stats, unit) + return await asyncio.to_thread(self.calc_char_stats, unit, datacron) async def acalc_ship_stats(self, unit: dict[str, Any], crew_member: list[dict[str, Any]]) -> dict[str, Any]: """Run :meth:`calc_ship_stats` in a worker thread. @@ -123,24 +124,28 @@ async def acalc_ship_stats(self, unit: dict[str, Any], crew_member: list[dict[st """ return await asyncio.to_thread(self.calc_ship_stats, unit, crew_member) - async def acalc_roster_stats(self, units: Any) -> Any: + async def acalc_roster_stats(self, units: Any, datacron: dict[str, Any] | None = None) -> Any: """Run :meth:`calc_roster_stats` in a worker thread. Args: units: Either a list of units or a legacy dict keyed by unit id. + datacron: Optional datacron object to apply to every character, as + in :meth:`calc_roster_stats`. Returns: Input object with `stats` and `gp` fields added for each unit. """ - return await asyncio.to_thread(self.calc_roster_stats, units) + return await asyncio.to_thread(self.calc_roster_stats, units, datacron) async def acalc_player_stats( - self, players: dict[str, Any] | list[dict[str, Any]] + self, players: dict[str, Any] | list[dict[str, Any]], datacron_id: str | None = None ) -> dict[str, Any] | list[dict[str, Any]]: """Run :meth:`calc_player_stats` in a worker thread. Args: players: One player object, or a list of player objects, each with a `rosterUnit` element. + datacron_id: Optional id of a datacron in each player's own + `datacron` collection, as in :meth:`calc_player_stats`. Returns: The input object with `stats` and `gp` fields added for each player's roster. @@ -148,8 +153,10 @@ async def acalc_player_stats( Raises: RuntimeError: If a dict player is missing a 'rosterUnit' key. TypeError: If the input object is not a list or dict. + KeyError: If `datacron_id` is given and a player has no `datacron` + collection or does not own that datacron. """ - return await asyncio.to_thread(self.calc_player_stats, players) + return await asyncio.to_thread(self.calc_player_stats, players, datacron_id) @classmethod async def _async_fetch_game_data_from_github( diff --git a/tests/statcalc/test_datacron.py b/tests/statcalc/test_datacron.py new file mode 100644 index 0000000..07f154f --- /dev/null +++ b/tests/statcalc/test_datacron.py @@ -0,0 +1,699 @@ +"""Datacron behaviour, driven entirely through ``calc_player_stats``. + +Single seam by design: a player payload is an ordinary dict, so hand-authored +players give exact control over gear tiers, relic tiers and affix thresholds +without reaching into the resolution module. Nothing here may monkeypatch +private methods or assert on where the datacron step sits in the pipeline — +that position is an implementation detail. +""" + +from __future__ import annotations + +import copy +import json +import math +from pathlib import Path +from typing import Any + +import pytest + +from swgoh_comlink import StatCalc + +_RESOURCES = Path(__file__).resolve().parent.parent / "resources" +_GAME_DATA_FILE = _RESOURCES / "gameData.json" +_PLAYER_FILE = _RESOURCES / "example-player.json" + +# A character present in the committed game data, used wherever the test needs +# a real unit definition rather than a specific character's properties. +_CHAR = "CADBANE" + +DATACRON_ID = "test-datacron" + + +# ── Fixtures ───────────────────────────────────────────────────────────── + + +@pytest.fixture(scope="module") +def game_data() -> dict[str, Any]: + return json.loads(_GAME_DATA_FILE.read_text())["data"] + + +@pytest.fixture(scope="module") +def calc(game_data: dict[str, Any]) -> StatCalc: + return StatCalc(game_data=game_data) + + +@pytest.fixture(scope="module") +def example_player() -> dict[str, Any]: + return json.loads(_PLAYER_FILE.read_text()) + + +# ── Payload builders ───────────────────────────────────────────────────── + + +def stat_affix( + stat_type: int, + value: int, + *, + required_unit_tier: int = 0, + required_relic_tier: int = 1, +) -> dict[str, Any]: + """A Stat Affix. Never carries a target rule — real ones never do.""" + return { + "tag": [], + "targetRule": "", + "abilityId": "", + "statType": stat_type, + "statValue": str(value), + "requiredUnitTier": required_unit_tier, + "requiredRelicTier": required_relic_tier, + "scopeIcon": "", + } + + +def ability_affix(ability_id: str = "datacron_alignment_generic_030") -> dict[str, Any]: + """An Ability Affix, shaped as the game reports one: stat type 1, value 0.""" + return { + "tag": ["darkside"], + "targetRule": "target_datacron_darkside", + "abilityId": ability_id, + "statType": 1, + "statValue": "0", + "requiredUnitTier": 0, + "requiredRelicTier": 1, + "scopeIcon": "tex.datacronui_affix_darkside", + } + + +def datacron(*affixes: dict[str, Any], datacron_id: str = DATACRON_ID) -> dict[str, Any]: + return { + "id": datacron_id, + "setId": 25, + "templateId": "datacron_set_25_base", + "tag": [], + "affix": list(affixes), + "rerollOption": [], + "locked": False, + "rerollIndex": 0, + "rerollCount": 0, + "focused": False, + } + + +def character( + def_id: str = _CHAR, + *, + gear_tier: int = 13, + relic_tier: int | None = 11, + level: int = 85, + rarity: int = 7, +) -> dict[str, Any]: + """A roster unit. `relic_tier=None` produces a unit with no relic at all.""" + unit: dict[str, Any] = { + "definitionId": f"{def_id}:SEVEN_STAR", + "currentRarity": rarity, + "currentLevel": level, + "currentTier": gear_tier, + "equipment": [], + "skill": [], + "equippedStatMod": [], + "relic": None if relic_tier is None else {"currentTier": relic_tier}, + } + return unit + + +def player(*units: dict[str, Any], datacrons: list[dict[str, Any]] | None = None) -> dict[str, Any]: + return { + "rosterUnit": list(units), + "datacron": [] if datacrons is None else datacrons, + } + + +def datacron_bucket(calc: StatCalc, payload: dict[str, Any], datacron_id: str | None = DATACRON_ID) -> dict[str, Any]: + """Run one player through the seam and return the first unit's bucket.""" + result = calc.calc_player_stats(copy.deepcopy(payload), datacron_id=datacron_id) + assert isinstance(result, dict) + return result["rosterUnit"][0]["stats"].get("datacron", {}) + + +# ── The bucket appears, and only when asked for ─────────────────────────── + + +def test_characters_gain_a_datacron_bucket(calc: StatCalc) -> None: + payload = player(character(), datacrons=[datacron(stat_affix(16, 50_000_000))]) + + assert datacron_bucket(calc, payload) == {"Critical Damage": pytest.approx(0.5)} + + +def test_bucket_is_absent_not_empty_when_no_datacron_requested(calc: StatCalc) -> None: + payload = player(character(), datacrons=[datacron(stat_affix(16, 50_000_000))]) + + result = calc.calc_player_stats(copy.deepcopy(payload)) + assert isinstance(result, dict) + + assert "datacron" not in result["rosterUnit"][0]["stats"] + + +def test_output_is_unchanged_when_no_datacron_requested(calc: StatCalc, example_player: dict[str, Any]) -> None: + """The whole feature is dormant unless a datacron is named.""" + before = calc.calc_player_stats(copy.deepcopy(example_player)) + after = calc.calc_player_stats(copy.deepcopy(example_player), datacron_id=None) + + assert after == before + + +# ── Passthrough stat types ──────────────────────────────────────────────── + + +def test_stat_values_are_scaled_for_display(calc: StatCalc) -> None: + """Affix values arrive in Unscaled Space and leave in display units.""" + payload = player(character(), datacrons=[datacron(stat_affix(17, 12_500_000))]) + + assert datacron_bucket(calc, payload)["Potency"] == pytest.approx(0.125) + + +def test_a_stat_type_repeated_across_levels_is_summed(calc: StatCalc) -> None: + payload = player( + character(), + datacrons=[ + datacron( + stat_affix(16, 21_927_327), + stat_affix(16, 23_172_075), + stat_affix(16, 42_891_143), + ) + ], + ) + + # 21.927327 + 23.172075 + 42.891143 = 87.990545%, applied as the 87.99% + # the card displays. + assert datacron_bucket(calc, payload)["Critical Damage"] == pytest.approx(0.8799) + + +def test_a_percentage_is_applied_as_the_card_displays_it(calc: StatCalc) -> None: + """The game applies the two-decimal percentage, not the stored value. + + Measured on Lord Vader: a 27.14327% Protection affix against a base of + 116,765 contributed 31,690, which is 27.14% of it. The stored value would + have given 31,693. + """ + payload = player(character(), datacrons=[datacron(stat_affix(16, 27_143_270))]) + + assert datacron_bucket(calc, payload)["Critical Damage"] == pytest.approx(0.2714) + + +def test_percentages_are_summed_before_they_are_rounded(calc: StatCalc) -> None: + """Rounding each affix first would give a different, wrong answer. + + Measured: affixes of 2.828575% and 19.515055% are applied as 22.34% — the + rounded sum. Rounding each part first gives 2.83 + 19.52 = 22.35%. + """ + payload = player( + character(), + datacrons=[datacron(stat_affix(16, 2_828_575), stat_affix(16, 19_515_055))], + ) + + assert datacron_bucket(calc, payload)["Critical Damage"] == pytest.approx(0.2234) + + +def test_distinct_stat_types_stay_distinct(calc: StatCalc) -> None: + payload = player( + character(), + datacrons=[datacron(stat_affix(17, 10_000_000), stat_affix(18, 20_000_000))], + ) + + assert datacron_bucket(calc, payload) == { + "Potency": pytest.approx(0.1), + "Tenacity": pytest.approx(0.2), + } + + +def test_bucket_stat_names_match_the_other_buckets(calc: StatCalc) -> None: + """Names must line up so a caller can pair buckets without a lookup table.""" + payload = player(character(), datacrons=[datacron(stat_affix(16, 50_000_000))]) + + result = calc.calc_player_stats(copy.deepcopy(payload), datacron_id=DATACRON_ID) + assert isinstance(result, dict) + stats = result["rosterUnit"][0]["stats"] + + assert set(stats["datacron"]) <= set(stats["final"]) + + +# ── Ability Affixes ─────────────────────────────────────────────────────── + + +def test_ability_affixes_contribute_nothing(calc: StatCalc) -> None: + payload = player(character(), datacrons=[datacron(ability_affix(), ability_affix())]) + + assert datacron_bucket(calc, payload) == {} + + +def test_ability_affixes_are_skipped_even_carrying_a_real_stat_value(calc: StatCalc) -> None: + """Identified by granting an ability, not by having a zero value.""" + affix = ability_affix() + affix["statValue"] = "50000000" + payload = player(character(), datacrons=[datacron(affix)]) + + assert datacron_bucket(calc, payload) == {} + + +def test_stat_affixes_survive_alongside_ability_affixes(calc: StatCalc) -> None: + payload = player( + character(), + datacrons=[datacron(stat_affix(16, 30_000_000), ability_affix(), stat_affix(17, 10_000_000))], + ) + + assert datacron_bucket(calc, payload) == { + "Critical Damage": pytest.approx(0.3), + "Potency": pytest.approx(0.1), + } + + +# ── Affix Requirement gating ────────────────────────────────────────────── + + +@pytest.mark.parametrize( + ("unit_gear_tier", "applies"), + [(13, True), (12, True), (11, False), (1, False)], + ids=["above", "met exactly", "one short", "far short"], +) +def test_gear_tier_requirement(calc: StatCalc, unit_gear_tier: int, applies: bool) -> None: + payload = player( + character(gear_tier=unit_gear_tier), + datacrons=[datacron(stat_affix(16, 50_000_000, required_unit_tier=12))], + ) + + assert bool(datacron_bucket(calc, payload)) is applies + + +@pytest.mark.parametrize( + ("unit_relic_tier", "applies"), + [(11, True), (8, True), (7, False), (3, False)], + ids=["above", "met exactly", "one short", "far short"], +) +def test_relic_tier_requirement(calc: StatCalc, unit_relic_tier: int, applies: bool) -> None: + """Encoded tiers on both sides, so the comparison is direct. + + Offsetting either side would shift this threshold by two tiers, which is + exactly what the 'one short' case would stop catching. + """ + payload = player( + character(relic_tier=unit_relic_tier), + datacrons=[datacron(stat_affix(16, 50_000_000, required_relic_tier=8))], + ) + + assert bool(datacron_bucket(calc, payload)) is applies + + +def test_both_requirements_must_be_met(calc: StatCalc) -> None: + affix = stat_affix(16, 50_000_000, required_unit_tier=12, required_relic_tier=8) + + both = player(character(gear_tier=13, relic_tier=9), datacrons=[datacron(affix)]) + assert datacron_bucket(calc, both) + + gear_short = player(character(gear_tier=11, relic_tier=9), datacrons=[datacron(affix)]) + assert datacron_bucket(calc, gear_short) == {} + + relic_short = player(character(gear_tier=13, relic_tier=7), datacrons=[datacron(affix)]) + assert datacron_bucket(calc, relic_short) == {} + + +def test_relic_less_unit_still_receives_unrestricted_affixes(calc: StatCalc) -> None: + """Regression: a unit with no relic sits at the locked base state, not zero. + + Treating it as zero fails even the baseline requirement every affix + carries, silently zeroing every relic-less unit while leaving the + high-relic units anyone would spot-check looking perfectly correct. + """ + payload = player( + character(gear_tier=1, relic_tier=None), + datacrons=[datacron(stat_affix(16, 50_000_000))], + ) + + assert datacron_bucket(calc, payload) == {"Critical Damage": pytest.approx(0.5)} + + +def test_relic_less_unit_is_denied_affixes_that_require_a_relic(calc: StatCalc) -> None: + payload = player( + character(gear_tier=13, relic_tier=None), + datacrons=[datacron(stat_affix(16, 50_000_000, required_relic_tier=3))], + ) + + assert datacron_bucket(calc, payload) == {} + + +def test_the_same_datacron_gives_different_units_different_contributions(calc: StatCalc) -> None: + """The whole point of gating: one datacron, a roster of varied progress.""" + dc = datacron( + stat_affix(16, 10_000_000), + stat_affix(17, 20_000_000, required_relic_tier=8), + stat_affix(18, 30_000_000, required_unit_tier=12, required_relic_tier=11), + ) + payload = player( + character(gear_tier=13, relic_tier=11), + character(gear_tier=13, relic_tier=8), + character(gear_tier=1, relic_tier=None), + datacrons=[dc], + ) + + result = calc.calc_player_stats(copy.deepcopy(payload), datacron_id=DATACRON_ID) + assert isinstance(result, dict) + buckets = [unit["stats"]["datacron"] for unit in result["rosterUnit"]] + + assert set(buckets[0]) == {"Critical Damage", "Potency", "Tenacity"} + assert set(buckets[1]) == {"Critical Damage", "Potency"} + assert set(buckets[2]) == {"Critical Damage"} + + +def test_a_relic_threshold_splits_the_real_roster(calc: StatCalc, example_player: dict[str, Any]) -> None: + """Gating against real units, whose relic tiers span the threshold. + + The committed player's characters sit across several relic tiers, so an + affix requiring a high one must reach strictly fewer of them than an + unrestricted affix does. + """ + payload = copy.deepcopy(example_player) + payload["datacron"] = [ + datacron(stat_affix(16, 10_000_000), datacron_id="unrestricted"), + datacron(stat_affix(16, 10_000_000, required_relic_tier=11), datacron_id="restricted"), + ] + + def reached(datacron_id: str) -> int: + result = calc.calc_player_stats(copy.deepcopy(payload), datacron_id=datacron_id) + assert isinstance(result, dict) + return sum(1 for unit in result["rosterUnit"] if unit.get("stats", {}).get("datacron")) + + everyone = reached("unrestricted") + qualified = reached("restricted") + + assert everyone > 0 + assert 0 < qualified < everyone + + +# ── Percent-additive expansion ──────────────────────────────────────────── + + +def test_additive_offense_expands_onto_both_damage_stats(calc: StatCalc) -> None: + payload = player(character(), datacrons=[datacron(stat_affix(41, 5_000_000))]) + + assert datacron_bucket(calc, payload) == { + "Physical Damage": pytest.approx(0.05), + "Special Damage": pytest.approx(0.05), + } + + +@pytest.mark.parametrize( + ("stat_type", "targets"), + [ + (48, ["Physical Damage", "Special Damage"]), + (55, ["Health"]), + (56, ["Protection"]), + (57, ["Speed"]), + ], + ids=["offense%", "health%", "protection%", "speed%"], +) +def test_proportional_types_expand_onto_their_targets(calc: StatCalc, stat_type: int, targets: list[str]) -> None: + payload = player(character(), datacrons=[datacron(stat_affix(stat_type, 30_000_000))]) + + assert sorted(datacron_bucket(calc, payload)) == sorted(targets) + + +def test_a_percentage_resolves_against_base_and_gear_excluding_mods( + calc: StatCalc, example_player: dict[str, Any] +) -> None: + """As measured in game, percentages resolve against base + gear. + + Mods are excluded. Health is not converted for display, so `final` minus the + `mods` bucket is exactly that base. Measured against Lord Vader: a +27.14% + Protection datacron contributed 31,690 on a total of 208,666 carrying 91,901 + from mods — 27.14% of 116,765, not of 208,666. + """ + fraction = 0.25 + payload = copy.deepcopy(example_player) + payload["datacron"] = [datacron(stat_affix(55, int(fraction * 1e8)))] + + result = calc.calc_player_stats(payload, datacron_id=DATACRON_ID) + assert isinstance(result, dict) + + checked = with_mods = 0 + for unit in result["rosterUnit"]: + stats = unit.get("stats", {}) + bucket = stats.get("datacron") + if not bucket: + continue + + total = stats["final"]["Health"] + from_mods = stats.get("mods", {}).get("Health", 0) + unmodded = total - from_mods + assert unmodded > 0 + + # floor(..., 8) in Unscaled Space quantises to whole display units. + assert bucket["Health"] == pytest.approx(unmodded * fraction, abs=1.0) + if from_mods: + # Only modded units can tell the two candidate bases apart. + assert bucket["Health"] != pytest.approx(total * fraction, abs=1.0) + with_mods += 1 + checked += 1 + + assert checked > 100, "expected most of the roster to be covered" + assert with_mods > 100, "without modded units this proves nothing" + + +@pytest.mark.parametrize( + ("stat_type", "targets"), + [ + (42, ["Armor", "Resistance"]), + (49, ["Armor", "Resistance"]), + (53, ["Physical Critical Chance", "Special Critical Chance"]), + (54, ["Physical Critical Avoidance", "Special Critical Avoidance"]), + ], + ids=["defense flat", "defense%", "crit chance%", "crit avoidance%"], +) +def test_types_reaching_converted_stats_expand(calc: StatCalc, stat_type: int, targets: list[str]) -> None: + payload = player(character(), datacrons=[datacron(stat_affix(stat_type, 50_000_000))]) + + assert sorted(datacron_bucket(calc, payload)) == sorted(targets) + + +def test_expansion_and_passthrough_coexist(calc: StatCalc) -> None: + payload = player( + character(), + datacrons=[datacron(stat_affix(16, 40_000_000), stat_affix(57, 10_000_000))], + ) + bucket = datacron_bucket(calc, payload) + + assert bucket["Critical Damage"] == pytest.approx(0.4) + assert "Speed" in bucket + + +def test_gating_applies_before_expansion(calc: StatCalc) -> None: + """An affix the unit does not qualify for must not expand onto anything.""" + payload = player( + character(gear_tier=1, relic_tier=3), + datacrons=[datacron(stat_affix(48, 30_000_000, required_relic_tier=11))], + ) + + assert datacron_bucket(calc, payload) == {} + + +# ── Converted stats reconcile with final ────────────────────────────────── + + +def test_a_converted_stat_reconciles_against_an_independent_recomputation(calc: StatCalc) -> None: + """The promise of the feature: `final + datacron` is right for every stat. + + Armor is stored as a non-linear percentage, `v / (level*7.5 + v)`, so a + flat delta could not simply be added to it. The bucket must instead hold + the *marginal* percentage the datacron adds. + + The oracle here is independent of the datacron code: invert the published + conversion to recover the unit's flat armour, apply the percentage by hand, + convert forward again, and require the two buckets to sum to that. + """ + level = 85 + fraction = 0.5 + payload = player( + character(level=level), + datacrons=[datacron(stat_affix(49, int(fraction * 1e8)))], + ) + + result = calc.calc_player_stats(copy.deepcopy(payload), datacron_id=DATACRON_ID) + assert isinstance(result, dict) + stats = result["rosterUnit"][0]["stats"] + + level_effect = level * 7.5 + p0 = stats["final"]["Armor"] + assert 0 < p0 < 1 + + flat = level_effect * p0 / (1 - p0) + # Proportional growth is floored to whole display units in Unscaled Space. + grown = flat + math.floor(flat * fraction) + expected = grown / (level_effect + grown) + + assert p0 + stats["datacron"]["Armor"] == pytest.approx(expected, rel=1e-6) + + +def test_a_converted_stat_is_not_given_a_flat_delta(calc: StatCalc) -> None: + """Guard against the naive implementation: a flat armour delta would dwarf + the percentage it is meant to be added to.""" + payload = player(character(), datacrons=[datacron(stat_affix(49, 50_000_000))]) + + result = calc.calc_player_stats(copy.deepcopy(payload), datacron_id=DATACRON_ID) + assert isinstance(result, dict) + stats = result["rosterUnit"][0]["stats"] + + assert 0 < stats["datacron"]["Armor"] < 1 + assert 0 < stats["final"]["Armor"] + stats["datacron"]["Armor"] < 1 + + +def test_a_converted_stat_shows_diminishing_returns(calc: StatCalc) -> None: + """Non-linearity is applied, not decorative. + + The conversion is concave, so doubling an affix's value must yield *less* + than double the marginal contribution. A flat delta, or a percentage + applied linearly, would yield exactly double. + """ + + def marginal(value: int) -> float: + payload = player(character(), datacrons=[datacron(stat_affix(49, value))]) + result = calc.calc_player_stats(copy.deepcopy(payload), datacron_id=DATACRON_ID) + assert isinstance(result, dict) + return float(result["rosterUnit"][0]["stats"]["datacron"]["Armor"]) + + single = marginal(50_000_000) + double = marginal(100_000_000) + + assert single > 0 + assert single < double < 2 * single + + +def test_every_datacron_stat_has_a_matching_final_key(calc: StatCalc, example_player: dict[str, Any]) -> None: + """Across the whole roster and every expansion, the two buckets line up.""" + payload = copy.deepcopy(example_player) + payload["datacron"] = [ + datacron( + stat_affix(16, 20_000_000), + stat_affix(48, 30_000_000), + stat_affix(49, 30_000_000), + stat_affix(53, 10_000_000), + stat_affix(54, 10_000_000), + stat_affix(55, 20_000_000), + stat_affix(56, 20_000_000), + ) + ] + + result = calc.calc_player_stats(payload, datacron_id=DATACRON_ID) + assert isinstance(result, dict) + + checked = 0 + for unit in result["rosterUnit"]: + bucket = unit.get("stats", {}).get("datacron") + if not bucket: + continue + assert set(bucket) <= set(unit["stats"]["final"]) + checked += 1 + + assert checked > 100 + + +# ── Degenerate datacrons ────────────────────────────────────────────────── + + +def test_datacron_with_no_affixes_yields_an_empty_bucket(calc: StatCalc) -> None: + payload = player(character(), datacrons=[datacron()]) + + assert datacron_bucket(calc, payload) == {} + + +def test_partially_levelled_datacron_is_handled(calc: StatCalc) -> None: + """A three-affix datacron is as valid as a fifteen-affix one.""" + payload = player( + character(), + datacrons=[datacron(stat_affix(16, 10_000_000), stat_affix(17, 10_000_000), ability_affix())], + ) + + assert datacron_bucket(calc, payload) == { + "Critical Damage": pytest.approx(0.1), + "Potency": pytest.approx(0.1), + } + + +# ── Selection errors ────────────────────────────────────────────────────── + + +def test_unknown_datacron_id_raises(calc: StatCalc) -> None: + payload = player(character(), datacrons=[datacron(stat_affix(16, 10_000_000))]) + + with pytest.raises(KeyError, match="not among the player's"): + calc.calc_player_stats(payload, datacron_id="no-such-datacron") + + +def test_player_owning_no_datacrons_is_distinct_from_a_missing_collection(calc: StatCalc) -> None: + """An empty collection is a real state; a missing one is a malformed payload.""" + owns_none = player(character(), datacrons=[]) + with pytest.raises(KeyError, match="not among the player's"): + calc.calc_player_stats(owns_none, datacron_id=DATACRON_ID) + + malformed = player(character()) + del malformed["datacron"] + with pytest.raises(KeyError, match="no 'datacron' collection"): + calc.calc_player_stats(malformed, datacron_id=DATACRON_ID) + + +def test_a_missing_collection_is_ignored_when_no_datacron_is_requested(calc: StatCalc) -> None: + payload = player(character()) + del payload["datacron"] + + result = calc.calc_player_stats(payload) + assert isinstance(result, dict) + assert "datacron" not in result["rosterUnit"][0]["stats"] + + +# ── Ships ───────────────────────────────────────────────────────────────── + + +def test_ships_gain_no_bucket_and_their_stats_are_unchanged( + calc: StatCalc, example_player: dict[str, Any], game_data: dict[str, Any] +) -> None: + """Datacrons are a squad mechanic — no game mode applies one to a fleet.""" + owned = example_player["datacron"][0]["id"] + + without = calc.calc_player_stats(copy.deepcopy(example_player)) + with_dc = calc.calc_player_stats(copy.deepcopy(example_player), datacron_id=owned) + assert isinstance(without, dict) + assert isinstance(with_dc, dict) + + ships = { + unit["definitionId"].split(":")[0] + for unit in with_dc["rosterUnit"] + if game_data["unitData"].get(unit["definitionId"].split(":")[0], {}).get("combatType") == 2 + } + assert ships, "example player has no ships; this test would prove nothing" + + by_id = {unit["definitionId"]: unit for unit in without["rosterUnit"]} + for unit in with_dc["rosterUnit"]: + if unit["definitionId"].split(":")[0] not in ships: + continue + assert "datacron" not in unit["stats"] + assert unit["stats"] == by_id[unit["definitionId"]]["stats"] + + +def test_characters_crewing_a_ship_still_receive_their_own_bucket( + calc: StatCalc, example_player: dict[str, Any], game_data: dict[str, Any] +) -> None: + """Crew rating reads a unit's raw attributes, never its calculated stats, + so a crew member's bucket cannot leak into the ship it crews.""" + owned = example_player["datacron"][0]["id"] + + result = calc.calc_player_stats(copy.deepcopy(example_player), datacron_id=owned) + assert isinstance(result, dict) + + crewed = { + crew_id + for unit in result["rosterUnit"] + for crew_id in game_data["unitData"].get(unit["definitionId"].split(":")[0], {}).get("crew", []) + } + assert crewed, "example player has no crewed ships; this test would prove nothing" + + seen = [unit for unit in result["rosterUnit"] if unit["definitionId"].split(":")[0] in crewed and "stats" in unit] + assert seen, "no crew members in roster" + assert all("datacron" in unit["stats"] for unit in seen) diff --git a/tests/unit/test_statcalc_async.py b/tests/unit/test_statcalc_async.py index 551a80a..a91f1e3 100644 --- a/tests/unit/test_statcalc_async.py +++ b/tests/unit/test_statcalc_async.py @@ -120,6 +120,48 @@ async def test_acalc_ship_stats_matches_sync( assert await calc.acalc_ship_stats(copy.deepcopy(ship), copy.deepcopy(crew)) == expected +_DATACRON: dict[str, Any] = { + "id": "test-datacron", + "affix": [ + # Critical Damage +50%, open to every unit. + {"abilityId": "", "statType": 16, "statValue": "50000000", "requiredUnitTier": 0, "requiredRelicTier": 1}, + ], +} + + +def _with_datacron(player: dict[str, Any]) -> dict[str, Any]: + payload = copy.deepcopy(player) + payload["datacron"] = [copy.deepcopy(_DATACRON)] + return payload + + +async def test_acalc_player_stats_passes_the_datacron_id(calc: StatCalcAsync, player: dict[str, Any]) -> None: + expected = calc.calc_player_stats(_with_datacron(player), datacron_id="test-datacron") + + result = await calc.acalc_player_stats(_with_datacron(player), datacron_id="test-datacron") + + assert result == expected + assert isinstance(result, dict) + assert any(u.get("stats", {}).get("datacron") == {"Critical Damage": 0.5} for u in result["rosterUnit"]) + + +async def test_acalc_roster_stats_passes_the_datacron(calc: StatCalcAsync, player: dict[str, Any]) -> None: + expected = calc.calc_roster_stats(copy.deepcopy(player["rosterUnit"]), _DATACRON) + + assert await calc.acalc_roster_stats(copy.deepcopy(player["rosterUnit"]), _DATACRON) == expected + + +async def test_acalc_char_stats_passes_the_datacron( + calc: StatCalcAsync, player: dict[str, Any], game_data: dict[str, Any] +) -> None: + unit = next(u for u in player["rosterUnit"] if game_data["unitData"][_def_id(u)]["combatType"] == 1) + + result = await calc.acalc_char_stats(copy.deepcopy(unit), _DATACRON) + + assert result["stats"]["datacron"] == {"Critical Damage": 0.5} + assert result == calc.calc_char_stats(copy.deepcopy(unit), _DATACRON) + + async def test_acalc_errors_propagate(calc: StatCalcAsync) -> None: not_a_player: Any = "not a player" From c20165597fac4fb4402f3d9413c0b3a403c700e4 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Mon, 9 Nov 2026 13:58:18 -0500 Subject: [PATCH 2/3] test(statcalc): add the datacron golden fixture from in-game readings No reference calculator implements datacrons, so the parity suite cannot check them. The fixture records stat values read off the live game for a hand-authored unit under three datacrons and none, and the test asserts `final + datacron` against them at the precision the game displays. The readings are the measurement: when the implementation disagrees, the implementation changes. The fixture carries no account-identifying fields and the datacron ids are placeholders. Co-Authored-By: Claude Opus 5.5 --- tests/resources/datacron-golden.json | 919 +++++++++++++++++++++++++ tests/statcalc/test_datacron_golden.py | 119 ++++ 2 files changed, 1038 insertions(+) create mode 100644 tests/resources/datacron-golden.json create mode 100644 tests/statcalc/test_datacron_golden.py diff --git a/tests/resources/datacron-golden.json b/tests/resources/datacron-golden.json new file mode 100644 index 0000000..06262ef --- /dev/null +++ b/tests/resources/datacron-golden.json @@ -0,0 +1,919 @@ +{ + "_source": "Stat values read by hand off the live game on 2026-07-28 and typed in. They are the external ground truth for datacron calculation.", + "_warning": "DO NOT REGENERATE THIS FILE FROM StatCalc OUTPUT. Every other number this library produces is checked against the JavaScript reference calculator; datacrons cannot be, because no reference implements them. These readings are the only evidence the arithmetic is right. A fixture produced by the code it is meant to check proves nothing while looking exactly like proof. If a reading disagrees with the implementation, the implementation is what changes -- that has already happened twice: percentages resolve against base and gear, not mods, and apply as the two-decimal value the card displays.", + "_unit": "Hand-authored equivalent of a real roster entry: the gear tier, relic tier, mods and skills that determine the numbers, with every account-identifying field removed.", + "_precision": "Values are as the game displays them. Percent stats are recorded as percentages, at the number of decimals the game showed -- no reading may be asserted more precisely than it was displayed.", + "percent_stats": { + "Critical Damage": 2, + "Armor": 1 + }, + "unit": { + "definitionId": "LORDVADER:SEVEN_STAR", + "currentRarity": 7, + "currentLevel": 85, + "currentTier": 13, + "relic": { + "currentTier": 12 + }, + "equipment": [], + "purchasedAbilityId": [ + "ultimateability_lordvader" + ], + "skill": [ + { + "id": "basicskill_LORDVADER", + "tier": 1 + }, + { + "id": "uniqueskill_GALACTICLEGEND01", + "tier": 1 + }, + { + "id": "uniqueskill_LORDVADER01", + "tier": 1 + }, + { + "id": "leaderskill_LORDVADER", + "tier": 1 + }, + { + "id": "specialskill_LORDVADER02", + "tier": 1 + }, + { + "id": "specialskill_LORDVADER01", + "tier": 1 + } + ], + "equippedStatMod": [ + { + "secondaryStat": [ + { + "roll": [ + "0.18734", + "0.12766", + "0.14950", + "0.12557" + ], + "unscaledRollValue": [ + "1873", + "1277", + "1495", + "1256" + ], + "stat": { + "unitStatId": 55, + "statValueDecimal": "590", + "unscaledDecimalValue": "5901000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 4, + "statRollerBoundsMin": "1000", + "statRollerBoundsMax": "2000" + }, + { + "roll": [ + "0.17141", + "0.19955", + "0.19367", + "0.15874", + "0.18306" + ], + "unscaledRollValue": [ + "514230", + "598650", + "581010", + "476220", + "549180" + ], + "stat": { + "unitStatId": 5, + "statValueDecimal": "280000", + "unscaledDecimalValue": "2800000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 5, + "statRollerBoundsMin": "300000", + "statRollerBoundsMax": "600000" + }, + { + "roll": [ + "0.11907", + "0.17519" + ], + "unscaledRollValue": [ + "1786", + "2628" + ], + "stat": { + "unitStatId": 18, + "statValueDecimal": "441", + "unscaledDecimalValue": "4414000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 2, + "statRollerBoundsMin": "1500", + "statRollerBoundsMax": "3000" + }, + { + "roll": [ + "0.16441" + ], + "unscaledRollValue": [ + "2466" + ], + "stat": { + "unitStatId": 17, + "statValueDecimal": "246", + "unscaledDecimalValue": "2466000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 1, + "statRollerBoundsMin": "1500", + "statRollerBoundsMax": "3000" + } + ], + "level": 15, + "primaryStat": { + "roll": [], + "unscaledRollValue": [], + "stat": { + "unitStatId": 48, + "statValueDecimal": "850", + "unscaledDecimalValue": "8500000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 0, + "statRollerBoundsMin": "0", + "statRollerBoundsMax": "0" + }, + "definitionId": "461", + "tier": 5 + }, + { + "secondaryStat": [ + { + "roll": [ + "0.14159", + "0.10781" + ], + "unscaledRollValue": [ + "2124", + "1617" + ], + "stat": { + "unitStatId": 18, + "statValueDecimal": "374", + "unscaledDecimalValue": "3741000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 2, + "statRollerBoundsMin": "1500", + "statRollerBoundsMax": "3000" + }, + { + "roll": [ + "0.18124", + "0.11856", + "0.14520", + "0.17997", + "0.11070" + ], + "unscaledRollValue": [ + "543720", + "355680", + "435600", + "539910", + "332100" + ], + "stat": { + "unitStatId": 5, + "statValueDecimal": "230000", + "unscaledDecimalValue": "2300000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 5, + "statRollerBoundsMin": "300000", + "statRollerBoundsMax": "600000" + }, + { + "roll": [ + "0.11534", + "0.19033" + ], + "unscaledRollValue": [ + "2883500", + "4758250" + ], + "stat": { + "unitStatId": 41, + "statValueDecimal": "770000", + "unscaledDecimalValue": "7700000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 2, + "statRollerBoundsMin": "2500000", + "statRollerBoundsMax": "5000000" + }, + { + "roll": [ + "0.10581", + "0.17976", + "0.12210" + ], + "unscaledRollValue": [ + "1587", + "2696", + "1832" + ], + "stat": { + "unitStatId": 17, + "statValueDecimal": "611", + "unscaledDecimalValue": "6115000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 3, + "statRollerBoundsMin": "1500", + "statRollerBoundsMax": "3000" + } + ], + "level": 15, + "primaryStat": { + "roll": [], + "unscaledRollValue": [], + "stat": { + "unitStatId": 56, + "statValueDecimal": "2400", + "unscaledDecimalValue": "24000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 0, + "statRollerBoundsMin": "0", + "statRollerBoundsMax": "0" + }, + "definitionId": "462", + "tier": 5 + }, + { + "secondaryStat": [ + { + "roll": [ + "0.13568", + "0.13129", + "0.18039" + ], + "unscaledRollValue": [ + "62412800", + "60393400", + "82979400" + ], + "stat": { + "unitStatId": 28, + "statValueDecimal": "20570000", + "unscaledDecimalValue": "205700000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 3, + "statRollerBoundsMin": "46000000", + "statRollerBoundsMax": "92000000" + }, + { + "roll": [ + "0.10294", + "0.19986", + "0.19259", + "0.14617", + "0.15915" + ], + "unscaledRollValue": [ + "308820", + "599580", + "577770", + "438510", + "477450" + ], + "stat": { + "unitStatId": 5, + "statValueDecimal": "250000", + "unscaledDecimalValue": "2500000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 5, + "statRollerBoundsMin": "300000", + "statRollerBoundsMax": "600000" + }, + { + "roll": [ + "0.11087", + "0.11377" + ], + "unscaledRollValue": [ + "1663", + "1707" + ], + "stat": { + "unitStatId": 17, + "statValueDecimal": "337", + "unscaledDecimalValue": "3370000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 2, + "statRollerBoundsMin": "1500", + "statRollerBoundsMax": "3000" + }, + { + "roll": [ + "0.15034", + "0.11384" + ], + "unscaledRollValue": [ + "1278", + "968" + ], + "stat": { + "unitStatId": 48, + "statValueDecimal": "224", + "unscaledDecimalValue": "2246000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 2, + "statRollerBoundsMin": "850", + "statRollerBoundsMax": "1700" + } + ], + "level": 15, + "primaryStat": { + "roll": [], + "unscaledRollValue": [], + "stat": { + "unitStatId": 49, + "statValueDecimal": "2000", + "unscaledDecimalValue": "20000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 0, + "statRollerBoundsMin": "0", + "statRollerBoundsMax": "0" + }, + "definitionId": "163", + "tier": 5 + }, + { + "secondaryStat": [ + { + "roll": [ + "0.16206", + "0.16759" + ], + "unscaledRollValue": [ + "2431", + "2514" + ], + "stat": { + "unitStatId": 56, + "statValueDecimal": "494", + "unscaledDecimalValue": "4945000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 2, + "statRollerBoundsMin": "1500", + "statRollerBoundsMax": "3000" + }, + { + "roll": [ + "0.18997", + "0.19266", + "0.17079", + "0.16452", + "0.15041" + ], + "unscaledRollValue": [ + "569910", + "577980", + "512370", + "493560", + "451230" + ], + "stat": { + "unitStatId": 5, + "statValueDecimal": "270000", + "unscaledDecimalValue": "2700000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 5, + "statRollerBoundsMin": "300000", + "statRollerBoundsMax": "600000" + }, + { + "roll": [ + "0.17466", + "0.18903", + "0.15058" + ], + "unscaledRollValue": [ + "2052", + "2221", + "1769" + ], + "stat": { + "unitStatId": 53, + "statValueDecimal": "604", + "unscaledDecimalValue": "6043000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 3, + "statRollerBoundsMin": "1175", + "statRollerBoundsMax": "2350" + }, + { + "roll": [ + "0.16731", + "0.10734" + ], + "unscaledRollValue": [ + "1673", + "1073" + ], + "stat": { + "unitStatId": 55, + "statValueDecimal": "274", + "unscaledDecimalValue": "2747000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 2, + "statRollerBoundsMin": "1000", + "statRollerBoundsMax": "2000" + } + ], + "level": 15, + "primaryStat": { + "roll": [], + "unscaledRollValue": [], + "stat": { + "unitStatId": 16, + "statValueDecimal": "4200", + "unscaledDecimalValue": "42000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 0, + "statRollerBoundsMin": "0", + "statRollerBoundsMax": "0" + }, + "definitionId": "164", + "tier": 5 + }, + { + "secondaryStat": [ + { + "roll": [ + "0.15387", + "0.17441", + "0.17100" + ], + "unscaledRollValue": [ + "2308", + "2616", + "2565" + ], + "stat": { + "unitStatId": 17, + "statValueDecimal": "748", + "unscaledDecimalValue": "7489000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 3, + "statRollerBoundsMin": "1500", + "statRollerBoundsMax": "3000" + }, + { + "roll": [ + "0.19423", + "0.18788", + "0.13273", + "0.19407", + "0.16928" + ], + "unscaledRollValue": [ + "582690", + "563640", + "398190", + "582210", + "507840" + ], + "stat": { + "unitStatId": 5, + "statValueDecimal": "270000", + "unscaledDecimalValue": "2700000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 5, + "statRollerBoundsMin": "300000", + "statRollerBoundsMax": "600000" + }, + { + "roll": [ + "0.12147", + "0.15623" + ], + "unscaledRollValue": [ + "1032", + "1328" + ], + "stat": { + "unitStatId": 48, + "statValueDecimal": "236", + "unscaledDecimalValue": "2360000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 2, + "statRollerBoundsMin": "850", + "statRollerBoundsMax": "1700" + }, + { + "roll": [ + "0.18987", + "0.19711" + ], + "unscaledRollValue": [ + "2848", + "2957" + ], + "stat": { + "unitStatId": 18, + "statValueDecimal": "580", + "unscaledDecimalValue": "5805000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 2, + "statRollerBoundsMin": "1500", + "statRollerBoundsMax": "3000" + } + ], + "level": 15, + "primaryStat": { + "roll": [], + "unscaledRollValue": [], + "stat": { + "unitStatId": 56, + "statValueDecimal": "2400", + "unscaledDecimalValue": "24000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 0, + "statRollerBoundsMin": "0", + "statRollerBoundsMax": "0" + }, + "definitionId": "465", + "tier": 5 + }, + { + "secondaryStat": [ + { + "roll": [ + "0.11440" + ], + "unscaledRollValue": [ + "915200" + ], + "stat": { + "unitStatId": 42, + "statValueDecimal": "90000", + "unscaledDecimalValue": "900000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 1, + "statRollerBoundsMin": "800000", + "statRollerBoundsMax": "1600000" + }, + { + "roll": [ + "0.14294", + "0.14832", + "0.15828", + "0.17381" + ], + "unscaledRollValue": [ + "2144", + "2225", + "2374", + "2607" + ], + "stat": { + "unitStatId": 17, + "statValueDecimal": "935", + "unscaledDecimalValue": "9350000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 4, + "statRollerBoundsMin": "1500", + "statRollerBoundsMax": "3000" + }, + { + "roll": [ + "0.15574", + "0.18536", + "0.19249", + "0.17482", + "0.17265" + ], + "unscaledRollValue": [ + "467220", + "556080", + "577470", + "524460", + "517950" + ], + "stat": { + "unitStatId": 5, + "statValueDecimal": "270000", + "unscaledDecimalValue": "2700000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 5, + "statRollerBoundsMin": "300000", + "statRollerBoundsMax": "600000" + }, + { + "roll": [ + "0.11378", + "0.19939" + ], + "unscaledRollValue": [ + "1337", + "2343" + ], + "stat": { + "unitStatId": 53, + "statValueDecimal": "368", + "unscaledDecimalValue": "3680000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 2, + "statRollerBoundsMin": "1175", + "statRollerBoundsMax": "2350" + } + ], + "level": 15, + "primaryStat": { + "roll": [], + "unscaledRollValue": [], + "stat": { + "unitStatId": 56, + "statValueDecimal": "2400", + "unscaledDecimalValue": "24000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 0, + "statRollerBoundsMin": "0", + "statRollerBoundsMax": "0" + }, + "definitionId": "466", + "tier": 5 + } + ] + }, + "datacrons": [ + { + "id": "datacron-a", + "setId": 32, + "templateId": "datacron_set_32_base", + "affix": [ + { + "requiredUnitTier": 2, + "statType": 16, + "abilityId": "", + "requiredRelicTier": 1, + "statValue": "17443980" + }, + { + "requiredUnitTier": 2, + "statType": 48, + "abilityId": "", + "requiredRelicTier": 1, + "statValue": "2828575" + }, + { + "requiredUnitTier": 2, + "statType": 1, + "abilityId": "datacron_faction_generic_043", + "requiredRelicTier": 1, + "statValue": "0" + }, + { + "requiredUnitTier": 4, + "statType": 16, + "abilityId": "", + "requiredRelicTier": 1, + "statValue": "34405787" + }, + { + "requiredUnitTier": 4, + "statType": 16, + "abilityId": "", + "requiredRelicTier": 1, + "statValue": "33342140" + }, + { + "requiredUnitTier": 0, + "statType": 1, + "abilityId": "datacron_faction_generic_007", + "requiredRelicTier": 6, + "statValue": "0" + }, + { + "requiredUnitTier": 0, + "statType": 48, + "abilityId": "", + "requiredRelicTier": 8, + "statValue": "19515055" + }, + { + "requiredUnitTier": 0, + "statType": 56, + "abilityId": "", + "requiredRelicTier": 8, + "statValue": "27143270" + }, + { + "requiredUnitTier": 0, + "statType": 1, + "abilityId": "datacron_character_talia_001", + "requiredRelicTier": 8, + "statValue": "0" + } + ] + }, + { + "id": "datacron-b", + "setId": 32, + "templateId": "datacron_set_32_base", + "affix": [ + { + "requiredUnitTier": 2, + "statType": 56, + "abilityId": "", + "requiredRelicTier": 1, + "statValue": "8305491" + }, + { + "requiredUnitTier": 2, + "statType": 55, + "abilityId": "", + "requiredRelicTier": 1, + "statValue": "6086343" + }, + { + "requiredUnitTier": 2, + "statType": 1, + "abilityId": "datacron_faction_generic_023", + "requiredRelicTier": 1, + "statValue": "0" + } + ] + }, + { + "id": "datacron-c", + "setId": 31, + "templateId": "datacron_set_31_base", + "affix": [ + { + "requiredUnitTier": 2, + "statType": 17, + "abilityId": "", + "requiredRelicTier": 1, + "statValue": "26721944" + }, + { + "requiredUnitTier": 2, + "statType": 48, + "abilityId": "", + "requiredRelicTier": 1, + "statValue": "3674536" + }, + { + "requiredUnitTier": 2, + "statType": 1, + "abilityId": "datacron_alignment_generic_003", + "requiredRelicTier": 1, + "statValue": "0" + }, + { + "requiredUnitTier": 4, + "statType": 56, + "abilityId": "", + "requiredRelicTier": 1, + "statValue": "11645456" + }, + { + "requiredUnitTier": 4, + "statType": 48, + "abilityId": "", + "requiredRelicTier": 1, + "statValue": "9803783" + }, + { + "requiredUnitTier": 0, + "statType": 1, + "abilityId": "datacron_faction_separatist_002", + "requiredRelicTier": 6, + "statValue": "0" + }, + { + "requiredUnitTier": 0, + "statType": 48, + "abilityId": "", + "requiredRelicTier": 8, + "statValue": "11348363" + }, + { + "requiredUnitTier": 0, + "statType": 16, + "abilityId": "", + "requiredRelicTier": 8, + "statValue": "36362478" + }, + { + "requiredUnitTier": 0, + "statType": 1, + "abilityId": "datacron_character_trench_001", + "requiredRelicTier": 8, + "statValue": "0" + } + ] + } + ], + "readings": [ + { + "datacron": null, + "asserted": true, + "stats": { + "Health": 124335, + "Protection": 208666, + "Speed": 586, + "Physical Damage": 11004, + "Critical Damage": 192.0, + "Armor": 56.1 + } + }, + { + "datacron": "datacron-a", + "asserted": true, + "stats": { + "Health": 124335, + "Protection": 240356, + "Speed": 586, + "Physical Damage": 13162, + "Critical Damage": 277.19, + "Armor": 56.1 + } + }, + { + "datacron": "datacron-c", + "asserted": true, + "note": "Screenshot cropped to Health and Protection; nothing else was read.", + "stats": { + "Health": 124335, + "Protection": 222269 + } + }, + { + "datacron": "datacron-b", + "asserted": false, + "note": "Recorded but not asserted. This capture is the only one whose mod contribution displayed one higher on both stats -- 91902 and 19542, against 91901 and 19541 in every other reading -- so the unit was not in the same state. Reconstructing its baseline from its own mods figure gives base+gear identical to the other readings and reproduces both totals exactly, so it corroborates the displayed-percentage rule rather than contradicting it. Kept here so the data is visible and the reason for excluding it is on the record.", + "stats": { + "Health": 130717, + "Protection": 218370 + } + } + ] +} diff --git a/tests/statcalc/test_datacron_golden.py b/tests/statcalc/test_datacron_golden.py new file mode 100644 index 0000000..0556af7 --- /dev/null +++ b/tests/statcalc/test_datacron_golden.py @@ -0,0 +1,119 @@ +"""Datacron output against stat values read by hand off the live game. + +This is the only evidence that datacron arithmetic is correct. Every other +number `StatCalc` produces is diffed against the JavaScript reference +calculator; datacrons cannot be, because no reference implements them and the +stats service does not calculate them either. + +If a test here fails, the implementation is what changes -- not the fixture. +The fixture is a measurement. It has already overturned the implementation +twice: percentages resolve against base and gear, not base, gear and mods; and +the two-decimal percentage the card shows is what gets applied, summed before +it is rounded. + +Unlike the parity suite this runs by default and needs nothing external -- the +readings are committed. Putting it behind a marker would leave the feature's +only correctness guard skipped in normal runs. +""" + +from __future__ import annotations + +import copy +import json +from pathlib import Path +from typing import Any + +import pytest + +from swgoh_comlink import StatCalc + +_RESOURCES = Path(__file__).resolve().parent.parent / "resources" +_GAME_DATA_FILE = _RESOURCES / "gameData.json" +_GOLDEN_FILE = _RESOURCES / "datacron-golden.json" + +# Loaded at import so every asserted reading becomes its own test case, named +# for the datacron it came from. +_GOLDEN: dict[str, Any] = json.loads(_GOLDEN_FILE.read_text()) +_ASSERTED: list[dict[str, Any]] = [r for r in _GOLDEN["readings"] if r["asserted"]] + + +@pytest.fixture(scope="module") +def golden() -> dict[str, Any]: + return json.loads(_GOLDEN_FILE.read_text()) + + +@pytest.fixture(scope="module") +def calc() -> StatCalc: + return StatCalc(game_data=json.loads(_GAME_DATA_FILE.read_text())["data"]) + + +def _asserted(golden: dict[str, Any]) -> list[dict[str, Any]]: + return [r for r in golden["readings"] if r["asserted"]] + + +def _observed(calc: StatCalc, golden: dict[str, Any], datacron_id: str | None) -> dict[str, float]: + """Run the hand-authored unit and return `final + datacron` per stat.""" + payload = { + "rosterUnit": [copy.deepcopy(golden["unit"])], + "datacron": copy.deepcopy(golden["datacrons"]), + } + result = calc.calc_player_stats(payload, datacron_id=datacron_id) + assert isinstance(result, dict) + stats = result["rosterUnit"][0]["stats"] + combined = dict(stats["final"]) + for name, value in stats.get("datacron", {}).items(): + combined[name] = combined.get(name, 0) + value + return combined + + +def _as_displayed(name: str, value: float, percent_stats: dict[str, int]) -> float: + """Express a computed stat the way the game printed it. + + A reading cannot be checked more precisely than it was displayed. + """ + if name in percent_stats: + return round(value * 100, percent_stats[name]) + return round(value) + + +@pytest.mark.parametrize( + "reading", + _ASSERTED, + ids=[r["datacron"] or "no-datacron" for r in _ASSERTED], +) +def test_matches_values_read_from_the_game(calc: StatCalc, golden: dict[str, Any], reading: dict[str, Any]) -> None: + combined = _observed(calc, golden, reading["datacron"]) + percent_stats = golden["percent_stats"] + + for name, expected in reading["stats"].items(): + assert name in combined, f"{name} missing from calculated output" + assert _as_displayed(name, combined[name], percent_stats) == expected, ( + f"datacron={reading['datacron']} stat={name}: " + f"calculated {combined[name]!r} does not match the value read in game. " + f"Fix the implementation, not this fixture." + ) + + +def test_every_asserted_reading_is_exercised(golden: dict[str, Any]) -> None: + """Guards the parametrisation above from silently covering fewer readings.""" + assert len(_asserted(golden)) == 3 + + +def test_unasserted_readings_carry_their_reason(golden: dict[str, Any]) -> None: + """A reading may be excluded, but never silently.""" + for reading in golden["readings"]: + if not reading["asserted"]: + assert reading.get("note"), "an unasserted reading must say why" + + +def test_fixture_warns_against_regeneration(golden: dict[str, Any]) -> None: + """The warning is the fixture's only defence against being 'refreshed'.""" + assert "DO NOT REGENERATE" in golden["_warning"] + + +def test_the_unit_carries_no_account_identifying_fields(golden: dict[str, Any]) -> None: + """The unit is a hand-authored equivalent, not a copied roster entry.""" + unit = golden["unit"] + assert not {"id", "currentXp", "unitStat", "promotionRecipeReference"} & set(unit) + for mod in unit["equippedStatMod"]: + assert "id" not in mod From c213f68a248b9b540b3eaffa545914f4d2dd8f5d Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Mon, 9 Nov 2026 13:58:20 -0500 Subject: [PATCH 3/3] docs(examples): add sync and async datacron calculation examples Walks through applying a datacron, combining it with `final`, affix requirements across units, comparing datacrons, ships being unaffected, and applying one of a real player's datacrons fetched from Comlink. Co-Authored-By: Claude Opus 5.5 --- examples/Async/README.md | 1 + examples/Async/calc_datacron_stats.py | 237 ++++++++++++++++++++++++++ examples/Sync/README.md | 1 + examples/Sync/calc_datacron_stats.py | 235 +++++++++++++++++++++++++ 4 files changed, 474 insertions(+) create mode 100644 examples/Async/calc_datacron_stats.py create mode 100644 examples/Sync/calc_datacron_stats.py diff --git a/examples/Async/README.md b/examples/Async/README.md index 7a07a92..3d4c278 100644 --- a/examples/Async/README.md +++ b/examples/Async/README.md @@ -6,6 +6,7 @@ These examples use the `SwgohComlinkAsync` async client. All methods must be `aw | File | Description | |------|-------------| +| `calc_datacron_stats.py` | Apply a datacron to a roster and combine it with `final` stats | | `calc_stats_local.py` | Calculate character stats locally using `StatCalcAsync` | | `get_events.py` | Retrieve current game events with timestamps and status | | `get_gac_brackets.py` | Scan GAC brackets for a league and search for a player (parallel batches) | diff --git a/examples/Async/calc_datacron_stats.py b/examples/Async/calc_datacron_stats.py new file mode 100644 index 0000000..4a165b8 --- /dev/null +++ b/examples/Async/calc_datacron_stats.py @@ -0,0 +1,237 @@ +""" +calc_datacron_stats.py +Applying a datacron to a roster with async StatCalcAsync support. + +A datacron is never equipped to a unit — a player owns dozens and picks one per +squad when they deploy. So there is no such thing as "this unit's stats with +datacrons", only "this unit's stats given *this* datacron". You name the one you +mean; the library never chooses. + +`create()` fetches game data without blocking the event loop, and each +`acalc_*` method runs the matching `calc_*` method in a worker thread, so a +large roster does not stall the loop either. They take the same datacron +arguments as their synchronous counterparts. + +Demonstrates: + 1. Applying a datacron and reading its contribution + 2. Combining `final` and `datacron` to get battle-ready stats + 3. Affix requirements — the same datacron gives different units different amounts + 4. Comparing several datacrons for one unit + 5. Ships, which datacrons never touch + 6. Doing the same against a real player from a running Comlink service + +Examples 1 to 5 use a hand-authored roster and need only game data, which is +fetched from GitHub. Example 6 needs a running Comlink service. + +See the Sync example for the same walkthrough without the event loop. +""" + +import asyncio + +from swgoh_comlink import StatCalcAsync, SwgohComlinkAsync + +# ── A datacron, shaped as the game reports one ──────────────────────────── +# +# Affixes come in threes. Every third one grants an *ability* rather than a +# stat — it reports stat type 1 with value 0 and names a targeting rule. Those +# contribute nothing to stats and StatCalc skips them. +# +# `requiredUnitTier` is a gear tier and `requiredRelicTier` a relic tier. Both +# are compared directly against the unit. Note relic tiers are encoded with +# their locked and unlocked base states occupying the first two values, so a +# `requiredRelicTier` of 8 means relic 6 as a player would count it. +# +# Values are fixed point, where 1e8 is 100%. 27143270 is 27.14327%. + + +def stat_affix(stat_type, value, unit_tier=0, relic_tier=1): + return { + "statType": stat_type, + "statValue": str(value), + "requiredUnitTier": unit_tier, + "requiredRelicTier": relic_tier, + "abilityId": "", + "targetRule": "", + } + + +def ability_affix(ability_id, unit_tier=0, relic_tier=1): + return { + "statType": 1, + "statValue": "0", + "requiredUnitTier": unit_tier, + "requiredRelicTier": relic_tier, + "abilityId": ability_id, + "targetRule": "target_datacron_darkside", + } + + +# Stat types: 16 Critical Damage, 48 Offense%, 55 Health%, 56 Protection% +maxed_datacron = { + "id": "maxed", + "affix": [ + stat_affix(16, 17_443_980, unit_tier=2), + stat_affix(48, 2_828_575, unit_tier=2), + ability_affix("datacron_faction_generic_043", unit_tier=2), + stat_affix(16, 34_405_787, unit_tier=4), + stat_affix(16, 33_342_140, unit_tier=4), + ability_affix("datacron_faction_generic_007", relic_tier=6), + stat_affix(48, 19_515_055, relic_tier=8), + stat_affix(56, 27_143_270, relic_tier=8), + ability_affix("datacron_character_talia_001", relic_tier=8), + ], +} + +starter_datacron = { + "id": "starter", + "affix": [ + stat_affix(56, 8_305_491, unit_tier=2), + stat_affix(55, 6_086_343, unit_tier=2), + ability_affix("datacron_faction_generic_023", unit_tier=2), + ], +} + + +def character(def_id, gear_tier=13, relic_tier=12): + """A roster unit. `relic_tier=None` gives a unit with no relic at all.""" + return { + "definitionId": f"{def_id}:SEVEN_STAR", + "currentRarity": 7, + "currentLevel": 85, + "currentTier": gear_tier, + "equipment": [], + "skill": [], + "equippedStatMod": [], + "relic": None if relic_tier is None else {"currentTier": relic_tier}, + } + + +def show(value): + """Percentage stats come back as fractions; flat stats as whole numbers.""" + return f"{value:,.0f}" if abs(value) >= 100 else f"{value:.4f}" + + +async def main(): + calc = await StatCalcAsync.create() # fetches game data from GitHub + + # ── Example 1: apply a datacron and read its contribution ───────────── + + player = { + "rosterUnit": [character("CADBANE")], + "datacron": [maxed_datacron, starter_datacron], + } + + await calc.acalc_player_stats(player, datacron_id="maxed") + stats = player["rosterUnit"][0]["stats"] + + print("=== Example 1: what the datacron adds ===") + for name, amount in sorted(stats["datacron"].items()): + print(f" {name:<20} +{show(amount)}") + + # Ask for nothing and nothing changes — no `datacron` key appears at all. + untouched = {"rosterUnit": [character("CADBANE")], "datacron": []} + await calc.acalc_player_stats(untouched) + print("\n bucket present when no datacron requested:", "datacron" in untouched["rosterUnit"][0]["stats"]) + + # ── Example 2: combining the buckets ────────────────────────────────── + # + # The `datacron` bucket sits *beside* `final`, never inside it. A datacron + # is a hypothetical you supplied, so folding it into `final` would make that + # field mean different things depending on an argument. Add them yourself: + + combined = {name: value + stats["datacron"].get(name, 0) for name, value in stats["final"].items()} + + print("\n=== Example 2: final + datacron ===") + for name in ("Protection", "Physical Damage", "Critical Damage", "Health"): + before, after = stats["final"][name], combined[name] + moved = "" if before == after else " <- moved" + print(f" {name:<18} {show(before):>10} -> {show(after):>10}{moved}") + + # Health is untouched because this datacron carries no Health affix. That is + # the normal case: a datacron moves a handful of stats, not all of them. + # + # The addition is correct for *every* stat, including ones reported as + # percentages such as Armor. Those are stored non-linearly, so a raw + # percentage could not simply be added — the bucket holds the marginal + # amount the datacron actually contributes on top of everything else. + + # ── Example 3: affix requirements ───────────────────────────────────── + + squad = { + "rosterUnit": [ + character("CADBANE", gear_tier=13, relic_tier=12), # relic 10 — clears everything + character("BOSSK", gear_tier=13, relic_tier=7), # relic 5 — below the relic-8 affixes + character("JAWA", gear_tier=1, relic_tier=None), # no relic — clears nothing + ], + "datacron": [maxed_datacron], + } + await calc.acalc_player_stats(squad, datacron_id="maxed") + + print("\n=== Example 3: the same datacron, three units ===") + for unit in squad["rosterUnit"]: + name = unit["definitionId"].split(":")[0] + relic = (unit["relic"] or {}).get("currentTier", 1) + granted = sorted(unit["stats"]["datacron"]) or ["nothing"] + print(f" {name:<9} gear {unit['currentTier']:<3} relic {relic:<3} -> {', '.join(granted)}") + + # BOSSK sits below the relic requirement on two affixes, so he gets strictly + # less than CADBANE from the very same datacron. JAWA qualifies for nothing. + + # ── Example 4: comparing datacrons ──────────────────────────────────── + # + # The library never picks for you, so comparing means asking twice. + + print("\n=== Example 4: which datacron suits this unit? ===") + for datacron_id in ("maxed", "starter"): + candidate = {"rosterUnit": [character("CADBANE")], "datacron": [maxed_datacron, starter_datacron]} + await calc.acalc_player_stats(candidate, datacron_id=datacron_id) + bucket = candidate["rosterUnit"][0]["stats"]["datacron"] + protection = bucket.get("Protection", 0) + damage = bucket.get("Physical Damage", 0) + print(f" {datacron_id:<9} Protection +{protection:<10,.0f} Physical Damage +{damage:,.0f}") + + # ── Example 5: ships ────────────────────────────────────────────────── + # + # Datacrons are a squad mechanic. No game mode applies one to a fleet + # battle, so ships receive no bucket and their stats are untouched. + + fleet = { + "rosterUnit": [character("CADBANE"), character("VULTUREDROID")], # a crewless ship + "datacron": [maxed_datacron], + } + await calc.acalc_player_stats(fleet, datacron_id="maxed") + + print("\n=== Example 5: ships are never affected ===") + for unit in fleet["rosterUnit"]: + name = unit["definitionId"].split(":")[0] + print(f" {name:<14} datacron bucket: {'datacron' in unit['stats']}") + + # ── Example 6: a real player ────────────────────────────────────────── + # + # Requires a running Comlink service. The datacron id comes from the + # player's own collection, which is why this entry point takes an id rather + # than an object — `acalc_roster_stats` and `acalc_char_stats` take the + # object, having no player to look it up in. Naming a datacron the player + # does not own raises KeyError, so a mistyped id fails loudly rather than + # silently adding nothing. + + async with SwgohComlinkAsync() as comlink: + real_player = await comlink.get_player(allycode=314927874) + + print("\n=== Example 6: a real player ===") + if not real_player.get("datacron"): + print(" this player owns no datacrons") + return + + chosen = real_player["datacron"][0] + await calc.acalc_player_stats(real_player, datacron_id=chosen["id"]) + + affected = [unit for unit in real_player["rosterUnit"] if unit.get("stats", {}).get("datacron")] + print(f" {chosen['templateId']} adds stats to {len(affected)} of {len(real_player['rosterUnit'])} units") + for unit in affected[:3]: + name = unit["definitionId"].split(":")[0] + added = ", ".join(f"{stat} +{show(amount)}" for stat, amount in sorted(unit["stats"]["datacron"].items())) + print(f" {name:<20} {added}") + + +asyncio.run(main()) diff --git a/examples/Sync/README.md b/examples/Sync/README.md index a5060ed..454bc9d 100644 --- a/examples/Sync/README.md +++ b/examples/Sync/README.md @@ -6,6 +6,7 @@ These examples use the `SwgohComlink` synchronous client. They run in a standard | File | Description | |------|-------------| +| `calc_datacron_stats.py` | Apply a datacron to a roster and combine it with `final` stats | | `calc_stats_local.py` | Calculate character stats locally using the `StatCalc` module | | `get_events.py` | Retrieve current game events with timestamps and status | | `get_gac_brackets.py` | Scan GAC brackets for a league and search for a player | diff --git a/examples/Sync/calc_datacron_stats.py b/examples/Sync/calc_datacron_stats.py new file mode 100644 index 0000000..a8e5c37 --- /dev/null +++ b/examples/Sync/calc_datacron_stats.py @@ -0,0 +1,235 @@ +""" +calc_datacron_stats.py +Applying a datacron to a roster with local StatCalc support. + +A datacron is never equipped to a unit — a player owns dozens and picks one per +squad when they deploy. So there is no such thing as "this unit's stats with +datacrons", only "this unit's stats given *this* datacron". You name the one you +mean; the library never chooses. + +Demonstrates: + 1. Applying a datacron and reading its contribution + 2. Combining `final` and `datacron` to get battle-ready stats + 3. Affix requirements — the same datacron gives different units different amounts + 4. Comparing several datacrons for one unit + 5. Ships, which datacrons never touch + 6. Doing the same against a real player from a running Comlink service + +Examples 1 to 5 use a hand-authored roster and need only game data, which is +fetched from GitHub. Example 6 needs a running Comlink service. +""" + +from swgoh_comlink import StatCalc, SwgohComlink + +# ── A datacron, shaped as the game reports one ──────────────────────────── +# +# Affixes come in threes. Every third one grants an *ability* rather than a +# stat — it reports stat type 1 with value 0 and names a targeting rule. Those +# contribute nothing to stats and StatCalc skips them. +# +# `requiredUnitTier` is a gear tier and `requiredRelicTier` a relic tier. Both +# are compared directly against the unit. Note relic tiers are encoded with +# their locked and unlocked base states occupying the first two values, so a +# `requiredRelicTier` of 8 means relic 6 as a player would count it. +# +# Values are fixed point, where 1e8 is 100%. 27143270 is 27.14327%. + + +def stat_affix(stat_type, value, unit_tier=0, relic_tier=1): + return { + "statType": stat_type, + "statValue": str(value), + "requiredUnitTier": unit_tier, + "requiredRelicTier": relic_tier, + "abilityId": "", + "targetRule": "", + } + + +def ability_affix(ability_id, unit_tier=0, relic_tier=1): + return { + "statType": 1, + "statValue": "0", + "requiredUnitTier": unit_tier, + "requiredRelicTier": relic_tier, + "abilityId": ability_id, + "targetRule": "target_datacron_darkside", + } + + +# Stat types: 16 Critical Damage, 48 Offense%, 56 Protection% +maxed_datacron = { + "id": "maxed", + "affix": [ + stat_affix(16, 17_443_980, unit_tier=2), + stat_affix(48, 2_828_575, unit_tier=2), + ability_affix("datacron_faction_generic_043", unit_tier=2), + stat_affix(16, 34_405_787, unit_tier=4), + stat_affix(16, 33_342_140, unit_tier=4), + ability_affix("datacron_faction_generic_007", relic_tier=6), + stat_affix(48, 19_515_055, relic_tier=8), + stat_affix(56, 27_143_270, relic_tier=8), + ability_affix("datacron_character_talia_001", relic_tier=8), + ], +} + +# A shorter one, for the comparison in Example 4. +starter_datacron = { + "id": "starter", + "affix": [ + stat_affix(56, 8_305_491, unit_tier=2), + stat_affix(55, 6_086_343, unit_tier=2), + ability_affix("datacron_faction_generic_023", unit_tier=2), + ], +} + + +def character(def_id, gear_tier=13, relic_tier=12): + """A roster unit. `relic_tier=None` gives a unit with no relic at all.""" + return { + "definitionId": f"{def_id}:SEVEN_STAR", + "currentRarity": 7, + "currentLevel": 85, + "currentTier": gear_tier, + "equipment": [], + "skill": [], + "equippedStatMod": [], + "relic": None if relic_tier is None else {"currentTier": relic_tier}, + } + + +calc = StatCalc() # fetches game data from GitHub on init + + +# ── Example 1: apply a datacron and read its contribution ───────────────── + +player = { + "rosterUnit": [character("CADBANE")], + "datacron": [maxed_datacron, starter_datacron], +} + +calc.calc_player_stats(player, datacron_id="maxed") +stats = player["rosterUnit"][0]["stats"] + + +def show(value): + """Percentage stats come back as fractions; flat stats as whole numbers.""" + return f"{value:,.0f}" if abs(value) >= 100 else f"{value:.4f}" + + +print("=== Example 1: what the datacron adds ===") +for name, amount in sorted(stats["datacron"].items()): + print(f" {name:<20} +{show(amount)}") + +# Ask for nothing and nothing changes — no `datacron` key appears at all. +untouched = {"rosterUnit": [character("CADBANE")], "datacron": []} +calc.calc_player_stats(untouched) +print("\n bucket present when no datacron requested:", "datacron" in untouched["rosterUnit"][0]["stats"]) + + +# ── Example 2: combining the buckets ────────────────────────────────────── +# +# The `datacron` bucket sits *beside* `final`, never inside it. A datacron is a +# hypothetical you supplied, so folding it into `final` would make that field +# mean different things depending on an argument. Add them yourself: + +combined = {name: value + stats["datacron"].get(name, 0) for name, value in stats["final"].items()} + + +print("\n=== Example 2: final + datacron ===") +for name in ("Protection", "Physical Damage", "Critical Damage", "Health"): + before, after = stats["final"][name], combined[name] + moved = "" if before == after else " <- moved" + print(f" {name:<18} {show(before):>10} -> {show(after):>10}{moved}") + +# Health is untouched because this datacron carries no Health affix. That is +# the normal case: a datacron moves a handful of stats, not all of them. +# +# The addition is correct for *every* stat, including ones reported as +# percentages such as Armor. Those are stored non-linearly, so a raw percentage +# could not simply be added — the bucket holds the marginal amount the datacron +# actually contributes on top of everything else. + + +# ── Example 3: affix requirements ───────────────────────────────────────── +# +# Each affix names a gear tier and a relic tier the unit must reach. One +# datacron therefore contributes differently across a roster. + +squad = { + "rosterUnit": [ + character("CADBANE", gear_tier=13, relic_tier=12), # relic 10 — clears everything + character("BOSSK", gear_tier=13, relic_tier=7), # relic 5 — below the relic-8 affixes + character("JAWA", gear_tier=1, relic_tier=None), # no relic — clears nothing + ], + "datacron": [maxed_datacron], +} +calc.calc_player_stats(squad, datacron_id="maxed") + +print("\n=== Example 3: the same datacron, three units ===") +for unit in squad["rosterUnit"]: + name = unit["definitionId"].split(":")[0] + relic = (unit["relic"] or {}).get("currentTier", 1) + granted = sorted(unit["stats"]["datacron"]) or ["nothing"] + print(f" {name:<9} gear {unit['currentTier']:<3} relic {relic:<3} -> {', '.join(granted)}") + +# BOSSK sits below the relic requirement on two affixes, so he gets strictly +# less than CADBANE from the very same datacron. JAWA qualifies for nothing. + + +# ── Example 4: comparing datacrons ──────────────────────────────────────── +# +# The library never picks for you, so comparing means asking twice. + +print("\n=== Example 4: which datacron suits this unit? ===") +for datacron_id in ("maxed", "starter"): + candidate = {"rosterUnit": [character("CADBANE")], "datacron": [maxed_datacron, starter_datacron]} + calc.calc_player_stats(candidate, datacron_id=datacron_id) + bucket = candidate["rosterUnit"][0]["stats"]["datacron"] + protection = bucket.get("Protection", 0) + damage = bucket.get("Physical Damage", 0) + print(f" {datacron_id:<9} Protection +{protection:<10,.0f} Physical Damage +{damage:,.0f}") + + +# ── Example 5: ships ────────────────────────────────────────────────────── +# +# Datacrons are a squad mechanic. No game mode applies one to a fleet battle, +# so ships receive no bucket and their stats are untouched. + +fleet = { + "rosterUnit": [character("CADBANE"), character("VULTUREDROID")], # a crewless ship + "datacron": [maxed_datacron], +} +calc.calc_player_stats(fleet, datacron_id="maxed") + +print("\n=== Example 5: ships are never affected ===") +for unit in fleet["rosterUnit"]: + name = unit["definitionId"].split(":")[0] + has_bucket = "datacron" in unit["stats"] + print(f" {name:<14} datacron bucket: {has_bucket}") + + +# ── Example 6: a real player ────────────────────────────────────────────── +# +# Requires a running Comlink service. The datacron id comes from the player's +# own collection, which is why this entry point takes an id rather than an +# object — `calc_roster_stats` and `calc_char_stats` take the object, having no +# player to look it up in. Naming a datacron the player does not own raises +# KeyError, so a mistyped id fails loudly rather than silently adding nothing. + +comlink = SwgohComlink() +real_player = comlink.get_player(allycode=314927874) + +print("\n=== Example 6: a real player ===") +if not real_player.get("datacron"): + print(" this player owns no datacrons") +else: + chosen = real_player["datacron"][0] + calc.calc_player_stats(real_player, datacron_id=chosen["id"]) + + affected = [unit for unit in real_player["rosterUnit"] if unit.get("stats", {}).get("datacron")] + print(f" {chosen['templateId']} adds stats to {len(affected)} of {len(real_player['rosterUnit'])} units") + for unit in affected[:3]: + name = unit["definitionId"].split(":")[0] + added = ", ".join(f"{stat} +{show(amount)}" for stat, amount in sorted(unit["stats"]["datacron"].items())) + print(f" {name:<20} {added}")