steam-backlog-enforcer/_installer_import/tests/test_cli.py
Krzysztof kuhy Rudnicki aaf9c18a8a fix(recognize): stop Steam re-downloading after a hand-finished install
The KCD2 run reported success but Steam re-downloaded 90 GB anyway. Two
independent causes, plus a defect that hid both.

force_install_dir sets a Steam *library root*, not an install directory.
Pointing it at the game folder made steamcmd search <game>/steamapps/ for
manifests ("Loaded 0 apps from install folder"), create that stray dir, and
fail the app with "Invalid platform" for lack of depot context. Dropped it;
the app already lives in a registered library. Separately, a Linux steamcmd
needs +@sSteamCmdForcePlatformType windows for a Windows-only title.

Steam then discarded the manifest because it was self-contradictory:
StateFlags=4 while BytesDownloaded (22 GB) != BytesToDownload (92 GB), with
tens of GB still staged under steamapps/downloading/. Across every genuinely
installed manifest the byte counters are equal in pairs, StagingSize is 0 and
staging is empty; DownloadType is kept, not dropped. Settle all of it, and
refuse to call an install real until it holds.

The defect that hid this: steamcmd exited 8 having done nothing and the tool
still wrote StateFlags=4, printed a success line and returned 0. Now gated on
depotdownloader succeeding, every required depot being cached, real game
content on disk, a matching buildid and no running Steam client -- and it
re-reads the manifest after writing.

Also fixes data corruption found in review: vdf.dumps never re-escaped
backslashes, so each parse/dump cycle halved them and silently mangled the
Windows paths in appmanifest_228980.acf's InstallScripts. Manifest writes are
now atomic with a preserved pristine .acf.bak.

Adds per-run logging to ~/.local/state/steam-game-installer (argv, exit codes,
full subprocess output, manifest before/after), teed through a pty so
steamcmd's password prompt still works.

Verified end-to-end on KCD2: Steam logged "Fully Installed, App Running" and
the game launched with no download queued. Coverage 100% statements+branches,
enforced by fail_under.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EK4urCmbTqN4Vrc3nGBcXF
2026-08-05 10:11:34 +02:00

329 lines
11 KiB
Python

