steam-backlog-enforcer/steam_backlog_enforcer/tests/test_playtime_attribution.py
Krzysztof kuhy Rudnicki 1faf211767 Show which games make up the gaming budget, and bill osu!lazer
The budget tab answered "how much did I play" but not "what did I play":
playtime_state.json and playtime_history.json each stored one aggregate
seconds figure per gaming day, so the 14-day chart was a row of featureless
bars. Separately, qualifying_pids had exactly two sources — the SteamAppId
env var and a hardcoded 16-launcher frozenset — so osu!lazer, which sets no
SteamAppId and matches no launcher name, was never billed at all.

qualifying_pids now returns pid -> attribution key instead of a bare pid set.
The app id was already in hand and thrown away on its first line; it now
survives into PlaytimeState.per_game, alongside a user-editable
counted_processes list in config.json seeded with osu!lazer.

Two things the parts/whole relationship forces:

  - per_game only ever sums to AT MOST seconds, never equals it. backdate
    refunds the idle grace on every engaged-to-paused edge, and
    _state_or_recover synthesises a full budget with no breakdown. The
    refund is debited from last_credited_key, and the remainder is rendered
    as "Unattributed" rather than stored — one path then covers legacy days,
    focus-probe failures and drift alike.

  - counted_processes is kept apart from LAUNCHER_PROCESS_NAMES. That
    frozenset is also the total-block kill list, and it routes through
    kill_and_uninstall_launchers, which pacman -R's the owning package.
    Counted entries are killed on total block, never uninstalled.

Both storage formats stay at schema 1: load_state already filters to
dataclass fields, so a record without per_game migrates for free, and the
history reader has to accept both a bare float and an object regardless, so
a version bump would distinguish nothing.

Chart segments use the shared design system's categorical ramp (--cat-1..6),
capped at six games plus "Other" because a seventh distinguishable hue does
not exist under simulated CVD. The red over-budget fill is gone: colour now
encodes which game, and the dashed budget line alone says over or under.

Snapshot persistence moves to _snapshot.py to keep config.py under the
250-line cap. Three modules bound config paths at import time, which
bypasses the conftest redirect — they now reach them through the module.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MKFzwzwRU1JD7SFLHtQBsz
2026-08-29 18:32:03 +02:00

213 lines
8.3 KiB
Python

