From 681ab14481fc236dc53a15b04000e9c5148c081b Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Thu, 12 Nov 2026 08:34:14 +0100 Subject: [PATCH] Group Config and State fields, keep flat JSON Config moves the earned-time transports into EarnSources and the budget switches into PlaytimePolicy; State moves the legacy single pick into LegacyManualPick and the assignment clocks into AssignmentTimes. _flat_record writes groups inline at their old position, so config.json and state.json keep their exact bytes (golden round-trip tests). Todo: 9b9342ba Co-Authored-By: Claude Opus 5.5 --- .../_assignment_progress.py | 10 +- steam_backlog_enforcer/_config_groups.py | 84 +++++++++ steam_backlog_enforcer/_config_setup.py | 3 +- steam_backlog_enforcer/_flat_record.py | 77 ++++++++ steam_backlog_enforcer/_leetcode_bonus.py | 4 +- .../_manual_pick_lifecycle.py | 2 +- steam_backlog_enforcer/_pick_keep.py | 2 +- steam_backlog_enforcer/_playtime_state.py | 4 +- steam_backlog_enforcer/_reading_bonus.py | 2 +- steam_backlog_enforcer/_scanning_tampering.py | 2 +- steam_backlog_enforcer/_state_migrations.py | 26 +-- steam_backlog_enforcer/_workout_budget.py | 4 +- steam_backlog_enforcer/config.py | 87 +++------ steam_backlog_enforcer/main/misc.py | 12 +- steam_backlog_enforcer/tests/_main_helpers.py | 2 +- .../tests/_release_helpers.py | 42 +++++ steam_backlog_enforcer/tests/test_actions.py | 11 +- .../tests/test_assignment_progress.py | 15 +- .../tests/test_flat_records_golden.py | 108 +++++++++++ .../tests/test_main_status.py | 2 +- .../tests/test_pick_keep.py | 6 +- .../tests/test_pick_manual_keep.py | 3 +- .../tests/test_playtime_policy.py | 5 +- .../tests/test_playtime_rules_for.py | 21 ++- .../tests/test_reading_bonus.py | 7 +- .../tests/test_release_lifecycle.py | 174 +++++------------- .../tests/test_release_tampering.py | 107 +++++++++++ .../tests/test_status_api_stamp.py | 2 +- .../tests/test_workout_budget.py | 4 +- 29 files changed, 571 insertions(+), 257 deletions(-) create mode 100644 steam_backlog_enforcer/_config_groups.py create mode 100644 steam_backlog_enforcer/_flat_record.py create mode 100644 steam_backlog_enforcer/tests/_release_helpers.py create mode 100644 steam_backlog_enforcer/tests/test_flat_records_golden.py create mode 100644 steam_backlog_enforcer/tests/test_release_tampering.py diff --git a/steam_backlog_enforcer/_assignment_progress.py b/steam_backlog_enforcer/_assignment_progress.py index c315135..4ef8d21 100644 --- a/steam_backlog_enforcer/_assignment_progress.py +++ b/steam_backlog_enforcer/_assignment_progress.py @@ -62,15 +62,15 @@ def record_assignment( stamp = at or _now_iso() state.current_app_id = app_id state.current_game_name = game_name - state.current_assigned_at = stamp - state.last_assigned_at[str(app_id)] = stamp + state.assignment.current_assigned_at = stamp + state.assignment.last_assigned_at[str(app_id)] = stamp if not state.enforcement_started_at: state.enforcement_started_at = stamp def last_assigned_epoch(state: State, app_id: int) -> float: """Return when *app_id* was last assigned, ``0.0`` if never (sorts first).""" - return iso_to_epoch(state.last_assigned_at.get(str(app_id), "")) or 0.0 + return iso_to_epoch(state.assignment.last_assigned_at.get(str(app_id), "")) or 0.0 def assignment_baseline(state: State, app_id: int) -> str: @@ -86,7 +86,7 @@ def assignment_baseline(state: State, app_id: int) -> str: if pick.get("app_id") == app_id and pick.get("started_at"): return str(pick["started_at"]) if app_id == state.current_app_id: - return state.current_assigned_at + return state.assignment.current_assigned_at return "" @@ -158,5 +158,5 @@ def release_game(state: State, game: GameInfo) -> None: for pick in state.manual_picks: if pick.get("app_id") == game.app_id and not pick.get("released_at"): pick["released_at"] = now - state.released_at[str(game.app_id)] = now + state.assignment.released_at[str(game.app_id)] = now state.skip_for_days(game.app_id, RELEASE_COOLDOWN_DAYS) diff --git a/steam_backlog_enforcer/_config_groups.py b/steam_backlog_enforcer/_config_groups.py new file mode 100644 index 0000000..97da24d --- /dev/null +++ b/steam_backlog_enforcer/_config_groups.py @@ -0,0 +1,84 @@ +"""Field groups of :class:`~config.Config` and :class:`~config.State`. + +Each group is stored flat in its record's JSON file (see ``_flat_record``): +the keys below are the exact keys of ``config.json`` / ``state.json``. +A leaf module, so ``config`` can import it. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + + +@dataclass +class EarnSources: + """Where each earned-time bonus is read from (``config.json``).""" + + book_ledger_path: str = "~/.local/share/book_guard/ledger.json" + """book-guard's signed ledger: the reading hour's only transport.""" + workout_status_url: str = "http://127.0.0.1:8770/api/status" + """Where to ask whether today has a counted workout. Loopback only.""" + workout_log_path: str = "~/src/screen-locker/screen_locker/log.json" + """screen-locker's log.json; a change re-asks that URL at once.""" + leetcode_ledger_path: str = "~/.local/share/leetcode_guard/ledger.json" + leetcode_status_url: str = "http://127.0.0.1:8771/api/status" + """LeetCode's transports: ledger first, this loopback URL as fallback.""" + + +@dataclass +class PlaytimePolicy: + """What counts against the daily gaming budget (``config.json``).""" + + count_launcher_processes: bool = True + """Whether time spent in non-Steam launchers counts against the budget. + + Set False if a launcher legitimately idles in the tray all day. Leaving it + True is the safer default: under-counting is the failure mode that quietly + defeats the budget entirely. + """ + counted_processes: list[dict[str, Any]] | None = None + """Non-Steam games that count against the budget, beyond the launcher set. + + Each entry is ``{"id": ..., "label": ..., "names": [...]}``. ``None`` means + "use the built-in defaults" (osu!lazer); an explicit ``[]`` means "none", + which is why this is not simply an empty list. Parsed and validated by + ``leisure_watch.procscan`` (once ``_counted_procs``) — the field exists + here only so that ``save()`` round-trips a hand-edited list instead of + dropping it. + + Deliberately separate from ``LAUNCHER_PROCESS_NAMES``: that frozenset is + also the total-block kill list, so adding a game there has side effects + this list does not. + """ + playtime_enforcement: bool = True + """Master switch for the daily gaming budget. + + Disabling stops the cutoff but never strands a live block — the release + path runs regardless, so "disabled" cannot come to mean "blocked forever". + """ + + +@dataclass +class LegacyManualPick: + """Legacy single-slot manual pick, migrated into ``manual_picks`` on load. + + Stored as ``manual_pick_app_id`` / ``_game_name`` / ``_started_at`` so an + older ``state.json`` still deserialises; blanked once migrated. + """ + + app_id: int | None = None + game_name: str = "" + started_at: str = "" + + +@dataclass +class AssignmentTimes: + """When games were assigned and released (``state.json``).""" + + current_assigned_at: str = "" + """ISO time the current game was assigned; unlocks after it release it.""" + last_assigned_at: dict[str, str] = field(default_factory=dict) + """``str(app_id)`` → ISO time of its latest assignment (pick ordering).""" + released_at: dict[str, str] = field(default_factory=dict) + """``str(app_id)`` → ISO time it was released below 100% (tampering).""" diff --git a/steam_backlog_enforcer/_config_setup.py b/steam_backlog_enforcer/_config_setup.py index 80d7c34..3e64419 100644 --- a/steam_backlog_enforcer/_config_setup.py +++ b/steam_backlog_enforcer/_config_setup.py @@ -13,6 +13,7 @@ import json import sys from steam_backlog_enforcer import config as config_mod +from steam_backlog_enforcer._flat_record import to_flat from steam_backlog_enforcer._prompter import current_prompter from steam_backlog_enforcer.config import Config @@ -45,7 +46,7 @@ def save_credentials(api_key: str, steam_id: str) -> Config: # world-readable, nor be written to the real config during a test run. path = config_mod.CONFIG_FILE on_disk = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} - merged = on_disk | config.__dict__ + merged = on_disk | to_flat(config) config_mod.atomic_write(path, json.dumps(merged, indent=2) + "\n") path.chmod(0o600) return config diff --git a/steam_backlog_enforcer/_flat_record.py b/steam_backlog_enforcer/_flat_record.py new file mode 100644 index 0000000..d5a85ba --- /dev/null +++ b/steam_backlog_enforcer/_flat_record.py @@ -0,0 +1,77 @@ +"""Nested dataclass groups stored as one flat JSON object. + +The persisted records (``config.json``, ``state.json``, the playtime state) +are flat JSON objects that older daemons and kuhy's hand edits rely on. In +code, related fields live in a nested dataclass, a *group*, so no record +carries more than pylint's ``max-attributes``. A group field is marked with +:func:`flat_group`; :func:`to_flat` writes its fields inline (with an +optional key prefix) at the group's position, and :func:`from_flat` reads +them back, so the bytes on disk do not change. +""" + +from __future__ import annotations + +from dataclasses import fields +from typing import TYPE_CHECKING, Any, ClassVar, Final, Protocol + +if TYPE_CHECKING: + from collections.abc import Mapping + +_GROUP: Final = "flat_group" + + +class DataclassInstance(Protocol): + """Any dataclass instance (what ``dataclasses.fields`` accepts).""" + + __dataclass_fields__: ClassVar[dict[str, Any]] + + +def flat_group(cls: type[DataclassInstance], prefix: str = "") -> dict[str, Any]: + """Field metadata marking a group of *cls*, stored with key *prefix*.""" + return {_GROUP: (cls, prefix)} + + +def _group_of(meta: Mapping[str, Any]) -> tuple[type[DataclassInstance], str] | None: + """The group's class and key prefix, or ``None`` for a plain field.""" + group: tuple[type[DataclassInstance], str] | None = meta.get(_GROUP) + return group + + +def to_flat(record: DataclassInstance) -> dict[str, Any]: + """The record's fields as one flat dict, groups inlined in place.""" + out: dict[str, Any] = {} + for f in fields(record): + value = getattr(record, f.name) + group = _group_of(f.metadata) + if group is None: + out[f.name] = value + else: + out.update({group[1] + k: v for k, v in to_flat(value).items()}) + return out + + +def flat_keys(cls: type[DataclassInstance]) -> frozenset[str]: + """Every flat key a record of *cls* reads and writes.""" + keys: set[str] = set() + for f in fields(cls): + group = _group_of(f.metadata) + if group is None: + keys.add(f.name) + else: + keys.update(group[1] + k for k in flat_keys(group[0])) + return frozenset(keys) + + +def from_flat[T: DataclassInstance](cls: type[T], data: Mapping[str, Any]) -> T: + """Build *cls* from a flat dict; unknown keys are ignored.""" + kwargs: dict[str, Any] = {} + for f in fields(cls): + group = _group_of(f.metadata) + if group is None: + if f.name in data: + kwargs[f.name] = data[f.name] + continue + inner, prefix = group + sub = {k: data[prefix + k] for k in flat_keys(inner) if prefix + k in data} + kwargs[f.name] = from_flat(inner, sub) + return cls(**kwargs) diff --git a/steam_backlog_enforcer/_leetcode_bonus.py b/steam_backlog_enforcer/_leetcode_bonus.py index c6fa062..76fb6ac 100644 --- a/steam_backlog_enforcer/_leetcode_bonus.py +++ b/steam_backlog_enforcer/_leetcode_bonus.py @@ -124,8 +124,8 @@ def leetcode_solved_today(config: Config) -> bool | None: can log which one happened -- and so an unreadable ledger raises an incident while an honest "not solved yet" does not. """ - url = config.leetcode_status_url - path = Path(config.leetcode_ledger_path).expanduser() + url = config.earn.leetcode_status_url + path = Path(config.earn.leetcode_ledger_path).expanduser() # A new credit row rewrites the ledger; its stamp drops the memo at once. stamp = file_stamp(path) cached = _cache.fresh(url, stamp=stamp) diff --git a/steam_backlog_enforcer/_manual_pick_lifecycle.py b/steam_backlog_enforcer/_manual_pick_lifecycle.py index 7c83ca7..3bd3af6 100644 --- a/steam_backlog_enforcer/_manual_pick_lifecycle.py +++ b/steam_backlog_enforcer/_manual_pick_lifecycle.py @@ -100,7 +100,7 @@ def abandon_manual_pick(state: State, app_id: int) -> bool: if survivor is None: state.current_app_id = None state.current_game_name = "" - state.current_assigned_at = "" + state.assignment.current_assigned_at = "" else: # The survivor has been assigned since it was picked. record_assignment( diff --git a/steam_backlog_enforcer/_pick_keep.py b/steam_backlog_enforcer/_pick_keep.py index 80573eb..725b142 100644 --- a/steam_backlog_enforcer/_pick_keep.py +++ b/steam_backlog_enforcer/_pick_keep.py @@ -44,7 +44,7 @@ def keep_outgoing_assignment(state: State) -> dict[str, Any] | None: entry: dict[str, Any] = { "app_id": app_id, "game_name": state.current_game_name, - "started_at": state.current_assigned_at or now, + "started_at": state.assignment.current_assigned_at or now, # Released, not active: allowed, but no lock and no pick slot. "released_at": now, } diff --git a/steam_backlog_enforcer/_playtime_state.py b/steam_backlog_enforcer/_playtime_state.py index 1b134f2..8549a89 100644 --- a/steam_backlog_enforcer/_playtime_state.py +++ b/steam_backlog_enforcer/_playtime_state.py @@ -129,8 +129,8 @@ def rules_for(config: Config, *, demo: bool) -> PlaytimeRules: budget_seconds=_DEMO_BUDGET_SECONDS if resolved is None else max(live, held), warn_at=_DEMO_WARN_AT if demo else _WARN_AT, sigkill_after=(_DEMO_SIGKILL_AFTER_SECONDS if demo else _SIGKILL_AFTER_SECONDS), - count_launchers=config.count_launcher_processes, - enforcement=config.playtime_enforcement, + count_launchers=config.playtime.count_launcher_processes, + enforcement=config.playtime.playtime_enforcement, demo=demo, base_seconds=_DEMO_BUDGET_SECONDS if resolved is None diff --git a/steam_backlog_enforcer/_reading_bonus.py b/steam_backlog_enforcer/_reading_bonus.py index cca30d7..317cac7 100644 --- a/steam_backlog_enforcer/_reading_bonus.py +++ b/steam_backlog_enforcer/_reading_bonus.py @@ -59,7 +59,7 @@ def read_ledger_read_today(path: Path) -> bool | None: def read_today(config: Config) -> bool | None: """Today's reading answer, memoised like the other earners.""" - path = Path(config.book_ledger_path).expanduser() + path = Path(config.earn.book_ledger_path).expanduser() # Stat before reading, so a credit landing mid-read is re-read next tick. stamp = file_stamp(path) cached = _cache.fresh(_CACHE_KEY, stamp=stamp) diff --git a/steam_backlog_enforcer/_scanning_tampering.py b/steam_backlog_enforcer/_scanning_tampering.py index 30b660b..d5287ac 100644 --- a/steam_backlog_enforcer/_scanning_tampering.py +++ b/steam_backlog_enforcer/_scanning_tampering.py @@ -88,7 +88,7 @@ def _unexpected_unlocks( Tuple of (name, app_id, diff) if tampering detected, else None. """ app_id = entry["app_id"] - released = iso_to_epoch(state.released_at.get(str(app_id), "")) + released = iso_to_epoch(state.assignment.released_at.get(str(app_id), "")) if released is not None: # Released below 100%: the snapshot predates the unlocks earned while # it was assigned, so only unlocks after the release are suspicious. diff --git a/steam_backlog_enforcer/_state_migrations.py b/steam_backlog_enforcer/_state_migrations.py index eb8d38f..6ee226b 100644 --- a/steam_backlog_enforcer/_state_migrations.py +++ b/steam_backlog_enforcer/_state_migrations.py @@ -27,18 +27,18 @@ def migrate_legacy_manual_pick(state: State) -> bool: Returns: Whether a legacy pick was migrated. """ - if state.manual_pick_app_id is None or state.manual_picks: + if state.legacy_pick.app_id is None or state.manual_picks: return False state.manual_picks = [ { - "app_id": state.manual_pick_app_id, - "game_name": state.manual_pick_game_name, - "started_at": state.manual_pick_started_at, + "app_id": state.legacy_pick.app_id, + "game_name": state.legacy_pick.game_name, + "started_at": state.legacy_pick.started_at, } ] - state.manual_pick_app_id = None - state.manual_pick_game_name = "" - state.manual_pick_started_at = "" + state.legacy_pick.app_id = None + state.legacy_pick.game_name = "" + state.legacy_pick.started_at = "" return True @@ -67,18 +67,20 @@ def backfill_assignment_times(state: State) -> bool: changed |= _stamp_if_missing(state, app_id, started_at) current = state.current_app_id if current is not None: - if not state.current_assigned_at: + if not state.assignment.current_assigned_at: # A current game that is also a pick was assigned when picked. - state.current_assigned_at = pick_started.get(current) or ( + state.assignment.current_assigned_at = pick_started.get(current) or ( datetime.now(UTC).isoformat() ) changed = True - changed |= _stamp_if_missing(state, current, state.current_assigned_at) + changed |= _stamp_if_missing( + state, current, state.assignment.current_assigned_at + ) return changed def _stamp_if_missing(state: State, app_id: int, stamp: str) -> bool: - if str(app_id) in state.last_assigned_at: + if str(app_id) in state.assignment.last_assigned_at: return False - state.last_assigned_at[str(app_id)] = stamp + state.assignment.last_assigned_at[str(app_id)] = stamp return True diff --git a/steam_backlog_enforcer/_workout_budget.py b/steam_backlog_enforcer/_workout_budget.py index 5f9be32..3cb2289 100644 --- a/steam_backlog_enforcer/_workout_budget.py +++ b/steam_backlog_enforcer/_workout_budget.py @@ -36,7 +36,7 @@ def reset_cache() -> None: def workout_log_path(config: Config) -> Path: """screen-locker's ``log.json``, which ``gaming.workout_today`` derives from.""" - return Path(config.workout_log_path).expanduser() + return Path(config.earn.workout_log_path).expanduser() def _fetch_workout_today(url: str) -> bool: @@ -67,7 +67,7 @@ def workout_logged_today(config: Config) -> bool | None: reached or its answer could not be understood. ``None`` is deliberately distinct from ``False`` so the caller can log which one happened. """ - url = config.workout_status_url + url = config.earn.workout_status_url # Stat before asking: a credited workout rewrites log.json, and the new # stamp re-asks on the very next tick instead of after the cache TTL. stamp = file_stamp(workout_log_path(config)) diff --git a/steam_backlog_enforcer/config.py b/steam_backlog_enforcer/config.py index ec42d89..a7473ba 100644 --- a/steam_backlog_enforcer/config.py +++ b/steam_backlog_enforcer/config.py @@ -3,7 +3,7 @@ from __future__ import annotations import contextlib -from dataclasses import dataclass, field, fields +from dataclasses import dataclass, field from datetime import UTC, datetime, timedelta import json import logging @@ -12,6 +12,13 @@ from pathlib import Path import tempfile from typing import Any +from steam_backlog_enforcer._config_groups import ( + AssignmentTimes, + EarnSources, + LegacyManualPick, + PlaytimePolicy, +) +from steam_backlog_enforcer._flat_record import flat_group, from_flat, to_flat from steam_backlog_enforcer._state_migrations import ( backfill_assignment_times, migrate_legacy_manual_pick, @@ -76,11 +83,6 @@ def _atomic_write(path: Path, data: str, *, mode: int | None = None) -> None: atomic_write = _atomic_write -def _field_names(cls: type) -> frozenset[str]: - """The dataclass's own field names, for filtering a loaded JSON object.""" - return frozenset(f.name for f in fields(cls)) - - @dataclass class Config: """User configuration.""" @@ -97,48 +99,18 @@ class Config: All active picks stay installed and visible; the enforcer treats them as one allowed set. Raising this weakens enforcement proportionally. """ - book_ledger_path: str = "~/.local/share/book_guard/ledger.json" - """book-guard's signed ledger: the reading hour's only transport.""" - workout_status_url: str = "http://127.0.0.1:8770/api/status" - """Where to ask whether today has a counted workout. Loopback only.""" - workout_log_path: str = "~/src/screen-locker/screen_locker/log.json" - """screen-locker's log.json; a change re-asks that URL at once.""" - leetcode_ledger_path: str = "~/.local/share/leetcode_guard/ledger.json" - leetcode_status_url: str = "http://127.0.0.1:8771/api/status" - """LeetCode's transports: ledger first, this loopback URL as fallback.""" - count_launcher_processes: bool = True - """Whether time spent in non-Steam launchers counts against the budget. - - Set False if a launcher legitimately idles in the tray all day. Leaving it - True is the safer default: under-counting is the failure mode that quietly - defeats the budget entirely. - """ - counted_processes: list[dict[str, Any]] | None = None - """Non-Steam games that count against the budget, beyond the launcher set. - - Each entry is ``{"id": ..., "label": ..., "names": [...]}``. ``None`` means - "use the built-in defaults" (osu!lazer); an explicit ``[]`` means "none", - which is why this is not simply an empty list. Parsed and validated by - ``leisure_watch.procscan`` (once ``_counted_procs``) — the field exists - here only so that ``save()`` round-trips a hand-edited list instead of - dropping it. - - Deliberately separate from ``LAUNCHER_PROCESS_NAMES``: that frozenset is - also the total-block kill list, so adding a game there has side effects - this list does not. - """ - playtime_enforcement: bool = True - """Master switch for the daily gaming budget. - - Disabling stops the cutoff but never strands a live block — the release - path runs regardless, so "disabled" cannot come to mean "blocked forever". - """ + earn: EarnSources = field( + default_factory=EarnSources, metadata=flat_group(EarnSources) + ) + playtime: PlaytimePolicy = field( + default_factory=PlaytimePolicy, metadata=flat_group(PlaytimePolicy) + ) def save(self) -> None: """Persist config to disk.""" _atomic_write( CONFIG_FILE, - json.dumps(self.__dict__, indent=2) + "\n", + json.dumps(to_flat(self), indent=2) + "\n", ) @classmethod @@ -146,7 +118,7 @@ class Config: """Load config from disk, or return defaults.""" if CONFIG_FILE.exists(): data = json.loads(CONFIG_FILE.read_text(encoding="utf-8")) - return cls(**{k: v for k, v in data.items() if k in _field_names(cls)}) + return from_flat(cls, data) return cls() @@ -166,27 +138,20 @@ class State: """ enforcement_started_at: str = "" """ISO-8601 UTC timestamp set on the first game assignment.""" - manual_pick_app_id: int | None = None - manual_pick_game_name: str = "" - manual_pick_started_at: str = "" - """Legacy single-slot manual pick, migrated into ``manual_picks`` on load. - - Kept as fields so an older ``state.json`` still deserialises; they are - blanked once migrated and are never written again. - """ + legacy_pick: LegacyManualPick = field( + default_factory=LegacyManualPick, + metadata=flat_group(LegacyManualPick, "manual_pick_"), + ) manual_picks: list[dict[str, Any]] = field(default_factory=list) """Manual picks, newest last; inactive ones stay until a new choice. Each entry is ``{"app_id": int, "game_name": str, "started_at": iso}``, plus ``"released_at": iso`` once it earned a new achievement. Plain dicts - because ``save`` serialises ``self.__dict__`` straight to JSON. + because ``save`` serialises them straight to JSON. """ - current_assigned_at: str = "" - """ISO time the current game was assigned; unlocks after it release it.""" - last_assigned_at: dict[str, str] = field(default_factory=dict) - """``str(app_id)`` → ISO time of its latest assignment (pick ordering).""" - released_at: dict[str, str] = field(default_factory=dict) - """``str(app_id)`` → ISO time it was released below 100% (tampering).""" + assignment: AssignmentTimes = field( + default_factory=AssignmentTimes, metadata=flat_group(AssignmentTimes) + ) store_unblocked_until: str = "" """ISO deadline of the open store window (``unblock``); CLI-written only.""" @@ -222,7 +187,7 @@ class State: """Persist state to disk.""" _atomic_write( STATE_FILE, - json.dumps(self.__dict__, indent=2) + "\n", + json.dumps(to_flat(self), indent=2) + "\n", ) @classmethod @@ -234,7 +199,7 @@ class State: except json.JSONDecodeError, OSError, ValueError: logger.warning("Corrupt state file, using defaults.") return cls() - state = cls(**{k: v for k, v in data.items() if k in _field_names(cls)}) + state = from_flat(cls, data) migrated = migrate_legacy_manual_pick(state) if backfill_assignment_times(state) or migrated: state.save() diff --git a/steam_backlog_enforcer/main/misc.py b/steam_backlog_enforcer/main/misc.py index b62c355..67c5174 100644 --- a/steam_backlog_enforcer/main/misc.py +++ b/steam_backlog_enforcer/main/misc.py @@ -102,13 +102,13 @@ def cmd_reset(config: Config, state: State) -> None: state.current_app_id = None state.current_game_name = "" state.finished_app_ids = [] - state.manual_pick_app_id = None - state.manual_pick_game_name = "" - state.manual_pick_started_at = "" + state.legacy_pick.app_id = None + state.legacy_pick.game_name = "" + state.legacy_pick.started_at = "" state.manual_picks = [] - state.current_assigned_at = "" - state.last_assigned_at = {} - state.released_at = {} + state.assignment.current_assigned_at = "" + state.assignment.last_assigned_at = {} + state.assignment.released_at = {} state.save() _echo("State reset. Store left blocked: open a timed window with 'unblock'.") diff --git a/steam_backlog_enforcer/tests/_main_helpers.py b/steam_backlog_enforcer/tests/_main_helpers.py index 4206c69..b5836ec 100644 --- a/steam_backlog_enforcer/tests/_main_helpers.py +++ b/steam_backlog_enforcer/tests/_main_helpers.py @@ -123,7 +123,7 @@ def abandonable_state(app_id: int = 100, started_at: str = RECENT_PICK) -> State """ state = locked_state(app_id=app_id, started_at=started_at) state.current_app_id = app_id - state.current_game_name = state.manual_pick_game_name + state.current_game_name = state.legacy_pick.game_name return state diff --git a/steam_backlog_enforcer/tests/_release_helpers.py b/steam_backlog_enforcer/tests/_release_helpers.py new file mode 100644 index 0000000..00ac13d --- /dev/null +++ b/steam_backlog_enforcer/tests/_release_helpers.py @@ -0,0 +1,42 @@ +"""Shared builders for the release-lifecycle and tampering tests.""" + +from __future__ import annotations + +from datetime import UTC, datetime +import json + +from steam_backlog_enforcer import config as config_mod +from steam_backlog_enforcer.steam_api import AchievementInfo, GameInfo +from steam_backlog_enforcer.tests._main_helpers import STARTED_AT + +RELEASED = datetime(2026, 9, 20, tzinfo=UTC) + + +def pick(app_id: int, **extra: str) -> dict[str, object]: + """Build one manual-pick entry started a day ago.""" + return { + "app_id": app_id, + "game_name": f"G{app_id}", + "started_at": STARTED_AT, + } | dict(extra.items()) + + +def game(app_id: int, *unlock_times: int, hours: float = 5.0) -> GameInfo: + """Build a GameInfo with one unlocked achievement per epoch given.""" + return GameInfo( + app_id=app_id, + name=f"G{app_id}", + total_achievements=10, + unlocked_achievements=len(unlock_times), + playtime_minutes=60, + completionist_hours=hours, + achievements=[ + AchievementInfo(f"a{t}", f"A{t}", achieved=True, unlock_time=t) + for t in unlock_times + ], + ) + + +def write_state(data: dict[str, object]) -> None: + """Write raw JSON to the (conftest-redirected) state file.""" + config_mod.STATE_FILE.write_text(json.dumps(data), encoding="utf-8") diff --git a/steam_backlog_enforcer/tests/test_actions.py b/steam_backlog_enforcer/tests/test_actions.py index da50de0..d0659a9 100644 --- a/steam_backlog_enforcer/tests/test_actions.py +++ b/steam_backlog_enforcer/tests/test_actions.py @@ -9,6 +9,7 @@ from steam_backlog_enforcer._actions import ( apply_manual_pick, is_manual_pick_locked, ) +from steam_backlog_enforcer._config_groups import LegacyManualPick from steam_backlog_enforcer._manual_pick_lifecycle import manual_pick_age_days from steam_backlog_enforcer.config import State from steam_backlog_enforcer.tests._manual_pick_rows import iso_days_ago, pick_row @@ -77,18 +78,16 @@ class TestLegacyManualPickMigration: """Test legacy pick is migrated on load.""" started = iso_days_ago(1) State( - manual_pick_app_id=5, - manual_pick_game_name="Legacy", - manual_pick_started_at=started, + legacy_pick=LegacyManualPick(5, "Legacy", started), ).save() loaded = State.load() assert loaded.manual_picks == [ {"app_id": 5, "game_name": "Legacy", "started_at": started} ] - assert loaded.manual_pick_app_id is None - assert loaded.manual_pick_game_name == "" - assert loaded.manual_pick_started_at == "" + assert loaded.legacy_pick.app_id is None + assert loaded.legacy_pick.game_name == "" + assert loaded.legacy_pick.started_at == "" assert is_manual_pick_locked(loaded) is True def test_new_format_is_left_alone(self) -> None: diff --git a/steam_backlog_enforcer/tests/test_assignment_progress.py b/steam_backlog_enforcer/tests/test_assignment_progress.py index 8e166bb..ad2798f 100644 --- a/steam_backlog_enforcer/tests/test_assignment_progress.py +++ b/steam_backlog_enforcer/tests/test_assignment_progress.py @@ -15,6 +15,7 @@ from steam_backlog_enforcer._assignment_progress import ( release_game, release_verdict, ) +from steam_backlog_enforcer._config_groups import AssignmentTimes from steam_backlog_enforcer.config import State from steam_backlog_enforcer.steam_api import AchievementInfo, GameInfo @@ -57,7 +58,7 @@ def assigned_state(app_id: int = 1) -> State: return State( current_app_id=app_id, current_game_name="G", - current_assigned_at=ASSIGNED.isoformat(), + assignment=AssignmentTimes(current_assigned_at=ASSIGNED.isoformat()), ) @@ -151,8 +152,8 @@ class TestRecordAssignment: state = State() record_assignment(state, 7, "Seven", at="T") assert (state.current_app_id, state.current_game_name) == (7, "Seven") - assert state.current_assigned_at == "T" - assert state.last_assigned_at == {"7": "T"} + assert state.assignment.current_assigned_at == "T" + assert state.assignment.last_assigned_at == {"7": "T"} assert state.enforcement_started_at == "T" def test_keeps_the_first_enforcement_start(self) -> None: @@ -160,7 +161,7 @@ class TestRecordAssignment: state = State(enforcement_started_at="FIRST") record_assignment(state, 7, "Seven") assert state.enforcement_started_at == "FIRST" - assert iso_to_epoch(state.current_assigned_at) is not None + assert iso_to_epoch(state.assignment.current_assigned_at) is not None class TestLastAssignedEpoch: @@ -172,7 +173,9 @@ class TestLastAssignedEpoch: def test_reads_the_stamp(self) -> None: """A stored stamp reads back as its epoch seconds.""" - state = State(last_assigned_at={"1": ASSIGNED.isoformat()}) + state = State( + assignment=AssignmentTimes(last_assigned_at={"1": ASSIGNED.isoformat()}) + ) assert last_assigned_epoch(state, 1) == ASSIGNED.timestamp() @@ -197,7 +200,7 @@ class TestReleaseGame: release_game(state, game(("a", AFTER))) assert state.finished_app_ids == [] assert state.manual_picks[0]["released_at"] - assert "1" in state.released_at + assert "1" in state.assignment.released_at expiry = datetime.fromisoformat(state.skipped_until["1"]) assert expiry > datetime.now(UTC) + timedelta(days=RELEASE_COOLDOWN_DAYS - 1) diff --git a/steam_backlog_enforcer/tests/test_flat_records_golden.py b/steam_backlog_enforcer/tests/test_flat_records_golden.py new file mode 100644 index 0000000..05ab0ea --- /dev/null +++ b/steam_backlog_enforcer/tests/test_flat_records_golden.py @@ -0,0 +1,108 @@ +"""Golden round-trips: the persisted files keep their exact flat bytes. + +``Config``, ``State`` and ``PlaytimeState`` group fields into nested +dataclasses, but the files on disk stay flat. A fully populated file written +by the old flat classes must load and save back byte for byte. +""" + +from __future__ import annotations + +import json +from typing import Any + +from steam_backlog_enforcer import _playtime_state, config +from steam_backlog_enforcer._playtime_state import load_state, save_state + +CONFIG: dict[str, Any] = { + "steam_api_key": "KEY", + "steam_id": "7656", + "block_store": False, + "kill_unauthorized_games": False, + "uninstall_other_games": False, + "desktop_notifications": False, + "max_manual_picks": 3, + "book_ledger_path": "/b.json", + "workout_status_url": "http://127.0.0.1:1/w", + "workout_log_path": "/w.json", + "leetcode_ledger_path": "/l.json", + "leetcode_status_url": "http://127.0.0.1:2/l", + "count_launcher_processes": False, + "counted_processes": [{"id": "osu", "label": "osu!", "names": ["osu!"]}], + "playtime_enforcement": False, +} + +STATE: dict[str, Any] = { + "current_app_id": 440, + "current_game_name": "TF2", + "finished_app_ids": [10, 20], + "skipped_until": {"30": "2026-11-20T00:00:00+00:00"}, + "enforcement_started_at": "2026-01-01T00:00:00+00:00", + "manual_pick_app_id": None, + "manual_pick_game_name": "", + "manual_pick_started_at": "", + "manual_picks": [ + {"app_id": 50, "game_name": "Fifty", "started_at": "2026-11-01T00:00:00"} + ], + "current_assigned_at": "2026-11-02T00:00:00+00:00", + "last_assigned_at": { + "440": "2026-11-02T00:00:00+00:00", + "50": "2026-11-01T00:00:00", + }, + "released_at": {"60": "2026-11-03T00:00:00+00:00"}, + "store_unblocked_until": "2026-11-12T10:00:00+00:00", +} + +PLAYTIME: dict[str, Any] = { + "schema_version": 1, + "day_key": "2026-11-12", + "seconds": 120.5, + "last_tick_at": 1700000000.0, + "blocked_at": 1700000100.0, + "per_game": {"app:440": 100.0}, + "last_credited_key": "app:440", + "warned_seconds": [600, 300], + "budget_seconds": 7200.0, + "shadow_seconds": 30.0, + "shadow_budget_seconds": 3600.0, + "shadow_per_source": {"media": 30.0}, + "shadow_paused_seconds": 5.0, +} + + +def _flat(data: dict[str, Any]) -> str: + """The exact bytes the flat classes wrote.""" + return json.dumps(data, indent=2) + "\n" + + +def test_config_round_trips_byte_for_byte() -> None: + """A full config.json loads and saves back unchanged.""" + config.CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True) + config.CONFIG_FILE.write_text(_flat(CONFIG), encoding="utf-8") + config.Config.load().save() + assert config.CONFIG_FILE.read_text(encoding="utf-8") == _flat(CONFIG) + + +def test_config_defaults_keep_the_flat_shape() -> None: + """A default config writes every flat key, in the old order.""" + config.Config().save() + saved = json.loads(config.CONFIG_FILE.read_text(encoding="utf-8")) + assert list(saved) == list(CONFIG) + + +def test_state_round_trips_byte_for_byte() -> None: + """A full state.json loads and saves back unchanged.""" + config.STATE_FILE.parent.mkdir(parents=True, exist_ok=True) + config.STATE_FILE.write_text(_flat(STATE), encoding="utf-8") + config.State.load().save() + assert config.STATE_FILE.read_text(encoding="utf-8") == _flat(STATE) + + +def test_playtime_state_round_trips_byte_for_byte() -> None: + """A full playtime state file loads and saves back unchanged.""" + path = _playtime_state.state_path(demo=True) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(_flat(PLAYTIME), encoding="utf-8") + state = load_state(demo=True) + assert state is not None + save_state(state, demo=True) + assert path.read_text(encoding="utf-8") == _flat(PLAYTIME) diff --git a/steam_backlog_enforcer/tests/test_main_status.py b/steam_backlog_enforcer/tests/test_main_status.py index 43d7c62..0bf57e5 100644 --- a/steam_backlog_enforcer/tests/test_main_status.py +++ b/steam_backlog_enforcer/tests/test_main_status.py @@ -131,7 +131,7 @@ _RECENT_PICK = (datetime.now(UTC) - timedelta(days=1)).isoformat() def _abandonable_state(app_id: int = 100, started_at: str = _RECENT_PICK) -> State: state = locked_state(app_id=app_id, started_at=started_at) state.current_app_id = app_id - state.current_game_name = state.manual_pick_game_name + state.current_game_name = state.legacy_pick.game_name return state diff --git a/steam_backlog_enforcer/tests/test_pick_keep.py b/steam_backlog_enforcer/tests/test_pick_keep.py index b70ebc5..044ff8d 100644 --- a/steam_backlog_enforcer/tests/test_pick_keep.py +++ b/steam_backlog_enforcer/tests/test_pick_keep.py @@ -56,8 +56,8 @@ def _state_on( state = State(manual_picks=manual_picks or []) state.current_app_id = app_id state.current_game_name = name - state.current_assigned_at = STARTED_AT - state.last_assigned_at[str(app_id)] = STARTED_AT + state.assignment.current_assigned_at = STARTED_AT + state.assignment.last_assigned_at[str(app_id)] = STARTED_AT return state @@ -123,7 +123,7 @@ class TestKeep: assert kept["released_at"] assert active_manual_picks(state) == [] assert state.finished_app_ids == [] - assert state.released_at == {} + assert state.assignment.released_at == {} def test_allowed_games_are_not_offered(self) -> None: """Games already allowed are not offered as candidates.""" diff --git a/steam_backlog_enforcer/tests/test_pick_manual_keep.py b/steam_backlog_enforcer/tests/test_pick_manual_keep.py index 7fcd135..d7c047d 100644 --- a/steam_backlog_enforcer/tests/test_pick_manual_keep.py +++ b/steam_backlog_enforcer/tests/test_pick_manual_keep.py @@ -15,6 +15,7 @@ import pytest from steam_backlog_enforcer import _mcp_actions as mcp_actions from steam_backlog_enforcer._actions import allowed_app_ids, apply_manual_pick from steam_backlog_enforcer._allowed_games import active_manual_picks +from steam_backlog_enforcer._config_groups import AssignmentTimes from steam_backlog_enforcer.config import Config, State from steam_backlog_enforcer.main import cmd_pick_manual from steam_backlog_enforcer.tests._main_helpers import STARTED_AT @@ -36,7 +37,7 @@ def _state(*kept: tuple[int, str], current: tuple[int, str] = (1, "Current")) -> return State( current_app_id=current[0], current_game_name=current[1], - current_assigned_at=STARTED_AT, + assignment=AssignmentTimes(current_assigned_at=STARTED_AT), manual_picks=[_kept(a, n) for a, n in kept], ) diff --git a/steam_backlog_enforcer/tests/test_playtime_policy.py b/steam_backlog_enforcer/tests/test_playtime_policy.py index 8a39714..61b4075 100644 --- a/steam_backlog_enforcer/tests/test_playtime_policy.py +++ b/steam_backlog_enforcer/tests/test_playtime_policy.py @@ -13,6 +13,7 @@ from datetime import ( ) from unittest.mock import patch +from steam_backlog_enforcer._config_groups import PlaytimePolicy from steam_backlog_enforcer._playtime import ( _policy, ) @@ -28,8 +29,8 @@ NOW = datetime(2026, 7, 27, 20, 0, tzinfo=LOCAL) TODAY = "2026-07-27" -def _rules(*, demo: bool = False, **cfg: object) -> object: - return rules_for(Config(**cfg), demo=demo) +def _rules(*, demo: bool = False, **policy: bool) -> object: + return rules_for(Config(playtime=PlaytimePolicy(**policy)), demo=demo) class TestPolicyBelowBudget: diff --git a/steam_backlog_enforcer/tests/test_playtime_rules_for.py b/steam_backlog_enforcer/tests/test_playtime_rules_for.py index 6cdfe98..5ac31a3 100644 --- a/steam_backlog_enforcer/tests/test_playtime_rules_for.py +++ b/steam_backlog_enforcer/tests/test_playtime_rules_for.py @@ -6,6 +6,7 @@ from dataclasses import FrozenInstanceError import pytest +from steam_backlog_enforcer._config_groups import PlaytimePolicy from steam_backlog_enforcer._playtime_state import rules_for from steam_backlog_enforcer.config import Config from steam_backlog_enforcer.tests._no_workout_http import fixed_budget @@ -41,26 +42,36 @@ class TestRulesFor: """count_launcher_processes becomes count_launchers.""" assert ( rules_for( - Config(count_launcher_processes=False), demo=False + Config(playtime=PlaytimePolicy(count_launcher_processes=False)), + demo=False, ).count_launchers is False ) assert ( - rules_for(Config(count_launcher_processes=True), demo=False).count_launchers + rules_for( + Config(playtime=PlaytimePolicy(count_launcher_processes=True)), + demo=False, + ).count_launchers is True ) def test_enforcement_toggle_is_carried_through(self) -> None: """playtime_enforcement off becomes enforcement off.""" assert ( - rules_for(Config(playtime_enforcement=False), demo=False).enforcement + rules_for( + Config(playtime=PlaytimePolicy(playtime_enforcement=False)), demo=False + ).enforcement is False ) def test_demo_uses_the_same_qualifying_predicate(self) -> None: """Demo may differ in budget and warnings only.""" - prod = rules_for(Config(count_launcher_processes=True), demo=False) - demo = rules_for(Config(count_launcher_processes=True), demo=True) + prod = rules_for( + Config(playtime=PlaytimePolicy(count_launcher_processes=True)), demo=False + ) + demo = rules_for( + Config(playtime=PlaytimePolicy(count_launcher_processes=True)), demo=True + ) assert prod.count_launchers == demo.count_launchers def test_rules_are_frozen(self) -> None: diff --git a/steam_backlog_enforcer/tests/test_reading_bonus.py b/steam_backlog_enforcer/tests/test_reading_bonus.py index 5b79e2a..d9f7bd8 100644 --- a/steam_backlog_enforcer/tests/test_reading_bonus.py +++ b/steam_backlog_enforcer/tests/test_reading_bonus.py @@ -16,6 +16,7 @@ from unittest.mock import patch import pytest +from steam_backlog_enforcer._config_groups import EarnSources from steam_backlog_enforcer._reading_bonus import ( read_ledger_read_today, read_today, @@ -199,7 +200,9 @@ class TestTheMemo: def test_reads_the_configured_ledger(self, tmp_path: Path) -> None: """read_today reads the ledger named in the config.""" ledger = write_ledger(tmp_path, [reading(when=_now())]) - assert read_today(Config(book_ledger_path=str(ledger))) is True + assert ( + read_today(Config(earn=EarnSources(book_ledger_path=str(ledger)))) is True + ) def test_a_cached_answer_is_served_without_a_reread(self) -> None: """A cached answer is served without reading the ledger again.""" @@ -225,4 +228,4 @@ class TestTheMemo: def test_the_default_path_is_book_guards(self) -> None: """The default ledger path points at book_guard's ledger.""" - assert Config().book_ledger_path.endswith("book_guard/ledger.json") + assert Config().earn.book_ledger_path.endswith("book_guard/ledger.json") diff --git a/steam_backlog_enforcer/tests/test_release_lifecycle.py b/steam_backlog_enforcer/tests/test_release_lifecycle.py index 77b2d73..82a6a03 100644 --- a/steam_backlog_enforcer/tests/test_release_lifecycle.py +++ b/steam_backlog_enforcer/tests/test_release_lifecycle.py @@ -1,14 +1,13 @@ """A released game stays playable until the user explicitly picks another. -Covers the state upgrade, the allowed set, abandoning, pick order, tampering -and the ``check`` command under the "one new achievement" rule. +Covers the state upgrade, the allowed set, abandoning and pick order under +the "one new achievement" rule (tampering: ``test_release_tampering``). """ from __future__ import annotations -from datetime import UTC, datetime, timedelta import json -from unittest.mock import MagicMock, patch +from unittest.mock import patch from steam_backlog_enforcer import config as config_mod from steam_backlog_enforcer._actions import ( @@ -17,45 +16,16 @@ from steam_backlog_enforcer._actions import ( is_manual_pick_locked, ) from steam_backlog_enforcer._allowed_games import drop_inactive_picks +from steam_backlog_enforcer._config_groups import AssignmentTimes from steam_backlog_enforcer._manual_pick_lifecycle import abandon_manual_pick from steam_backlog_enforcer._scanning_assign import _open_candidates -from steam_backlog_enforcer._scanning_tampering import _check_game_tampering -from steam_backlog_enforcer.config import Config, State -from steam_backlog_enforcer.scanning import do_check -from steam_backlog_enforcer.steam_api import AchievementInfo, GameInfo +from steam_backlog_enforcer.config import State from steam_backlog_enforcer.tests._main_helpers import EXPIRED_AT, STARTED_AT - -RELEASED = datetime(2026, 9, 20, tzinfo=UTC) - - -def pick(app_id: int, **extra: str) -> dict[str, object]: - """Build one manual-pick entry started a day ago.""" - return { - "app_id": app_id, - "game_name": f"G{app_id}", - "started_at": STARTED_AT, - } | dict(extra.items()) - - -def game(app_id: int, *unlock_times: int, hours: float = 5.0) -> GameInfo: - """Build a GameInfo with one unlocked achievement per epoch given.""" - return GameInfo( - app_id=app_id, - name=f"G{app_id}", - total_achievements=10, - unlocked_achievements=len(unlock_times), - playtime_minutes=60, - completionist_hours=hours, - achievements=[ - AchievementInfo(f"a{t}", f"A{t}", achieved=True, unlock_time=t) - for t in unlock_times - ], - ) - - -def write_state(data: dict[str, object]) -> None: - """Write raw JSON to the (conftest-redirected) state file.""" - config_mod.STATE_FILE.write_text(json.dumps(data), encoding="utf-8") +from steam_backlog_enforcer.tests._release_helpers import ( + game, + pick, + write_state, +) class TestLoadBackfill: @@ -65,16 +35,21 @@ class TestLoadBackfill: """A plain assignment gets one timestamp that later loads keep.""" write_state({"current_app_id": 5, "current_game_name": "G5"}) first = State.load() - assert first.current_assigned_at - assert State.load().current_assigned_at == first.current_assigned_at - assert first.last_assigned_at == {"5": first.current_assigned_at} + assert first.assignment.current_assigned_at + assert ( + State.load().assignment.current_assigned_at + == first.assignment.current_assigned_at + ) + assert first.assignment.last_assigned_at == { + "5": first.assignment.current_assigned_at + } def test_current_pick_keeps_its_pick_time(self) -> None: """An assigned pick is timed from when it was picked.""" write_state({"current_app_id": 5, "manual_picks": [pick(5), pick(6)]}) state = State.load() - assert state.current_assigned_at == STARTED_AT - assert state.last_assigned_at == {"5": STARTED_AT, "6": STARTED_AT} + assert state.assignment.current_assigned_at == STARTED_AT + assert state.assignment.last_assigned_at == {"5": STARTED_AT, "6": STARTED_AT} def test_legacy_pick_migration_is_persisted(self) -> None: """A legacy single-pick state is migrated and written back.""" @@ -120,7 +95,9 @@ class TestReleasedPicksStayPlayable: with patch.object(State, "save"): assert apply_manual_pick(state, 4, "G4", max_picks=1) is None assert allowed_app_ids(state) == {2, 4} - assert state.current_assigned_at == state.manual_picks[-1]["started_at"] + assert ( + state.assignment.current_assigned_at == state.manual_picks[-1]["started_at"] + ) def test_released_pick_can_be_abandoned(self) -> None: """A released pick can be abandoned and the active pick takes over.""" @@ -130,14 +107,24 @@ class TestReleasedPicksStayPlayable: with patch.object(State, "save"): assert abandon_manual_pick(state, 2) is True # The active pick inherits the assignment, timed from its pick. - assert (state.current_app_id, state.current_assigned_at) == (3, STARTED_AT) + assert (state.current_app_id, state.assignment.current_assigned_at) == ( + 3, + STARTED_AT, + ) def test_abandoning_the_last_pick_clears_the_assignment(self) -> None: """Abandoning the only pick clears the assignment.""" - state = State(current_app_id=2, current_assigned_at="T", manual_picks=[pick(2)]) + state = State( + current_app_id=2, + assignment=AssignmentTimes(current_assigned_at="T"), + manual_picks=[pick(2)], + ) with patch.object(State, "save"): abandon_manual_pick(state, 2) - assert (state.current_app_id, state.current_assigned_at) == (None, "") + assert (state.current_app_id, state.assignment.current_assigned_at) == ( + None, + "", + ) class TestPickOrder: @@ -146,10 +133,12 @@ class TestPickOrder: def test_least_recently_assigned_first_then_shortest(self) -> None: """Never-assigned games come first, then the oldest assignment.""" state = State( - last_assigned_at={ - "1": "2026-09-01T00:00:00+00:00", - "2": "2026-08-01T00:00:00+00:00", - } + assignment=AssignmentTimes( + last_assigned_at={ + "1": "2026-09-01T00:00:00+00:00", + "2": "2026-08-01T00:00:00+00:00", + } + ) ) games = [game(1, hours=1.0), game(2, hours=2.0), game(3, hours=9.0)] with patch( @@ -158,82 +147,3 @@ class TestPickOrder: ): order = [g.app_id for g in _open_candidates(games, state)] assert order == [3, 2, 1] - - -class TestTamperingAfterRelease: - """Unlocks after a release are tampering; earlier ones are not.""" - - def entry(self) -> dict[str, object]: - """Return the catalogue entry for the released game.""" - return { - "app_id": 7, - "name": "G7", - "total_achievements": 10, - "unlocked_achievements": 0, - "playtime_minutes": 60, - } - - def check(self, *unlock_times: int) -> tuple[str, int, int] | None: - """Run the tampering check against a refresh with these unlocks.""" - client = MagicMock() - client.refresh_single_game.return_value = game(7, *unlock_times) - state = State(current_app_id=1, released_at={"7": RELEASED.isoformat()}) - return _check_game_tampering(client, self.entry(), state) - - def test_unlocks_earned_while_assigned_are_legitimate(self) -> None: - """Unlocks earned while the game was assigned are legitimate.""" - before = int((RELEASED - timedelta(hours=1)).timestamp()) - assert self.check(before, before) is None - - def test_unlocks_after_release_are_flagged(self) -> None: - """Unlocks made after the release are flagged as tampering.""" - before = int((RELEASED - timedelta(hours=1)).timestamp()) - after = int((RELEASED + timedelta(hours=1)).timestamp()) - assert self.check(before, after) == ("G7", 7, 1) - - def test_unreadable_game_is_not_flagged(self) -> None: - """A game whose refresh fails is not flagged.""" - client = MagicMock() - client.refresh_single_game.return_value = None - assert _check_game_tampering(client, self.entry(), State()) is None - - -class TestCheckCommand: - """The check command applies the one-new-achievement rule.""" - - def run_check(self, state: State, refreshed: GameInfo) -> MagicMock: - """Run do_check with every side effect patched; return the pick mock.""" - client = MagicMock() - client.refresh_single_game.return_value = refreshed - with ( - patch( - "steam_backlog_enforcer.scanning.SteamAPIClient", return_value=client - ), - patch("steam_backlog_enforcer.scanning._echo"), - patch("steam_backlog_enforcer.scanning.report_completion"), - patch("steam_backlog_enforcer.scanning.detect_tampering"), - patch("steam_backlog_enforcer.scanning.send_notification"), - patch("steam_backlog_enforcer.scanning.load_snapshot", return_value=[]), - patch("steam_backlog_enforcer.scanning.pick_next_game") as mock_pick, - patch.object(State, "save"), - ): - do_check(Config(), state) - return mock_pick - - def test_new_achievement_releases_and_keeps_the_game(self) -> None: - """A new achievement releases the game and keeps it assigned.""" - state = State(current_app_id=7, current_assigned_at=RELEASED.isoformat()) - after = int((RELEASED + timedelta(hours=1)).timestamp()) - self.run_check(state, game(7, after)) - assert "7" in state.released_at - assert state.finished_app_ids == [] - # No snapshot, so no replacement: the game stays assigned. - assert state.current_app_id == 7 - - def test_no_new_achievement_changes_nothing(self) -> None: - """No new achievement leaves the state and the pick untouched.""" - state = State(current_app_id=7, current_assigned_at=RELEASED.isoformat()) - before = int((RELEASED - timedelta(hours=1)).timestamp()) - mock_pick = self.run_check(state, game(7, before)) - assert state.released_at == {} - mock_pick.assert_not_called() diff --git a/steam_backlog_enforcer/tests/test_release_tampering.py b/steam_backlog_enforcer/tests/test_release_tampering.py new file mode 100644 index 0000000..5b516f6 --- /dev/null +++ b/steam_backlog_enforcer/tests/test_release_tampering.py @@ -0,0 +1,107 @@ +"""Tampering checks after a game was released, and the check command.""" + +from __future__ import annotations + +from datetime import timedelta +from typing import TYPE_CHECKING +from unittest.mock import MagicMock, patch + +from steam_backlog_enforcer._config_groups import AssignmentTimes +from steam_backlog_enforcer._scanning_tampering import _check_game_tampering +from steam_backlog_enforcer.config import Config, State +from steam_backlog_enforcer.scanning import do_check +from steam_backlog_enforcer.tests._release_helpers import ( + RELEASED, + game, +) + +if TYPE_CHECKING: + from steam_backlog_enforcer.steam_api import GameInfo + + +class TestTamperingAfterRelease: + """Unlocks after a release are tampering; earlier ones are not.""" + + def entry(self) -> dict[str, object]: + """Return the catalogue entry for the released game.""" + return { + "app_id": 7, + "name": "G7", + "total_achievements": 10, + "unlocked_achievements": 0, + "playtime_minutes": 60, + } + + def check(self, *unlock_times: int) -> tuple[str, int, int] | None: + """Run the tampering check against a refresh with these unlocks.""" + client = MagicMock() + client.refresh_single_game.return_value = game(7, *unlock_times) + state = State( + current_app_id=1, + assignment=AssignmentTimes(released_at={"7": RELEASED.isoformat()}), + ) + return _check_game_tampering(client, self.entry(), state) + + def test_unlocks_earned_while_assigned_are_legitimate(self) -> None: + """Unlocks earned while the game was assigned are legitimate.""" + before = int((RELEASED - timedelta(hours=1)).timestamp()) + assert self.check(before, before) is None + + def test_unlocks_after_release_are_flagged(self) -> None: + """Unlocks made after the release are flagged as tampering.""" + before = int((RELEASED - timedelta(hours=1)).timestamp()) + after = int((RELEASED + timedelta(hours=1)).timestamp()) + assert self.check(before, after) == ("G7", 7, 1) + + def test_unreadable_game_is_not_flagged(self) -> None: + """A game whose refresh fails is not flagged.""" + client = MagicMock() + client.refresh_single_game.return_value = None + assert _check_game_tampering(client, self.entry(), State()) is None + + +class TestCheckCommand: + """The check command applies the one-new-achievement rule.""" + + def run_check(self, state: State, refreshed: GameInfo) -> MagicMock: + """Run do_check with every side effect patched; return the pick mock.""" + client = MagicMock() + client.refresh_single_game.return_value = refreshed + with ( + patch( + "steam_backlog_enforcer.scanning.SteamAPIClient", return_value=client + ), + patch("steam_backlog_enforcer.scanning._echo"), + patch("steam_backlog_enforcer.scanning.report_completion"), + patch("steam_backlog_enforcer.scanning.detect_tampering"), + patch("steam_backlog_enforcer.scanning.send_notification"), + patch("steam_backlog_enforcer.scanning.load_snapshot", return_value=[]), + patch("steam_backlog_enforcer.scanning.pick_next_game") as mock_pick, + patch.object(State, "save"), + ): + do_check(Config(), state) + return mock_pick + + def test_new_achievement_releases_and_keeps_the_game(self) -> None: + """A new achievement releases the game and keeps it assigned.""" + state = State( + current_app_id=7, + assignment=AssignmentTimes(current_assigned_at=RELEASED.isoformat()), + ) + after = int((RELEASED + timedelta(hours=1)).timestamp()) + self.run_check(state, game(7, after)) + assert "7" in state.assignment.released_at + assert state.finished_app_ids == [] + # No snapshot, so no replacement: the game stays assigned. + assert state.current_app_id == 7 + + def test_no_new_achievement_changes_nothing(self) -> None: + """No new achievement leaves the state and the pick untouched.""" + state = State( + current_app_id=7, + assignment=AssignmentTimes(current_assigned_at=RELEASED.isoformat()), + ) + before = int((RELEASED - timedelta(hours=1)).timestamp()) + mock_pick = self.run_check(state, game(7, before)) + assert state.assignment.released_at == {} + mock_pick.assert_not_called() diff --git a/steam_backlog_enforcer/tests/test_status_api_stamp.py b/steam_backlog_enforcer/tests/test_status_api_stamp.py index ba96e37..4e21907 100644 --- a/steam_backlog_enforcer/tests/test_status_api_stamp.py +++ b/steam_backlog_enforcer/tests/test_status_api_stamp.py @@ -151,7 +151,7 @@ class TestWorkoutLogPath: def test_expands_the_home_directory(self) -> None: """A ~ in the configured path expands to the home directory.""" config = Config() - config.workout_log_path = "~/locker/log.json" + config.earn.workout_log_path = "~/locker/log.json" assert workout_log_path(config) == Path.home() / "locker" / "log.json" def test_default_points_at_screen_locker(self) -> None: diff --git a/steam_backlog_enforcer/tests/test_workout_budget.py b/steam_backlog_enforcer/tests/test_workout_budget.py index cd5aaf1..bd64486 100644 --- a/steam_backlog_enforcer/tests/test_workout_budget.py +++ b/steam_backlog_enforcer/tests/test_workout_budget.py @@ -52,9 +52,9 @@ def _config(**over: object) -> Config: A Config instance; never loaded from or saved to disk. """ config = Config() - config.workout_status_url = "http://127.0.0.1:8770/api/status" + config.earn.workout_status_url = "http://127.0.0.1:8770/api/status" for key, value in over.items(): - setattr(config, key, value) + setattr(config.earn, key, value) return config