"""End-to-end-ish tests for the CLI's decision logic.
The bug that motivated all of this lived here, not in the manifest writer:
steamcmd died instantly having done nothing, and main() still wrote
StateFlags=4, printed "launch Steam and confirm Play works" and returned 0.
These tests pin the fail-closed behaviour.
"""
import logging
import subprocess
import sys
import pytest
from steam_installer import appinfo, cli, recognize, resolve, runlog, vdf
from steam_installer.library import SteamLibrary
@pytest.fixture(autouse=True)
def isolated_logs(tmp_path, monkeypatch):
monkeypatch.setattr(runlog, "LOG_DIR", tmp_path / "state")
yield
logger = logging.getLogger(runlog.LOGGER_NAME)
for handler in list(logger.handlers):
logger.removeHandler(handler)
handler.close()
@pytest.fixture
def steam(tmp_path, monkeypatch):
"""A Steam tree with KCD2 downloaded but its manifest not yet finished."""
root = tmp_path / "Steam"
library = SteamLibrary(root)
install_dir = library.common / "KingdomComeDeliverance2"
cache = install_dir / ".DepotDownloader"
cache.mkdir(parents=True)
(cache / "1771303_1999516201078544527.manifest").write_bytes(b"x")
(install_dir / "game.pak").write_bytes(b"x" * 1000)
library.steamapps.mkdir(parents=True, exist_ok=True)
(library.steamapps / "appmanifest_1771300.acf").write_text(
vdf.dumps(
"AppState",
{
"appid": "1771300",
"StateFlags": "1026",
"buildid": "23914554",
"BytesToDownload": "92009052960",
"BytesDownloaded": "22129058224",
},
)
)
monkeypatch.setattr(cli, "find_steam_root", lambda: root)
monkeypatch.setattr(cli, "list_libraries", lambda r: [library])
monkeypatch.setattr(cli, "pick_install_target", lambda libs, d: install_dir)
monkeypatch.setattr(cli.shutil, "which", lambda name: f"/usr/bin/{name}")
monkeypatch.setattr(
cli.appinfo,
"get_metadata",
lambda appid: appinfo.AppMetadata(appid, "KCD2", "KingdomComeDeliverance2"),
)
monkeypatch.setattr(
cli.appinfo,
"get_depot_plan",
lambda appid, language: appinfo.DepotPlan({"1771303"}, {"228989"}),
)
monkeypatch.setattr(cli.appinfo, "get_build_id", lambda appid: "23914554")
monkeypatch.setattr(recognize, "steam_client_pids", lambda: [])
monkeypatch.setattr(cli.recognize, "steam_client_pids", lambda: [])
monkeypatch.setattr("builtins.input", lambda *a: "y")
return library, install_dir
ARGV = ["--appid", "1771300", "--username", "u", "--language", "english"]
def _stub_download(monkeypatch, returncode=0):
monkeypatch.setattr(cli.depotdl, "download", lambda **kw: returncode)
def _stub_steamcmd(monkeypatch, returncode, crashed=False):
monkeypatch.setattr(
cli.recognize,
"run_steamcmd_validate",
lambda appid, username, logger: recognize.ValidateResult(
completed=returncode == 0,
crashed_on_install_script=crashed,
returncode=returncode,
),
)
def test_dead_steamcmd_run_still_finishes_when_content_is_present(steam, monkeypatch):
"""steamcmd failing is survivable -- the content is what matters -- but the
manifest must come out consistent, not merely flagged installed."""
library, install_dir = steam
_stub_download(monkeypatch)
_stub_steamcmd(monkeypatch, returncode=8)
assert cli.main(ARGV) == 0
app_state = recognize.read_app_state(library.steamapps / "appmanifest_1771300.acf")
assert app_state["StateFlags"] == "4"
assert app_state["BytesDownloaded"] == app_state["BytesToDownload"]
assert recognize.download_counters_settled(app_state)
def test_refuses_when_a_required_depot_never_downloaded(steam, monkeypatch):
"""The exact fail-open case: nothing was really downloaded, so declaring the
app installed would be a fabricated success."""
library, install_dir = steam
_stub_download(monkeypatch)
_stub_steamcmd(monkeypatch, returncode=8)
monkeypatch.setattr(
cli.appinfo,
"get_depot_plan",
lambda appid, language: appinfo.DepotPlan({"1771303", "9999999"}, set()),
)
assert cli.main(ARGV) == 1
app_state = recognize.read_app_state(library.steamapps / "appmanifest_1771300.acf")
assert app_state["StateFlags"] == "1026"
def test_refuses_when_depotdownloader_fails(steam, monkeypatch):
library, _ = steam
_stub_download(monkeypatch, returncode=1)
_stub_steamcmd(monkeypatch, returncode=0)
assert cli.main(ARGV) == 1
app_state = recognize.read_app_state(library.steamapps / "appmanifest_1771300.acf")
assert app_state["StateFlags"] == "1026"
def test_refuses_before_downloading_when_steam_is_running(steam, monkeypatch):
"""Steam owns the manifest while it runs; refuse up front rather than after
an hour of downloading."""
library, _ = steam
monkeypatch.setattr(cli.recognize, "steam_client_pids", lambda: [4242])
called = []
monkeypatch.setattr(cli.depotdl, "download", lambda **kw: called.append(1) or 0)
assert cli.main(ARGV) == 1
assert called == []
def test_clean_steamcmd_run_short_circuits(steam, monkeypatch):
"""If steamcmd genuinely finished the job, don't hand-patch anything."""
library, install_dir = steam
_stub_download(monkeypatch)
def fake_validate(appid, username, logger):
(library.steamapps / "appmanifest_1771300.acf").write_text(
vdf.dumps(
"AppState",
{
"StateFlags": "4",
"installdir": "KingdomComeDeliverance2",
"InstalledDepots": {"1771303": {"manifest": "1"}},
"BytesToDownload": "1",
"BytesDownloaded": "1",
},
)
)
return recognize.ValidateResult(True, False, 0)
monkeypatch.setattr(cli.recognize, "run_steamcmd_validate", fake_validate)
called = []
monkeypatch.setattr(
cli.recognize,
"finish_manifest_manually",
lambda **kw: called.append(1),
)
assert cli.main(ARGV) == 0
assert called == []
def test_user_declining_confirmation_aborts(steam, monkeypatch):
monkeypatch.setattr("builtins.input", lambda *a: "n")
called = []
monkeypatch.setattr(cli.depotdl, "download", lambda **kw: called.append(1) or 0)
assert cli.main(ARGV) == 1
assert called == []
def test_unhandled_error_returns_nonzero_and_names_the_log(steam, monkeypatch, capsys):
def boom(**kwargs):
raise RuntimeError("depotdownloader exploded")
monkeypatch.setattr(cli.depotdl, "download", boom)
assert cli.main(ARGV) == 1
assert "Run log" in capsys.readouterr().out
def test_requires_a_name_or_appid():
with pytest.raises(SystemExit):
cli.main(["--username", "u"])
def test_missing_manifest_under_skip_steamcmd_does_not_blame_steamcmd(
steam, monkeypatch, capsys
):
"""--skip-steamcmd never runs steamcmd, so "steamcmd never ran far enough"
would send the user chasing the wrong thing."""
library, _ = steam
(library.steamapps / "appmanifest_1771300.acf").unlink()
_stub_download(monkeypatch)
assert cli.main([*ARGV, "--skip-steamcmd"]) == 1
out = capsys.readouterr().out
assert "never fabricates one" in out
assert "Re-run without --skip-steamcmd" in out
assert "steamcmd never ran far enough" not in out
def test_missing_manifest_with_steamcmd_blames_steamcmd(steam, monkeypatch, capsys):
library, _ = steam
(library.steamapps / "appmanifest_1771300.acf").unlink()
_stub_download(monkeypatch)
_stub_steamcmd(monkeypatch, returncode=8)
assert cli.main(ARGV) == 1
assert "steamcmd never ran far enough" in capsys.readouterr().out
def test_require_tool_exits_when_binary_missing(monkeypatch, capsys):
monkeypatch.setattr(cli.shutil, "which", lambda name: None)
with pytest.raises(SystemExit):
cli._require_tool("depotdownloader", "See ~/depotdownloader.")
assert "not found on PATH" in capsys.readouterr().err
def test_resolve_appid_uses_search_when_no_appid(monkeypatch):
monkeypatch.setattr(
cli.resolve, "search", lambda name: [resolve.SearchResult(1771300, "KCD2")]
)
monkeypatch.setattr(cli.resolve, "prompt_confirm", lambda results: results[0])
args = cli._build_parser().parse_args(["kingdom", "--username", "u"])
assert cli._resolve_appid(args) == 1771300
def test_resolve_appid_exits_when_search_unavailable(monkeypatch, capsys):
"""store.steampowered.com blocks scripted clients on some networks; tell the
user to pass --appid rather than dying with a traceback."""
def boom(name):
raise resolve.SearchUnavailable("tls blocked")
monkeypatch.setattr(cli.resolve, "search", boom)
args = cli._build_parser().parse_args(["kingdom", "--username", "u"])
with pytest.raises(SystemExit):
cli._resolve_appid(args)
assert "pass --appid" in capsys.readouterr().err
def test_language_defaults_to_english_when_prompt_is_empty(steam, monkeypatch):
seen = {}
monkeypatch.setattr("builtins.input", lambda *a: "y" if "Proceed" in a[0] else "")
monkeypatch.setattr(
cli.appinfo,
"get_depot_plan",
lambda appid, language: (
seen.setdefault("language", language)
and None
or appinfo.DepotPlan({"1771303"}, set())
),
)
_stub_download(monkeypatch)
_stub_steamcmd(monkeypatch, returncode=8)
cli.main(["--appid", "1771300", "--username", "u"])
assert seen["language"] == "english"
def test_reports_the_known_install_script_crash(steam, monkeypatch, capsys):
_stub_download(monkeypatch)
_stub_steamcmd(monkeypatch, returncode=-11, crashed=True)
assert cli.main(ARGV) == 0
assert "known install-script crash" in capsys.readouterr().out
def test_reports_cleared_staging(steam, monkeypatch, capsys):
library, _ = steam
staged = library.steamapps / "downloading" / "1771300"
staged.mkdir(parents=True)
(staged / "big.pak").write_bytes(b"x" * 2_000_000)
_stub_download(monkeypatch)
_stub_steamcmd(monkeypatch, returncode=8)
assert cli.main(ARGV) == 0
assert "stale Steam staging data" in capsys.readouterr().out
def test_fails_when_written_manifest_does_not_read_back_as_installed(
steam, monkeypatch, capsys
):
"""Claiming success without re-reading the write is the same fail-open
mistake in a different place."""
_stub_download(monkeypatch)
_stub_steamcmd(monkeypatch, returncode=8)
monkeypatch.setattr(
cli.recognize, "manifest_reflects_real_install", lambda *a, **kw: False
)
assert cli.main(ARGV) == 1
assert "does not read back as a real install" in capsys.readouterr().out
def test_module_is_runnable_as_a_script(coverage_subprocess_env):
"""`python -m steam_installer.cli` is a real entry point (the __main__
guard), so it must not be dead code."""
result = subprocess.run(
[sys.executable, "-m", "steam_installer.cli", "--help"],
capture_output=True,
text=True,
timeout=60,
env=coverage_subprocess_env,
)
assert result.returncode == 0
assert "--skip-steamcmd" in result.stdout