"""Tests for who a billed tick belongs to — 100% branch coverage.
Split from ``test_playtime_procs`` at the 250-line cap. This file owns the
attribution dimension: which PIDs qualify, and which single game a tick is
credited to. ``test_playtime_procs`` keeps the /proc plumbing.
"""
from __future__ import annotations
from unittest.mock import patch
from steam_backlog_enforcer._counted_procs import CountedProcess
from steam_backlog_enforcer._playtime_procs import attributed_key, qualifying_pids
from steam_backlog_enforcer._playtime_state import rules_for
from steam_backlog_enforcer.config import Config
class TestQualifyingPids:
"""`qualifying_pids` returns pid -> attribution key, not a bare pid set."""
def test_steam_games_only_when_launchers_are_off(self) -> None:
rules = rules_for(Config(count_launcher_processes=False), demo=False)
with (
patch(
"steam_backlog_enforcer._playtime_procs.get_running_steam_game_pids",
return_value={5: 440, 6: 0},
),
patch(
"steam_backlog_enforcer._playtime_procs.load_counted_processes",
return_value=(),
),
patch(
"steam_backlog_enforcer._playtime_procs.get_pids_by_process_names"
) as mock_comm,
):
assert qualifying_pids(rules) == {5: "app:440"}
mock_comm.assert_not_called()
def test_steam_client_appid_zero_does_not_count(self) -> None:
"""Browsing the store is not gaming."""
rules = rules_for(Config(count_launcher_processes=False), demo=False)
with (
patch(
"steam_backlog_enforcer._playtime_procs.get_running_steam_game_pids",
return_value={9: 0},
),
patch(
"steam_backlog_enforcer._playtime_procs.load_counted_processes",
return_value=(),
),
):
assert qualifying_pids(rules) == {}
def test_unions_launchers_from_both_scanners(self) -> None:
rules = rules_for(Config(count_launcher_processes=True), demo=False)
with (
patch(
"steam_backlog_enforcer._playtime_procs.get_running_steam_game_pids",
return_value={5: 440},
),
patch(
"steam_backlog_enforcer._playtime_procs.load_counted_processes",
return_value=(),
),
patch(
"steam_backlog_enforcer._playtime_procs.get_pids_by_process_names",
return_value={7: "heroic"},
),
patch(
"steam_backlog_enforcer._playtime_procs.get_pids_by_cmdline_names",
return_value={8: "lutris"},
),
):
assert qualifying_pids(rules) == {
5: "app:440",
7: "launcher:heroic",
8: "launcher:lutris",
}
def test_counted_processes_bill_even_with_launchers_off(self) -> None:
"""The user's own list is not gated on the launcher switch.
Turning launcher counting off because a launcher idles in the tray must
not silently stop billing a game the user explicitly listed.
"""
rules = rules_for(Config(count_launcher_processes=False), demo=False)
with (
patch(
"steam_backlog_enforcer._playtime_procs.get_running_steam_game_pids",
return_value={},
),
patch(
"steam_backlog_enforcer._playtime_procs.load_counted_processes",
return_value=(
CountedProcess(
id="osu-lazer", label="osu!lazer", names=frozenset({"osu!"})
),
),
),
patch(
"steam_backlog_enforcer._playtime_procs.get_pids_by_process_names",
return_value={11: "osu!"},
),
patch(
"steam_backlog_enforcer._playtime_procs.get_pids_by_cmdline_names",
return_value={},
),
):
assert qualifying_pids(rules) == {11: "proc:osu-lazer"}
def test_steam_attribution_wins_over_a_name_match(self) -> None:
"""A Steam game keeps its app key even if its comm matches a launcher."""
rules = rules_for(Config(count_launcher_processes=True), demo=False)
with (
patch(
"steam_backlog_enforcer._playtime_procs.get_running_steam_game_pids",
return_value={7: 440},
),
patch(
"steam_backlog_enforcer._playtime_procs.load_counted_processes",
return_value=(),
),
patch(
"steam_backlog_enforcer._playtime_procs.get_pids_by_process_names",
return_value={7: "heroic"},
),
patch(
"steam_backlog_enforcer._playtime_procs.get_pids_by_cmdline_names",
return_value={},
),
):
assert qualifying_pids(rules) == {7: "app:440"}
def test_a_name_outside_the_map_is_skipped(self) -> None:
"""Unreachable in production; a KeyError in the enforce loop is not."""
rules = rules_for(Config(count_launcher_processes=True), demo=False)
with (
patch(
"steam_backlog_enforcer._playtime_procs.get_running_steam_game_pids",
return_value={},
),
patch(
"steam_backlog_enforcer._playtime_procs.load_counted_processes",
return_value=(),
),
patch(
"steam_backlog_enforcer._playtime_procs.get_pids_by_process_names",
return_value={12: "not-a-launcher"},
),
patch(
"steam_backlog_enforcer._playtime_procs.get_pids_by_cmdline_names",
return_value={},
),
):
assert qualifying_pids(rules) == {}
def test_no_processes_at_all(self) -> None:
rules = rules_for(Config(), demo=False)
with (
patch(
"steam_backlog_enforcer._playtime_procs.get_running_steam_game_pids",
return_value={},
),
patch(
"steam_backlog_enforcer._playtime_procs.get_pids_by_process_names",
return_value={},
),
patch(
"steam_backlog_enforcer._playtime_procs.get_pids_by_cmdline_names",
return_value={},
),
):
assert qualifying_pids(rules) == {}
class TestAttributedKey:
"""Deciding which single game a tick belongs to."""
_PKG = "steam_backlog_enforcer._playtime_procs"
def test_focused_pid_wins(self) -> None:
assert attributed_key({7: "app:440", 8: "proc:osu"}, 8) == "proc:osu"
def test_walks_up_to_the_owning_process(self) -> None:
"""A Proton game's window belongs to a child of the SteamAppId process."""
with patch(f"{self._PKG}._read_ppid", side_effect=[900, 7]):
assert attributed_key({7: "app:440"}, 999) == "app:440"
def test_gives_up_when_the_chain_ends(self) -> None:
with patch(f"{self._PKG}._read_ppid", return_value=None):
assert attributed_key({7: "app:440", 8: "app:1"}, 999) == ""
def test_stops_at_init(self) -> None:
with patch(f"{self._PKG}._read_ppid", return_value=1):
assert attributed_key({7: "app:440", 8: "app:1"}, 999) == ""
def test_stops_after_the_depth_limit(self) -> None:
"""A ppid cycle must not spin the enforce loop."""
with patch(f"{self._PKG}._read_ppid", return_value=500):
assert attributed_key({7: "app:440", 8: "app:1"}, 500) == ""
def test_falls_back_to_the_only_game_running(self) -> None:
"""Covers no X, or a toolkit that omits _NET_WM_PID."""
assert attributed_key({7: "app:440", 8: "app:440"}, None) == "app:440"
def test_two_games_and_no_focus_is_unattributable(self) -> None:
# There is no honest answer, so the tick still bills but the gap shows
# up as Unattributed rather than being charged to a guess.
assert attributed_key({7: "app:440", 8: "app:1"}, None) == ""
def test_nothing_qualifying(self) -> None:
assert attributed_key({}, None) == ""