diff --git a/_installer_import/.gitignore b/_installer_import/.gitignore index 76180b2..472098a 100644 --- a/_installer_import/.gitignore +++ b/_installer_import/.gitignore @@ -3,3 +3,5 @@ __pycache__/ *.pyc .pytest_cache/ *.egg-info/ +.coverage +.coverage.* diff --git a/_installer_import/README.md b/_installer_import/README.md new file mode 100644 index 0000000..550e0ee --- /dev/null +++ b/_installer_import/README.md @@ -0,0 +1,105 @@ +# steam-game-installer + +Download an owned Steam game with `depotdownloader` (which saturates a link far +better than the Steam client), then make the Steam client accept the result as +a real install so **Play** works. + +```bash +./install.sh # checks depotdownloader + steamcmd are present +pip install -e . +steam-game-installer --appid 1771300 --username +``` + +**Close the Steam client first.** Steam owns `appmanifest_.acf` while it +runs and rewrites it from its own in-memory state, so anything written +underneath a live client is discarded. The tool refuses to start if it sees one. + +## Run logs + +Every run writes a full log: + +``` +~/.local/state/steam-game-installer/run--.log +~/.local/state/steam-game-installer/latest.log -> most recent +``` + +The path is printed at the start and end of every run, and on every error path. +It contains the full argv, exit code and complete output of each subprocess, the +manifest verbatim before and after every write, the depot cache listing, +expected-vs-actual depots, and whether Steam was running. Send `latest.log` when +something goes wrong. `--verbose` mirrors all of it to the console. + +Subprocess output is teed through a pty rather than captured, because steamcmd +only prompts for a password / Steam Guard code when it believes it is on a +terminal — with a plain pipe the prompt never appears and the run looks hung. + +## How it works + +1. `depotdownloader` pulls the content (fast path). +2. `steamcmd app_update validate` reconciles Steam's own bookkeeping. +3. If that fails or leaves the manifest incomplete, the manifest is finished by + hand — but only when every precondition below holds. + +## Fail-closed preconditions + +The tool refuses to mark an app installed, and exits non-zero, unless: + +- `depotdownloader` exited 0; +- every required depot has a cached manifest under `.DepotDownloader/` + (required = this app's depots for the chosen language and OS, excluding DLC, + optional and shared depots — KCD2 lists 12 depots but an english/windows + install only ever fetches 3); +- the manifest carries a real `buildid` matching the current public build; +- no Steam client is running; +- the manifest reads back as a real install *after* being written. + +This matters: an earlier version wrote `StateFlags=4` and reported success after +a steamcmd run that had done nothing at all. + +## Failure modes this encodes + +Each of these cost a real debugging session; the tests pin them. + +**`force_install_dir` is a library root, not an install directory.** Pointing it +at the game folder made steamcmd look for manifests in `/steamapps/`, find +none (`Loaded 0 apps from install folder`), create that stray directory, and then +fail the app with `Invalid platform` — it had no depot context for the app. +Dropped entirely: the app already lives in a registered library. + +**A Linux steamcmd needs `+@sSteamCmdForcePlatformType windows`** (before +`+login`) for a Windows-only game, or it resolves depots against the host OS. + +**Steam rejects an internally inconsistent manifest.** A file that says +`StateFlags=4` while `BytesDownloaded` (22 GB) still differs from +`BytesToDownload` (92 GB) is self-contradictory; Steam discards the "installed" +claim and resumes downloading. Across every genuinely installed manifest the +counters are equal in pairs and `StagingSize` is `0`. `DownloadType` is *kept* — +it is present on every real install, so removing it is not the fix. + +**Staging must be cleared too.** Steam stages chunks in +`steamapps/downloading//`. Declaring the app installed while tens of GB +sit there pending makes Steam resume the update. Installed apps have an empty +(4 KB) staging dir. + +**Shared depots are not installed depots.** `228989` belongs to app 228980 +(Steamworks Common Redistributables); listing it in `InstalledDepots` +contradicts `SharedDepots`. + +**`SizeOnDisk` excludes `.DepotDownloader/`** — its cache and staging tree are +not game content and overstate the total by gigabytes. + +## Development + +```bash +./install.sh # also prepares the test env +.venv/bin/python -m pytest tests/ -q +ruff check steam_installer/ tests/ +ruff format --check steam_installer/ tests/ +``` + +Coverage is enforced at **100% of statements and branches** +(`fail_under = 100`), so an uncovered line fails the suite rather than quietly +lowering a number. One test runs `python -m steam_installer.cli` in a +subprocess to prove the `__main__` entry point works; recording coverage from +a child process needs a `.pth` that calls `coverage.process_startup()`, which +`install.sh` writes into the venv. Skip `install.sh` and coverage reports 99%. diff --git a/_installer_import/install.sh b/_installer_import/install.sh index 54cd179..e41cbe9 100755 --- a/_installer_import/install.sh +++ b/_installer_import/install.sh @@ -5,6 +5,9 @@ set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +readonly SCRIPT_DIR + missing=0 if ! command -v depotdownloader >/dev/null 2>&1; then @@ -17,8 +20,31 @@ if ! command -v steamcmd >/dev/null 2>&1; then missing=1 fi +setup_dev_env() { + # The test suite requires 100% coverage (pyproject: fail_under = 100), and + # one test runs `python -m steam_installer.cli` in a subprocess. Coverage in + # a child process is only recorded if it calls coverage.process_startup() at + # interpreter start, which is what this .pth does. Without it a clean clone + # reports 99% and the suite fails. + local venv="${SCRIPT_DIR}/.venv" + [[ -d "$venv" ]] || return 0 + + local python="${venv}/bin/python" + "$python" -m pip install -q -e "${SCRIPT_DIR}[dev]" 2>/dev/null || + "$python" -m pip install -q -e "$SCRIPT_DIR" pytest pytest-cov + + local site_packages + site_packages="$("$python" -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])')" + cat >"${site_packages}/steam_installer_coverage.pth" <<-'PTH' + import os, coverage; os.environ.get("COVERAGE_PROCESS_START") and coverage.process_startup() + PTH + echo "Dev environment ready (subprocess coverage enabled)." +} + if [[ "$missing" -eq 0 ]]; then echo "All dependencies present." fi +setup_dev_env + exit "$missing" diff --git a/_installer_import/pyproject.toml b/_installer_import/pyproject.toml index 6c9315a..43b0307 100644 --- a/_installer_import/pyproject.toml +++ b/_installer_import/pyproject.toml @@ -14,3 +14,18 @@ build-backend = "setuptools.build_meta" [tool.pytest.ini_options] testpaths = ["tests"] + +[tool.coverage.run] +source = ["steam_installer"] +branch = true +# The `__main__` guard is exercised by running the module as a script in a +# subprocess; without this its coverage would be recorded in a child process +# and thrown away. +parallel = true +concurrency = ["multiprocessing"] + +[tool.coverage.report] +# The suite covers every line and branch. Anything less is a regression, so +# make it fail rather than merely reporting a lower number. +fail_under = 100 +show_missing = true diff --git a/_installer_import/steam_installer/appinfo.py b/_installer_import/steam_installer/appinfo.py index 9a9a081..a238382 100644 --- a/_installer_import/steam_installer/appinfo.py +++ b/_installer_import/steam_installer/appinfo.py @@ -20,9 +20,37 @@ class AppMetadata: installdir: str +@dataclass +class DepotPlan: + """Which depots a given (os, language) install is actually supposed to contain. + + Needed to check that a download finished. "Every depot in app_info" is the + wrong bar: KCD2 lists 12 depots but an english/windows install only ever + fetches 3 of them, the rest being other languages, DLC and other platforms. + """ + + required: set[str] + shared: set[str] + + @property + def all_expected(self) -> set[str]: + return self.required | self.shared + + def _fetch_app_block(appid: int) -> dict: result = subprocess.run( - ["steamcmd", "+login", "anonymous", "+app_info_print", str(appid), "+quit"], + [ + "steamcmd", + # Without this, a Linux steamcmd resolves a Windows-only app's depot + # list against the host platform and can come back empty. + "+@sSteamCmdForcePlatformType", + "windows", + "+login", + "anonymous", + "+app_info_print", + str(appid), + "+quit", + ], capture_output=True, text=True, timeout=60, @@ -59,3 +87,56 @@ def get_metadata(appid: int) -> AppMetadata: raise AppInfoError(f"no installdir field found for app {appid}") return AppMetadata(appid=appid, name=name, installdir=installdir) + + +def get_build_id(appid: int, branch: str = "public") -> str | None: + """Current buildid for `branch`, used to sanity-check the manifest we write.""" + app_block = _fetch_app_block(appid) + depots = app_block.get("depots", {}) + if not isinstance(depots, dict): + return None + branches = depots.get("branches", {}) + if not isinstance(branches, dict): + return None + entry = branches.get(branch, {}) + if not isinstance(entry, dict): + return None + build_id = entry.get("buildid") + return build_id if isinstance(build_id, str) else None + + +def get_depot_plan( + appid: int, language: str = "english", os_name: str = "windows" +) -> DepotPlan: + """Depots an (os, language) install should end up with. + + Skips depots belonging to another language, another OS, a DLC (`dlcappid`) + or marked `optional` -- none of those are fetched by a default install, so + demanding them would make a healthy download look incomplete. + """ + app_block = _fetch_app_block(appid) + depots = app_block.get("depots", {}) + if not isinstance(depots, dict): + raise AppInfoError(f"no 'depots' section in app info for {appid}") + + required: set[str] = set() + shared: set[str] = set() + for depot_id, entry in depots.items(): + if not depot_id.isdigit() or not isinstance(entry, dict): + continue + # A shared depot is installed once under its owning app, not here. + if "depotfromapp" in entry or "sharedinstall" in entry: + shared.add(depot_id) + continue + if entry.get("dlcappid") or entry.get("optional") == "1": + continue + config = entry.get("config", {}) + config = config if isinstance(config, dict) else {} + oslist = config.get("oslist") + if isinstance(oslist, str) and oslist and os_name not in oslist.split(","): + continue + depot_language = config.get("language") + if isinstance(depot_language, str) and depot_language != language: + continue + required.add(depot_id) + return DepotPlan(required=required, shared=shared) diff --git a/_installer_import/steam_installer/cli.py b/_installer_import/steam_installer/cli.py index 1bf92fc..7cbb849 100644 --- a/_installer_import/steam_installer/cli.py +++ b/_installer_import/steam_installer/cli.py @@ -6,9 +6,15 @@ import argparse import shutil import sys import time +from pathlib import Path -from steam_installer import appinfo, depotdl, recognize, resolve -from steam_installer.library import find_steam_root, list_libraries, pick_install_target +from steam_installer import appinfo, depotdl, recognize, resolve, runlog +from steam_installer.library import ( + SteamLibrary, + find_steam_root, + list_libraries, + pick_install_target, +) def _require_tool(name: str, install_hint: str) -> None: @@ -40,7 +46,7 @@ def _resolve_appid(args: argparse.Namespace) -> int: return chosen.appid -def main(argv: list[str] | None = None) -> int: +def _build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description="Download an owned Steam game fast, then make Steam recognize it." ) @@ -66,47 +72,115 @@ def main(argv: list[str] | None = None) -> int: "already confirmed to work." ), ) + parser.add_argument( + "--verbose", + action="store_true", + help="Show on the console everything that goes to the run log.", + ) + return parser + + +def main(argv: list[str] | None = None) -> int: + parser = _build_parser() args = parser.parse_args(argv) if args.appid is None and args.name is None: parser.error("provide a game name to search for, or --appid directly") + log = runlog.setup(args.appid, verbose=args.verbose) + logger = log.logger + # Printed up front as well as at the end: if the run dies badly, the path + # still has to be on screen to copy-paste. + logger.info("Run log: %s", log.path) + logger.debug("argv: %s", sys.argv) + + try: + return _run(args, log) + except Exception: + logger.exception("Run failed with an unhandled error") + logger.info("Run log (send this): %s", log.path) + return 1 + + +def _run(args: argparse.Namespace, log: runlog.RunLog) -> int: + logger = log.logger + _require_tool("depotdownloader", "See ~/depotdownloader.") if not args.skip_steamcmd: _require_tool("steamcmd", "Run: yay -S steamcmd") appid = _resolve_appid(args) metadata = appinfo.get_metadata(appid) - print(f"Confirmed: {metadata.name} (appid {metadata.appid})") + logger.info("Confirmed: %s (appid %s)", metadata.name, metadata.appid) answer = input("Proceed? [y/N]: ").strip().lower() if answer != "y": - print("Cancelled.") + logger.info("Cancelled.") return 1 steam_root = find_steam_root() libraries = list_libraries(steam_root) target = pick_install_target(libraries, metadata.installdir) - print(f"Install target: {target}") + logger.info("Install target: %s", target) language = args.language if language is None: language = input("Language [english]: ").strip() or "english" - print("Downloading via depotdownloader (fast path)...") - depotdl.download( + # Refuse early rather than after an hour of downloading: a live Steam client + # rewrites the manifest from its own state and discards whatever we write. + running = recognize.steam_client_pids() + if running: + logger.error( + "The Steam client is running (pid %s). It owns appmanifest_%s.acf and " + "will overwrite anything this tool writes. Close Steam, then re-run.", + ", ".join(str(p) for p in running), + metadata.appid, + ) + logger.info("Run log (send this): %s", log.path) + return 1 + + depot_plan = appinfo.get_depot_plan(metadata.appid, language) + expected_build_id = appinfo.get_build_id(metadata.appid) + log.section("Plan") + logger.debug("language=%s max_downloads=%s", language, args.max_downloads) + logger.debug("required depots: %s", sorted(depot_plan.required)) + logger.debug("shared depots: %s", sorted(depot_plan.shared)) + logger.debug("expected buildid: %s", expected_build_id) + + library = next(lib for lib in libraries if lib.common == target.parent) + manifest_path = library.steamapps / f"appmanifest_{metadata.appid}.acf" + log.file_contents("Manifest before run", manifest_path) + + logger.info("Downloading via depotdownloader (fast path)...") + log.section("depotdownloader") + returncode = depotdl.download( appid=metadata.appid, install_dir=target, username=args.username, language=language, max_downloads=args.max_downloads, + logger=logger, ) + if returncode != 0: + logger.error( + "depotdownloader failed (exit %d) -- not touching the manifest.", returncode + ) + logger.info("Run log (send this): %s", log.path) + return 1 + + log.section("depotdownloader cache") + for depot_id, mid in sorted( + recognize.discover_cached_depot_manifests(target).items() + ): + logger.debug("depot %s -> manifest %s", depot_id, mid) - library = next(lib for lib in libraries if lib.common == target.parent) recognize.ensure_installdir_correct(library, metadata.appid, target) if not args.skip_steamcmd: - print("Reconciling with steamcmd (validate)...") - result = recognize.run_steamcmd_validate(metadata.appid, target, args.username) + logger.info("Reconciling with steamcmd (validate)...") + log.section("steamcmd app_update validate") + result = recognize.run_steamcmd_validate(metadata.appid, args.username, logger) + log.file_contents("Manifest after steamcmd", manifest_path) # Never trust steamcmd's exit code alone -- verify the manifest actually # reflects a real install before believing it. A "clean" exit has @@ -117,26 +191,107 @@ def main(argv: list[str] | None = None) -> int: library, metadata.appid, target ) ): - print("steamcmd finished cleanly -- Steam should show Play.") + logger.info("steamcmd finished cleanly -- Steam should show Play.") + logger.info("Run log: %s", log.path) return 0 if result.crashed_on_install_script: - print( + logger.info( "steamcmd hit the known install-script crash; finishing the manifest manually..." ) else: - print( - f"steamcmd exited {result.returncode} but the manifest doesn't reflect a " - "real install; finishing it manually..." + logger.info( + "steamcmd exited %d but the manifest doesn't reflect a real install; " + "checking whether it is safe to finish it manually...", + result.returncode, ) - manifest_path = recognize.finish_manifest_manually( + return _finish( + log, + library, + metadata, + target, + depot_plan, + expected_build_id, + skipped_steamcmd=args.skip_steamcmd, + ) + + +def _finish( + log: runlog.RunLog, + library: SteamLibrary, + metadata: appinfo.AppMetadata, + target: Path, + depot_plan: appinfo.DepotPlan, + expected_build_id: str | None, + skipped_steamcmd: bool, +) -> int: + """Hand-finish the manifest, but only if every precondition really holds.""" + logger = log.logger + manifest_path = library.steamapps / f"appmanifest_{metadata.appid}.acf" + + if not manifest_path.is_file(): + # Reachable two ways, so don't blame steamcmd unconditionally: under + # --skip-steamcmd it never runs at all, and nothing else in this tool + # creates a manifest from scratch. + logger.error( + "No %s exists, so there is nothing to finish. This tool only ever " + "patches a manifest Steam or steamcmd already wrote; it never " + "fabricates one. %s", + manifest_path, + ( + "Re-run without --skip-steamcmd so steamcmd creates it (it writes " + "one even when it crashes)." + if skipped_steamcmd + else "steamcmd writes one even when it crashes, so its absence " + "means steamcmd never ran far enough." + ), + ) + logger.info("Run log (send this): %s", log.path) + return 1 + + app_state = recognize.read_app_state(manifest_path) + problems = recognize.check_ready_to_finish( + install_dir=target, + app_state=app_state, + required_depots=depot_plan.required, + expected_build_id=expected_build_id, + ) + if problems: + # Fail closed. Writing StateFlags=4 here is what previously turned a + # steamcmd run that did nothing at all into a reported success. + logger.error("Refusing to mark %s as installed:", metadata.name) + for problem in problems: + logger.error(" - %s", problem) + logger.info("Run log (send this): %s", log.path) + return 1 + + # Do this before writing the manifest: a StateFlags=4 manifest alongside a + # staging tree full of pending chunks is the same contradiction that made + # Steam resume the download last time. + freed = recognize.clear_steam_staging(library, metadata.appid) + if freed: + logger.info("Cleared %.1f GB of stale Steam staging data.", freed / 1e9) + + written = recognize.finish_manifest_manually( library=library, appid=metadata.appid, install_dir=target, now_unix=int(time.time()), ) - print(f"Wrote {manifest_path} -- launch Steam and confirm Play works.") + log.file_contents("Manifest after manual finish", written) + + # Re-read from disk: claiming success without checking the write landed is + # the same fail-open mistake in a different place. + if not recognize.manifest_reflects_real_install(library, metadata.appid, target): + logger.error( + "Wrote %s but it still does not read back as a real install.", written + ) + logger.info("Run log (send this): %s", log.path) + return 1 + + logger.info("Wrote %s -- launch Steam and confirm Play works.", written) + logger.info("Run log: %s", log.path) return 0 diff --git a/_installer_import/steam_installer/depotdl.py b/_installer_import/steam_installer/depotdl.py index cc3c60c..09b5cf3 100644 --- a/_installer_import/steam_installer/depotdl.py +++ b/_installer_import/steam_installer/depotdl.py @@ -11,9 +11,11 @@ built to avoid. from __future__ import annotations -import subprocess +import logging from pathlib import Path +from steam_installer import runlog + DEFAULT_MAX_DOWNLOADS = 32 @@ -21,11 +23,17 @@ def download( appid: int, install_dir: Path, username: str, + logger: logging.Logger, language: str = "english", os_name: str = "windows", max_downloads: int = DEFAULT_MAX_DOWNLOADS, -) -> None: - """Run depotdownloader against `install_dir`, streaming its own progress output live.""" +) -> int: + """Run depotdownloader against `install_dir`, streaming its own progress output live. + + Returns the exit code rather than raising: the caller has to distinguish + "download failed" from "download fine, manifest step failed" to decide + whether touching the manifest is safe at all. + """ install_dir.mkdir(parents=True, exist_ok=True) cmd = [ "depotdownloader", @@ -43,4 +51,5 @@ def download( "-dir", str(install_dir), ] - subprocess.run(cmd, check=True) + returncode, _ = runlog.run_logged(cmd, logger) + return returncode diff --git a/_installer_import/steam_installer/recognize.py b/_installer_import/steam_installer/recognize.py index f71c889..59fd033 100644 --- a/_installer_import/steam_installer/recognize.py +++ b/_installer_import/steam_installer/recognize.py @@ -13,25 +13,42 @@ evaluator reports failure (crash backtrace: the same stack frame repeating dozens of times). There's no known fix. When that specific crash is detected, we finish the appmanifest by hand using ONLY values we already verified ourselves: the exact manifest IDs from depotdownloader's own local -cache (never guessed), and the real on-disk size via `du`. Steam is left to -self-correct the rest (byte counters, staged-file bookkeeping) on its very -next launch -- confirmed: it did exactly that in practice, cleaning up the -hand-edited fields on its own. +cache (never guessed), and the real on-disk size measured directly. + +Do NOT leave the download bookkeeping for Steam to tidy up on its next +launch. An earlier version of this module did, on the belief that Steam +self-corrects; it does not. A manifest that says StateFlags=4 while +`BytesDownloaded` still differs from `BytesToDownload` is self-contradictory, +and Steam resolves the contradiction by discarding the "installed" claim and +resuming the download -- 90 GB of it, in the run that prompted this comment. +The byte counters (`_settle_download_counters`) and the staging tree +(`clear_steam_staging`) must both be settled here, and +`manifest_reflects_real_install` refuses to call an install real until they +are. """ from __future__ import annotations +import logging +import os import re +import shutil import signal -import subprocess from dataclasses import dataclass from pathlib import Path -from steam_installer import vdf +from steam_installer import runlog, vdf from steam_installer.library import SteamLibrary MANIFEST_CACHE_RE = re.compile(r"^(\d+)_(\d+)\.manifest$") +# depotdownloader's own cache/staging area lives inside the install dir but is +# not game content -- Steam's SizeOnDisk must not count it. +DEPOTDOWNLOADER_DIR = ".DepotDownloader" + +# Module-level so tests can point it at a fake /proc tree. +PROC_DIR = Path("/proc") + class RecognizeError(Exception): pass @@ -42,31 +59,40 @@ class ValidateResult: completed: bool crashed_on_install_script: bool returncode: int + output: str = "" def run_steamcmd_validate( - appid: int, install_dir: Path, username: str + appid: int, + username: str, + logger: logging.Logger, ) -> ValidateResult: - """Run steamcmd's app_update ... validate. `force_install_dir` must precede `+login` - (steamcmd itself warns about this ordering). + """Run steamcmd's app_update ... validate. - Deliberately does NOT capture stdout/stderr: steamcmd prompts for a - password (and possibly a Steam Guard code) on stdin, and prompt text - written to a captured/buffered stdout never reaches the terminal -- - the process looks hung with no visible request for input. Output is - left to inherit the parent's terminal instead, exactly like - depotdownloader's own interactive login. + Takes no install dir on purpose. `force_install_dir` sets a Steam *library + root*, not an install directory: pointing it at the game folder made + steamcmd look for manifests in `/steamapps/`, find none ("Loaded 0 + apps from install folder"), create that stray directory, and then fail the + app with "Invalid platform" because it had no depot context for it. The app + already lives in a registered library, so letting steamcmd use the real one + is both correct and sufficient. + + Output is teed through a pty (see runlog) rather than captured: steamcmd + prompts for a password and possibly a Steam Guard code on stdin, and prompt + text written to a captured/buffered pipe never reaches the terminal -- the + process looks hung with no visible request for input. The confirmed steamcmd install-script bug (see module docstring) kills the process with SIGSEGV -- Python reports that as returncode -11 on POSIX. Checking the signal directly is more reliable than grepping - captured text for a message string, and doesn't require capturing - output at all. + captured text for a message string. """ cmd = [ "steamcmd", - "+force_install_dir", - str(install_dir), + # A Linux steamcmd refuses a Windows-only app with "Invalid platform" + # unless told which platform to resolve depots for. Must precede +login. + "+@sSteamCmdForcePlatformType", + "windows", "+login", username, "+app_update", @@ -74,12 +100,13 @@ def run_steamcmd_validate( "validate", "+quit", ] - result = subprocess.run(cmd, timeout=3600) - crashed = result.returncode == -signal.SIGSEGV + returncode, output = runlog.run_logged(cmd, logger, timeout=3600) + crashed = returncode == -signal.SIGSEGV return ValidateResult( - completed=result.returncode == 0, + completed=returncode == 0, crashed_on_install_script=crashed, - returncode=result.returncode, + returncode=returncode, + output=output, ) @@ -94,8 +121,8 @@ def ensure_installdir_correct( read that same stale field and wiped the correctly-downloaded folder as "orphaned" while starting a fresh download into the wrong one. Fixing it proactively, before steamcmd ever runs, closes that window entirely. - Does nothing if no manifest exists yet -- steamcmd creates one itself in - that case, with the right installdir since we pass force_install_dir. + Does nothing if no manifest exists yet -- steamcmd's own app_update writes + one in that case, and it derives installdir from the app's metadata. """ manifest_path = library.steamapps / f"appmanifest_{appid}.acf" if not manifest_path.is_file(): @@ -107,7 +134,8 @@ def ensure_installdir_correct( if app_state.get("installdir") == install_dir.name: return app_state["installdir"] = install_dir.name - manifest_path.write_text(vdf.dumps("AppState", app_state)) + _backup_once(manifest_path) + _write_atomic(manifest_path, vdf.dumps("AppState", app_state)) def manifest_reflects_real_install( @@ -132,12 +160,33 @@ def manifest_reflects_real_install( app_state.get("StateFlags") == "4" and app_state.get("installdir") == install_dir.name and bool(app_state.get("InstalledDepots")) + and download_counters_settled(app_state) ) +def download_counters_settled(app_state: dict) -> bool: + """Whether the download bookkeeping agrees that nothing is left to fetch. + + This is the check that was missing when Steam threw away a StateFlags=4 + manifest and resumed a 90 GB download: the file simultaneously claimed + "fully installed" and "22 GB of 92 GB downloaded". Across every genuine + installed manifest on this machine the counters are equal in pairs and + StagingSize is "0", so treat any inequality as "still downloading". + """ + pairs = (("BytesToDownload", "BytesDownloaded"), ("BytesToStage", "BytesStaged")) + for total_key, done_key in pairs: + total = app_state.get(total_key) + done = app_state.get(done_key) + # Absent counters are fine (Steam omits them on some apps); mismatched + # ones are not. + if total is not None and done is not None and total != done: + return False + return app_state.get("StagingSize", "0") == "0" + + def discover_cached_depot_manifests(install_dir: Path) -> dict[str, str]: """Depot ID -> manifest ID, read from depotdownloader's own local cache filenames.""" - cache_dir = install_dir / ".DepotDownloader" + cache_dir = install_dir / DEPOTDOWNLOADER_DIR found: dict[str, str] = {} if not cache_dir.is_dir(): return found @@ -149,6 +198,169 @@ def discover_cached_depot_manifests(install_dir: Path) -> dict[str, str]: return found +def clear_steam_staging(library: SteamLibrary, appid: int) -> int: + """Drop Steam's half-finished staging tree for `appid`. Returns bytes freed. + + Steam stages downloaded chunks in `steamapps/downloading//` and + commits them into `common/` afterwards. If we declare the app installed + while that tree still holds tens of GB plus its `state_*.patch` files, + Steam finds work pending and resumes the update -- the manifest says + "done", the staging area says "mid-download". Every genuinely installed app + on this machine has an empty (4 KB) staging dir, so matching that is what + "installed" actually looks like on disk. + + Only ever discards Steam's own staging copies, never `common/` content. + """ + downloading = library.steamapps / "downloading" + staged = downloading / str(appid) + freed = 0 + if staged.is_dir(): + freed = sum(f.stat().st_size for f in staged.rglob("*") if f.is_file()) + shutil.rmtree(staged) + staged.mkdir(parents=True, exist_ok=True) + for patch in downloading.glob(f"state_{appid}_*.patch"): + freed += patch.stat().st_size + patch.unlink() + return freed + + +def read_app_state(manifest_path: Path) -> dict: + """The `AppState` block of a manifest, or an empty dict if unreadable.""" + if not manifest_path.is_file(): + return {} + data = vdf.parse(manifest_path.read_text()) + app_state = data.get("AppState", {}) + return app_state if isinstance(app_state, dict) else {} + + +def steam_client_pids() -> list[int]: + """PIDs of a running Steam client, if any. + + Steam owns appmanifest_*.acf while it runs and rewrites it from its own + in-memory state, so a manifest patched underneath a live client is simply + discarded -- which is exactly what happened on the run that prompted all + this. Matching on the executable path (not a `pgrep -f` pattern) avoids + matching our own command line. + """ + pids: list[int] = [] + for entry in PROC_DIR.iterdir(): + if not entry.name.isdigit(): + continue + try: + exe = (entry / "exe").resolve() + except OSError: + continue + # Match the client by executable name alone. An earlier version also + # required "ubuntu12_32" in the path, which silently fails open for a + # Flatpak install (/app/bin/steam) -- and a guard that quietly stops + # guarding is worse than no guard. `steamcmd` is a different binary, so + # it is not matched here. + if exe.name in ("steam", "steamwebhelper"): + pids.append(int(entry.name)) + return pids + + +def check_ready_to_finish( + install_dir: Path, + app_state: dict, + required_depots: set[str], + expected_build_id: str | None, +) -> list[str]: + """Reasons the manifest must NOT be hand-finished. Empty list means go ahead. + + Every one of these was a real failure mode: writing StateFlags=4 after a + steamcmd run that did nothing turned a dead run into a reported success. + """ + problems: list[str] = [] + + # An empty required set would make the depot check below vacuously true and + # wave through a download that fetched nothing. It means the depot filter + # matched no depot at all (wrong language or OS for this app), not that + # there is nothing to install. + if not required_depots: + problems.append( + "no depots match this app for the chosen language/OS -- refusing to " + "guess that the install is complete" + ) + + cached = discover_cached_depot_manifests(install_dir) + + # `finish_manifest_manually` drops depots the on-disk manifest lists under + # SharedDepots, which is a different source of truth from app_info's + # depotfromapp/sharedinstall. If they disagree it can end up with nothing to + # install and raise -- and by then clear_steam_staging has already deleted + # Steam's resumable staging tree. Catch the disagreement here, while + # refusing is still free. + shared = app_state.get("SharedDepots") + shared_ids = set(shared) if isinstance(shared, dict) else set() + if cached and not (set(cached) - shared_ids): + problems.append( + "every cached depot is listed under SharedDepots in the existing " + "manifest, so there would be nothing to record as installed" + ) + + missing = sorted(required_depots - set(cached)) + if missing: + problems.append( + f"depot(s) {', '.join(missing)} have no cached manifest under " + f"{install_dir}/{DEPOTDOWNLOADER_DIR} -- the download did not finish" + ) + + buildid = app_state.get("buildid") + target = app_state.get("TargetBuildID") + if not (buildid and buildid != "0") and not (target and target != "0"): + problems.append( + "manifest has no usable buildid (both buildid and TargetBuildID are 0) " + "-- steamcmd never recorded a real build" + ) + resolved = buildid if buildid and buildid != "0" else target + if expected_build_id is None: + # Don't silently skip the comparison: a None here means app_info had no + # branches.public, so we cannot tell a current build from a stale one. + problems.append( + "could not determine the current public build from app info, so the " + "manifest's buildid cannot be checked" + ) + elif resolved and resolved != expected_build_id: + problems.append( + f"manifest buildid {resolved} != current public build " + f"{expected_build_id} -- content is for a different build" + ) + + # Cache *filenames* are not content. Without this, an install dir holding + # only `.DepotDownloader/_.manifest` and no game files passes every + # other check and gets written as StateFlags=4 with SizeOnDisk=0. + if not measure_content_size(install_dir): + problems.append( + f"no game content found under {install_dir} (only depotdownloader " + "cache files) -- nothing was actually installed" + ) + + pids = steam_client_pids() + if pids: + problems.append( + f"the Steam client is running (pid {', '.join(str(p) for p in pids)}) " + "and will overwrite the manifest -- close Steam and re-run" + ) + + return problems + + +def measure_content_size(install_dir: Path) -> int: + """Bytes of real game content, excluding depotdownloader's own cache/staging. + + `.DepotDownloader/` holds manifests and a staging tree that Steam knows + nothing about; counting them overstates SizeOnDisk by gigabytes. + """ + total = 0 + for entry in install_dir.rglob("*"): + if DEPOTDOWNLOADER_DIR in entry.parts: + continue + if entry.is_file() and not entry.is_symlink(): + total += entry.stat().st_size + return total + + def finish_manifest_manually( library: SteamLibrary, appid: int, @@ -175,10 +387,10 @@ def finish_manifest_manually( depot_manifests = discover_cached_depot_manifests(install_dir) if not depot_manifests: raise RecognizeError( - f"No cached depot manifests found under {install_dir}/.DepotDownloader" + f"No cached depot manifests found under {install_dir}/{DEPOTDOWNLOADER_DIR}" ) - size_on_disk = sum(f.stat().st_size for f in install_dir.rglob("*") if f.is_file()) + size_on_disk = measure_content_size(install_dir) # "0" means "no real build installed yet" (steamcmd/Steam use it as a # sentinel) -- a bare `or` treats that non-empty string as truthy and # never falls through to TargetBuildID, leaving a stale/wrong buildid. @@ -186,10 +398,20 @@ def finish_manifest_manually( buildid = existing_buildid if existing_buildid and existing_buildid != "0" else None buildid = buildid or app_state.get("TargetBuildID") or "0" + # A shared depot (e.g. Steamworks Common Redistributables) is installed once + # under its owning app and only referenced here. Listing it in + # InstalledDepots as though this app owned a copy contradicts SharedDepots. + shared = app_state.get("SharedDepots") + shared_ids = set(shared) if isinstance(shared, dict) else set() installed_depots = { depot_id: {"manifest": manifest_id, "size": "0"} for depot_id, manifest_id in depot_manifests.items() + if depot_id not in shared_ids } + if not installed_depots: + raise RecognizeError( + f"Every cached depot for {appid} is a shared depot -- nothing to install" + ) app_state["StateFlags"] = "4" app_state["installdir"] = install_dir.name @@ -200,8 +422,52 @@ def finish_manifest_manually( app_state["UpdateResult"] = "0" app_state["InstalledDepots"] = installed_depots app_state.pop("StagedDepots", None) + _settle_download_counters(app_state) - backup_path = manifest_path.with_suffix(".acf.bak") - backup_path.write_text(manifest_path.read_text()) - manifest_path.write_text(vdf.dumps("AppState", app_state)) + _backup_once(manifest_path) + _write_atomic(manifest_path, vdf.dumps("AppState", app_state)) return manifest_path + + +def _backup_once(manifest_path: Path) -> None: + """Keep the *pristine* manifest, not the previous run's output. + + An unconditional backup means a second run overwrites the original with + run 1's already-patched file, so the recovery artifact for a 90+ GB install + is one re-run away from being useless. Only write it if absent. + """ + backup_path = manifest_path.with_suffix(".acf.bak") + if not backup_path.exists(): + backup_path.write_text(manifest_path.read_text()) + + +def _write_atomic(path: Path, text: str) -> None: + """Write via a temp file + rename so a crash can't truncate the manifest. + + A partial write leaves an unparseable manifest, which Steam and this tool + both then choke on. `os.replace` is atomic within a filesystem, and the + temp file is created alongside the target to stay on the same one. + """ + tmp = path.with_name(f"{path.name}.tmp{os.getpid()}") + try: + tmp.write_text(text) + os.replace(tmp, path) + except BaseException: + tmp.unlink(missing_ok=True) + raise + + +def _settle_download_counters(app_state: dict) -> None: + """Mark the download bookkeeping complete: `Downloaded` == `ToDownload`. + + Leaving these at their mid-download values is what made Steam discard a + StateFlags=4 manifest and resume fetching. Real installed manifests keep + these fields (they are not dropped) with the pair values equal. + """ + for total_key, done_key in ( + ("BytesToDownload", "BytesDownloaded"), + ("BytesToStage", "BytesStaged"), + ): + total = app_state.get(total_key) + if total is not None: + app_state[done_key] = total diff --git a/_installer_import/steam_installer/runlog.py b/_installer_import/steam_installer/runlog.py new file mode 100644 index 0000000..d3741de --- /dev/null +++ b/_installer_import/steam_installer/runlog.py @@ -0,0 +1,223 @@ +"""Per-run logging. + +Everything a run does lands in one file the user can copy-paste verbatim when +something goes wrong. The first version of this tool had no logging at all, and +when a run failed the evidence was gone: Steam owns appmanifest_.acf and +had already overwritten the manifest we wrote by the time anyone looked. So the +log records the manifest *verbatim, before and after* every write, alongside the +full output of every subprocess. + +Subprocess output is teed through a pty rather than captured with +`capture_output=True`. steamcmd prompts for a password (and possibly a Steam +Guard code) on stdin; prompt text written to a captured/buffered pipe never +reaches the terminal, so the process looks hung with no visible request for +input. A pty keeps steamcmd in line-buffered interactive mode and lets us +mirror every byte to both the terminal and the log. +""" + +from __future__ import annotations + +import errno +import io +import logging +import os +import pty +import select +import shlex +import subprocess +import sys +import time +from dataclasses import dataclass +from pathlib import Path + +LOG_DIR = Path.home() / ".local/state/steam-game-installer" +LOGGER_NAME = "steam_installer" + +_CONSOLE_FORMAT = "%(message)s" +_FILE_FORMAT = "%(asctime)s %(levelname)-7s %(name)s: %(message)s" + +# Read granularity for the pty relay. Large enough that depotdownloader's +# progress spam doesn't cost a syscall per line, small enough to stay responsive. +_READ_CHUNK = 65536 + + +@dataclass +class RunLog: + """A single run's log file, plus the `latest.log` symlink pointing at it.""" + + path: Path + logger: logging.Logger + + def section(self, title: str) -> None: + """A visual divider so a pasted log is skimmable.""" + self.logger.debug("=" * 72) + self.logger.debug(title) + self.logger.debug("=" * 72) + + def file_contents(self, label: str, path: Path) -> None: + """Record a file verbatim. Used for manifests before/after every write.""" + self.section(f"{label}: {path}") + try: + self.logger.debug("\n%s", path.read_text()) + except OSError as exc: + self.logger.debug("(unreadable: %s)", exc) + + +def setup(appid: int | None, verbose: bool = False) -> RunLog: + """Start a run log. Console stays terse; the file gets everything at DEBUG.""" + LOG_DIR.mkdir(parents=True, exist_ok=True) + stamp = time.strftime("%Y%m%d-%H%M%S") + path = LOG_DIR / f"run-{stamp}-{appid if appid is not None else 'noappid'}.log" + + logger = logging.getLogger(LOGGER_NAME) + logger.setLevel(logging.DEBUG) + logger.propagate = False + # A second setup() in the same process (tests) must not double-log. + for handler in list(logger.handlers): + logger.removeHandler(handler) + handler.close() + + file_handler = logging.FileHandler(path, encoding="utf-8") + file_handler.setLevel(logging.DEBUG) + file_handler.setFormatter(logging.Formatter(_FILE_FORMAT)) + logger.addHandler(file_handler) + + console = logging.StreamHandler(sys.stdout) + console.setLevel(logging.DEBUG if verbose else logging.INFO) + console.setFormatter(logging.Formatter(_CONSOLE_FORMAT)) + logger.addHandler(console) + + _point_latest_at(path) + return RunLog(path=path, logger=logger) + + +def _point_latest_at(path: Path) -> None: + """Best-effort `latest.log` symlink -- a stale symlink must never fail a run.""" + latest = LOG_DIR / "latest.log" + try: + if latest.is_symlink() or latest.exists(): + latest.unlink() + latest.symlink_to(path.name) + except OSError: + pass + + +def run_logged( + cmd: list[str], + logger: logging.Logger, + timeout: float | None = None, +) -> tuple[int, str]: + """Run `cmd` on a pty, mirroring output to both the terminal and the log. + + Returns (returncode, combined_output). stdin stays attached to the real + terminal so interactive prompts (steamcmd's password / Steam Guard) work + exactly as they do without logging. + """ + logger.debug("$ %s", shlex.join(cmd)) + started = time.monotonic() + + master_fd, slave_fd = pty.openpty() + chunks: list[bytes] = [] + try: + process = subprocess.Popen( + cmd, + stdout=slave_fd, + stderr=slave_fd, + stdin=_stdin_for_child(slave_fd), + close_fds=True, + ) + except OSError: + os.close(master_fd) + os.close(slave_fd) + raise + # The child owns the slave end now; holding it open here would keep the + # master readable forever and hang the relay after the child exits. + os.close(slave_fd) + + try: + _relay(master_fd, chunks, process, timeout, started) + except subprocess.TimeoutExpired as exc: + # Record what the child managed to say before it hung, then re-raise. + # Losing it here defeats the whole point of the log in precisely the + # case where it matters most -- a steamcmd hang at the 3600s timeout. + output = _log_output(logger, chunks, started, returncode=None) + process.wait() + exc.output = output.encode() + raise + finally: + os.close(master_fd) + + returncode = process.wait() + output = _log_output(logger, chunks, started, returncode) + return returncode, output + + +def _log_output( + logger: logging.Logger, + chunks: list[bytes], + started: float, + returncode: int | None, +) -> str: + output = b"".join(chunks).decode("utf-8", errors="replace") + elapsed = time.monotonic() - started + logger.debug("--- output (%d bytes) ---\n%s", len(output), output) + if returncode is None: + logger.debug("TIMED OUT after %.1fs", elapsed) + else: + logger.debug("exit=%d elapsed=%.1fs", returncode, elapsed) + return output + + +def _read_pty(fd: int, size: int) -> bytes: + """Indirection so tests can fault-inject the pty read without patching the + global `os.read`, which subprocess itself uses during spawn.""" + return os.read(fd, size) + + +def _stdin_for_child(slave_fd: int) -> int: + """The child's stdin: the real terminal when there is one, else the pty. + + steamcmd needs a readable stdin to prompt for a password, but `sys.stdin` + is not always a real file descriptor -- under pytest's capture, systemd, or + a piped invocation it has no fileno(). Falling back to the pty's slave end + keeps the child on a terminal-like stdin instead of crashing. + """ + try: + return sys.stdin.fileno() + except (AttributeError, ValueError, OSError, io.UnsupportedOperation): + return slave_fd + + +def _relay( + master_fd: int, + chunks: list[bytes], + process: subprocess.Popen, + timeout: float | None, + started: float, +) -> None: + """Pump pty output to stdout and `chunks` until the child closes it.""" + while True: + if timeout is not None and time.monotonic() - started > timeout: + process.kill() + raise subprocess.TimeoutExpired(process.args, timeout) + try: + ready, _, _ = select.select([master_fd], [], [], 0.2) + except OSError: + break + if not ready: + # No output pending; the child may still have exited. + if process.poll() is not None: + break + continue + try: + data = _read_pty(master_fd, _READ_CHUNK) + except OSError as exc: + # EIO is the normal "child closed the pty" signal on Linux. + if exc.errno == errno.EIO: + break + raise + if not data: + break + chunks.append(data) + sys.stdout.buffer.write(data) + sys.stdout.buffer.flush() diff --git a/_installer_import/steam_installer/vdf.py b/_installer_import/steam_installer/vdf.py index 11d282f..b73bec3 100644 --- a/_installer_import/steam_installer/vdf.py +++ b/_installer_import/steam_installer/vdf.py @@ -98,6 +98,20 @@ def _tokenize(text: str) -> list[str]: return tokens +def _escape(value: str) -> str: + r"""Re-escape a value for VDF output. + + The tokenizer consumes `\` escapes, so a manifest holding + `_CommonRedist\\vcredist\\2015\\installscript.vdf` parses to a value with + single backslashes. Writing that back verbatim would halve them on every + parse/dump cycle and silently corrupt the path -- confirmed against the + real appmanifest_228980.acf (Steamworks Common Redistributables), whose + InstallScripts entries are Windows paths and whose depot 228989 is shared + with other games. + """ + return value.replace("\\", "\\\\").replace('"', '\\"') + + def dumps(root_key: str, data: dict[str, VdfValue], indent: str = "\t") -> str: """Serialize a dict back to VDF text, matching Steam's own tab-indented style.""" lines = [f'"{root_key}"', "{"] @@ -112,9 +126,9 @@ def _dump_block( prefix = indent * depth for key, value in data.items(): if isinstance(value, dict): - lines.append(f'{prefix}"{key}"') + lines.append(f'{prefix}"{_escape(key)}"') lines.append(f"{prefix}{{") _dump_block(value, indent, depth + 1, lines) lines.append(f"{prefix}}}") else: - lines.append(f'{prefix}"{key}"\t\t"{value}"') + lines.append(f'{prefix}"{_escape(key)}"\t\t"{_escape(value)}"') diff --git a/_installer_import/tests/conftest.py b/_installer_import/tests/conftest.py new file mode 100644 index 0000000..fbc4176 --- /dev/null +++ b/_installer_import/tests/conftest.py @@ -0,0 +1,21 @@ +"""Shared test setup. + +`test_module_is_runnable_as_a_script` runs `python -m steam_installer.cli` in a +subprocess. Without the hook below, coverage collected in that child is thrown +away and the `__main__` guard looks uncovered. +""" + +import os +import pathlib + +import pytest + + +@pytest.fixture +def coverage_subprocess_env(): + """Env for a child process that should also record coverage.""" + env = os.environ.copy() + root = pathlib.Path(__file__).resolve().parent.parent + env["COVERAGE_PROCESS_START"] = str(root / "pyproject.toml") + env["PYTHONPATH"] = str(root) + os.pathsep + env.get("PYTHONPATH", "") + return env diff --git a/_installer_import/tests/test_appinfo.py b/_installer_import/tests/test_appinfo.py new file mode 100644 index 0000000..06ab228 --- /dev/null +++ b/_installer_import/tests/test_appinfo.py @@ -0,0 +1,236 @@ +import pytest + +from steam_installer import appinfo + + +def _app_block(monkeypatch, block): + monkeypatch.setattr(appinfo, "_fetch_app_block", lambda appid: block) + + +# Shape taken from a real `app_info_print 1771300`: 12 depots, of which an +# english/windows install only ever fetches three. +KCD2_DEPOTS = { + "228989": {"depotfromapp": "228980", "config": {"oslist": "windows"}}, + "1771302": {"config": {"oslist": "windows"}}, + "1771303": {"config": {"oslist": "windows"}}, + "1771304": {"dlcappid": "3406020", "config": {"oslist": "windows"}}, + "1771305": {"config": {"oslist": "windows", "language": "czech"}}, + "1771306": {"config": {"oslist": "windows", "language": "english"}}, + "1771307": {"config": {"oslist": "windows", "language": "french"}}, + "4075290": {"dlcappid": "4075290"}, + "branches": {"public": {"buildid": "23914554"}}, +} + + +def test_get_depot_plan_selects_only_this_language_and_os(monkeypatch): + _app_block(monkeypatch, {"depots": KCD2_DEPOTS}) + + plan = appinfo.get_depot_plan(1771300, language="english", os_name="windows") + + assert plan.required == {"1771302", "1771303", "1771306"} + assert plan.shared == {"228989"} + assert plan.all_expected == {"1771302", "1771303", "1771306", "228989"} + + +def test_get_depot_plan_switches_language(monkeypatch): + _app_block(monkeypatch, {"depots": KCD2_DEPOTS}) + plan = appinfo.get_depot_plan(1771300, language="czech") + assert "1771305" in plan.required + assert "1771306" not in plan.required + + +def test_get_depot_plan_excludes_other_os(monkeypatch): + _app_block( + monkeypatch, + {"depots": {"10": {"config": {"oslist": "linux"}}, "11": {"config": {}}}}, + ) + plan = appinfo.get_depot_plan(1771300, os_name="windows") + assert plan.required == {"11"} + + +def test_get_depot_plan_skips_optional_depots(monkeypatch): + _app_block(monkeypatch, {"depots": {"10": {"optional": "1"}, "11": {}}}) + assert appinfo.get_depot_plan(1771300).required == {"11"} + + +def test_get_depot_plan_rejects_malformed_depots_section(monkeypatch): + _app_block(monkeypatch, {"depots": "not-a-dict"}) + with pytest.raises(appinfo.AppInfoError, match="depots"): + appinfo.get_depot_plan(1771300) + + +def test_get_depot_plan_with_no_depots_is_empty(monkeypatch): + """An app with no depot list yields nothing required -- callers must not + read that as "everything downloaded fine".""" + _app_block(monkeypatch, {}) + plan = appinfo.get_depot_plan(1771300) + assert plan.required == set() + assert plan.shared == set() + + +def test_get_build_id_reads_public_branch(monkeypatch): + _app_block(monkeypatch, {"depots": KCD2_DEPOTS}) + assert appinfo.get_build_id(1771300) == "23914554" + + +def test_get_build_id_missing_branch_returns_none(monkeypatch): + _app_block(monkeypatch, {"depots": {"branches": {}}}) + assert appinfo.get_build_id(1771300) is None + + +def test_get_build_id_without_depots_returns_none(monkeypatch): + _app_block(monkeypatch, {}) + assert appinfo.get_build_id(1771300) is None + + +def test_get_metadata_reads_name_and_installdir(monkeypatch): + _app_block( + monkeypatch, + { + "common": { + "name": "Kingdom Come: Deliverance II", + "installdir": "KingdomComeDeliverance2", + } + }, + ) + metadata = appinfo.get_metadata(1771300) + assert metadata.name == "Kingdom Come: Deliverance II" + assert metadata.installdir == "KingdomComeDeliverance2" + + +def test_get_metadata_falls_back_to_config_installdir(monkeypatch): + _app_block( + monkeypatch, + {"common": {"name": "Game"}, "config": {"installdir": "GameDir"}}, + ) + assert appinfo.get_metadata(1).installdir == "GameDir" + + +def test_get_metadata_requires_name(monkeypatch): + _app_block(monkeypatch, {"common": {"installdir": "GameDir"}}) + with pytest.raises(appinfo.AppInfoError, match="no name field"): + appinfo.get_metadata(1) + + +def test_get_metadata_requires_installdir(monkeypatch): + _app_block(monkeypatch, {"common": {"name": "Game"}}) + with pytest.raises(appinfo.AppInfoError, match="no installdir"): + appinfo.get_metadata(1) + + +def test_get_metadata_rejects_malformed_common_section(monkeypatch): + _app_block(monkeypatch, {"common": "not-a-dict"}) + with pytest.raises(appinfo.AppInfoError, match="no 'common' section"): + appinfo.get_metadata(1) + + +class _FakeCompleted: + def __init__(self, stdout): + self.stdout = stdout + self.returncode = 0 + + +# What steamcmd actually emits: its own log lines, then the VDF block. +STEAMCMD_OUTPUT = """Redirecting stderr to '/home/u/.steam/logs/stderr.txt' +Logging directory: '/home/u/.steam/logs' +"@sSteamCmdForcePlatformType" = "windows" +Logging in user 'anonymous' to Steam Public...OK +"1771300" +{ +\t"common" +\t{ +\t\t"name"\t\t"Kingdom Come: Deliverance II" +\t\t"installdir"\t\t"KingdomComeDeliverance2" +\t} +\t"depots" +\t{ +\t\t"1771303" +\t\t{ +\t\t\t"config" +\t\t\t{ +\t\t\t\t"oslist"\t\t"windows" +\t\t\t} +\t\t} +\t\t"branches" +\t\t{ +\t\t\t"public" +\t\t\t{ +\t\t\t\t"buildid"\t\t"23914554" +\t\t\t} +\t\t} +\t} +} +""" + + +def test_fetch_app_block_parses_real_steamcmd_output(monkeypatch): + seen = {} + + def fake_run(cmd, **kwargs): + seen["cmd"] = cmd + return _FakeCompleted(STEAMCMD_OUTPUT) + + monkeypatch.setattr(appinfo.subprocess, "run", fake_run) + + metadata = appinfo.get_metadata(1771300) + + assert metadata.name == "Kingdom Come: Deliverance II" + assert metadata.installdir == "KingdomComeDeliverance2" + # The platform flag must precede +login or a Windows-only app comes back empty. + cmd = seen["cmd"] + assert cmd.index("+@sSteamCmdForcePlatformType") < cmd.index("+login") + assert cmd[cmd.index("+@sSteamCmdForcePlatformType") + 1] == "windows" + + +def test_get_build_id_through_the_real_parser(monkeypatch): + monkeypatch.setattr( + appinfo.subprocess, "run", lambda cmd, **kw: _FakeCompleted(STEAMCMD_OUTPUT) + ) + assert appinfo.get_build_id(1771300) == "23914554" + + +def test_fetch_app_block_raises_when_appid_header_absent(monkeypatch): + """steamcmd prints its usual log noise even for an unknown app; without the + `""` header there is no app info to parse.""" + monkeypatch.setattr( + appinfo.subprocess, + "run", + lambda cmd, **kw: _FakeCompleted("Logging in user 'anonymous'...OK\n"), + ) + with pytest.raises(appinfo.AppInfoError, match="did not return app info"): + appinfo.get_metadata(999999999) + + +def test_fetch_app_block_raises_when_block_is_not_a_mapping(monkeypatch): + """Defensive guard against a shape vdf.parse cannot currently produce (it + always yields a dict for a `{ ... }` block). Exercised by injecting a parser + that returns a scalar, so the guard stays correct if vdf ever changes.""" + monkeypatch.setattr( + appinfo.subprocess, + "run", + lambda cmd, **kw: _FakeCompleted('"1771300"\n{\n}\n'), + ) + monkeypatch.setattr(appinfo.vdf, "parse", lambda text: {"1771300": "scalar"}) + + with pytest.raises(appinfo.AppInfoError, match="unexpected app_info_print"): + appinfo.get_metadata(1771300) + + +def test_get_build_id_handles_non_dict_sections(monkeypatch): + for text in ( + '"1"\n{\n\t"depots"\t\t"scalar"\n}\n', + '"1"\n{\n\t"depots"\n\t{\n\t\t"branches"\t\t"scalar"\n\t}\n}\n', + '"1"\n{\n\t"depots"\n\t{\n\t\t"branches"\n\t\t{\n\t\t\t"public"\t\t"x"\n\t\t}\n\t}\n}\n', + ): + monkeypatch.setattr( + appinfo.subprocess, "run", lambda cmd, _t=text, **kw: _FakeCompleted(_t) + ) + assert appinfo.get_build_id(1) is None + + +def test_get_build_id_returns_none_when_buildid_not_a_string(monkeypatch): + text = '"1"\n{\n\t"depots"\n\t{\n\t\t"branches"\n\t\t{\n\t\t\t"public"\n\t\t\t{\n\t\t\t\t"buildid"\n\t\t\t\t{\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n' + monkeypatch.setattr( + appinfo.subprocess, "run", lambda cmd, **kw: _FakeCompleted(text) + ) + assert appinfo.get_build_id(1) is None diff --git a/_installer_import/tests/test_cli.py b/_installer_import/tests/test_cli.py new file mode 100644 index 0000000..0170056 --- /dev/null +++ b/_installer_import/tests/test_cli.py @@ -0,0 +1,328 @@ +"""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 diff --git a/_installer_import/tests/test_depotdl.py b/_installer_import/tests/test_depotdl.py new file mode 100644 index 0000000..f43cd4e --- /dev/null +++ b/_installer_import/tests/test_depotdl.py @@ -0,0 +1,80 @@ +import logging + +from steam_installer import depotdl + + +def _capture(monkeypatch): + """Intercept the subprocess call and hand back the argv it was given.""" + seen = {} + + def fake_run_logged(cmd, logger, timeout=None): + seen["cmd"] = cmd + return seen.get("rc", 0), "" + + monkeypatch.setattr(depotdl.runlog, "run_logged", fake_run_logged) + return seen + + +def test_download_builds_expected_argv(tmp_path, monkeypatch): + seen = _capture(monkeypatch) + + depotdl.download( + appid=1771300, + install_dir=tmp_path / "Game", + username="krzys2000", + logger=logging.getLogger("t"), + language="english", + max_downloads=32, + ) + + cmd = seen["cmd"] + assert cmd[0] == "depotdownloader" + pairs = dict(zip(cmd[1::2], cmd[2::2])) + assert pairs["-app"] == "1771300" + assert pairs["-language"] == "english" + assert pairs["-max-downloads"] == "32" + assert pairs["-username"] == "krzys2000" + + +def test_download_always_passes_os_windows(tmp_path, monkeypatch): + """Without -os, depotdownloader defaults to the host OS and can filter out + every real (Windows-tagged) depot -- the original "0 bytes from 0 depots".""" + seen = _capture(monkeypatch) + + depotdl.download( + appid=1771300, + install_dir=tmp_path / "Game", + username="u", + logger=logging.getLogger("t"), + ) + + cmd = seen["cmd"] + assert cmd[cmd.index("-os") + 1] == "windows" + assert "-remember-password" in cmd + + +def test_download_creates_the_install_dir(tmp_path, monkeypatch): + _capture(monkeypatch) + target = tmp_path / "nested" / "Game" + + depotdl.download( + appid=1, install_dir=target, username="u", logger=logging.getLogger("t") + ) + + assert target.is_dir() + + +def test_download_returns_the_exit_code_instead_of_raising(tmp_path, monkeypatch): + """The caller must distinguish "download failed" from "manifest step failed" + to decide whether touching the manifest is safe at all.""" + seen = _capture(monkeypatch) + seen["rc"] = 1 + + returncode = depotdl.download( + appid=1, + install_dir=tmp_path / "Game", + username="u", + logger=logging.getLogger("t"), + ) + + assert returncode == 1 diff --git a/_installer_import/tests/test_library.py b/_installer_import/tests/test_library.py index e6ec1c0..a6f2d15 100644 --- a/_installer_import/tests/test_library.py +++ b/_installer_import/tests/test_library.py @@ -1,5 +1,8 @@ from pathlib import Path +import pytest + +from steam_installer import library, vdf from steam_installer.library import ( SteamLibrary, find_existing_install, @@ -68,3 +71,86 @@ def test_pick_install_target_defaults_to_primary_library(tmp_path): libraries = [SteamLibrary(root)] target = pick_install_target(libraries, "NewGame") assert target == root / "steamapps" / "common" / "NewGame" + + +def test_find_steam_root_prefers_default_location(tmp_path, monkeypatch): + root = tmp_path / ".local/share/Steam" + (root / "steamapps").mkdir(parents=True) + monkeypatch.setattr(library, "DEFAULT_STEAM_ROOT", root) + monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path)) + + assert library.find_steam_root() == root + + +def test_find_steam_root_falls_back_to_dot_steam(tmp_path, monkeypatch): + fallback = tmp_path / ".steam/steam" + (fallback / "steamapps").mkdir(parents=True) + monkeypatch.setattr(library, "DEFAULT_STEAM_ROOT", tmp_path / "absent") + monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path)) + + assert library.find_steam_root() == fallback + + +def test_find_steam_root_raises_when_no_steam_install(tmp_path, monkeypatch): + monkeypatch.setattr(library, "DEFAULT_STEAM_ROOT", tmp_path / "absent") + monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path)) + + with pytest.raises(FileNotFoundError, match="No Steam installation"): + library.find_steam_root() + + +def test_list_libraries_ignores_malformed_libraryfolders(tmp_path): + """A malformed or partial libraryfolders.vdf must degrade to "just the + primary library", never crash the run.""" + root = tmp_path / "Steam" + (root / "steamapps").mkdir(parents=True) + (root / "steamapps" / "libraryfolders.vdf").write_text( + vdf.dumps("libraryfolders", {"contentstatsid": "123"}) + ) + + assert [lib.path for lib in library.list_libraries(root)] == [root] + + +def test_list_libraries_skips_entries_without_a_path(tmp_path): + root = tmp_path / "Steam" + (root / "steamapps").mkdir(parents=True) + other = tmp_path / "hdd" + other.mkdir() + (root / "steamapps" / "libraryfolders.vdf").write_text( + vdf.dumps( + "libraryfolders", + { + "0": {"path": str(root)}, + "1": {"label": "no path here"}, + "2": {"path": str(other)}, + }, + ) + ) + + paths = [lib.path for lib in library.list_libraries(root)] + assert paths == [root, other.resolve()] + + +def test_list_libraries_ignores_non_dict_folder_entries(tmp_path): + root = tmp_path / "Steam" + (root / "steamapps").mkdir(parents=True) + (root / "steamapps" / "libraryfolders.vdf").write_text( + '"libraryfolders"\n{\n\t"0"\t\t"not-a-dict"\n}\n' + ) + + assert [lib.path for lib in library.list_libraries(root)] == [root] + + +def test_list_libraries_ignores_non_dict_libraryfolders_root(tmp_path, monkeypatch): + """Defensive guard: vdf.parse always yields a dict for a block today, so + inject a parser that does not, keeping the guard honest if vdf changes.""" + root = tmp_path / "Steam" + (root / "steamapps").mkdir(parents=True) + (root / "steamapps" / "libraryfolders.vdf").write_text( + vdf.dumps("libraryfolders", {"0": {"path": str(tmp_path)}}) + ) + monkeypatch.setattr( + "steam_installer.library.vdf.parse", lambda text: {"libraryfolders": "scalar"} + ) + + assert [lib.path for lib in library.list_libraries(root)] == [root] diff --git a/_installer_import/tests/test_recognize.py b/_installer_import/tests/test_recognize.py index 6a318cf..8a9f258 100644 --- a/_installer_import/tests/test_recognize.py +++ b/_installer_import/tests/test_recognize.py @@ -1,15 +1,24 @@ +import logging +import signal from pathlib import Path import pytest -from steam_installer import vdf +from steam_installer import recognize, vdf from steam_installer.library import SteamLibrary from steam_installer.recognize import ( RecognizeError, + check_ready_to_finish, + clear_steam_staging, discover_cached_depot_manifests, + download_counters_settled, ensure_installdir_correct, finish_manifest_manually, manifest_reflects_real_install, + measure_content_size, + read_app_state, + run_steamcmd_validate, + steam_client_pids, ) @@ -214,3 +223,543 @@ def test_manifest_reflects_real_install_false_when_no_manifest(tmp_path): library = SteamLibrary(tmp_path / "Steam") library.steamapps.mkdir(parents=True) assert not manifest_reflects_real_install(library, 1771300, library.common / "Game") + + +def test_finish_manifest_settles_download_counters(tmp_path): + """The regression that started all this: a manifest claiming StateFlags=4 + while still saying 22 GB of 92 GB downloaded. Steam discarded the "installed" + claim and resumed a 90 GB download.""" + library = SteamLibrary(tmp_path / "Steam") + library.steamapps.mkdir(parents=True) + data = { + "appid": "1771300", + "StateFlags": "1026", + "buildid": "23914554", + "DownloadType": "1", + "BytesToDownload": "92034161488", + "BytesDownloaded": "22129058224", + "BytesToStage": "96447764586", + "BytesStaged": "22462334559", + "StagingSize": "25876914424", + } + (library.steamapps / "appmanifest_1771300.acf").write_text( + vdf.dumps("AppState", data) + ) + install_dir = library.common / "Game" + cache_dir = install_dir / ".DepotDownloader" + cache_dir.mkdir(parents=True) + (cache_dir / "1771303_1999516201078544527.manifest").write_bytes(b"x") + + manifest_path = finish_manifest_manually( + library, 1771300, install_dir, now_unix=1000 + ) + + app_state = vdf.parse(manifest_path.read_text())["AppState"] + assert app_state["BytesDownloaded"] == app_state["BytesToDownload"] + assert app_state["BytesStaged"] == app_state["BytesToStage"] + assert app_state["StagingSize"] == "0" + # DownloadType is present on every real installed manifest -- keep it. + assert app_state["DownloadType"] == "1" + assert download_counters_settled(app_state) + + +def test_finish_manifest_excludes_shared_depots_from_installed(tmp_path): + """228989 is a SharedDepots entry owned by app 228980; claiming this app + installed its own copy contradicts SharedDepots.""" + library = SteamLibrary(tmp_path / "Steam") + _write_partial_manifest(library.steamapps, 1771300) + install_dir = library.common / "Game" + cache_dir = install_dir / ".DepotDownloader" + cache_dir.mkdir(parents=True) + (cache_dir / "228989_5753583882400741046.manifest").write_bytes(b"x") + (cache_dir / "1771303_1999516201078544527.manifest").write_bytes(b"x") + + manifest_path = finish_manifest_manually( + library, 1771300, install_dir, now_unix=1000 + ) + + app_state = vdf.parse(manifest_path.read_text())["AppState"] + assert set(app_state["InstalledDepots"]) == {"1771303"} + assert app_state["SharedDepots"] == {"228989": "228980"} + + +def test_finish_manifest_rejects_only_shared_depots(tmp_path): + library = SteamLibrary(tmp_path / "Steam") + _write_partial_manifest(library.steamapps, 1771300) + install_dir = library.common / "Game" + cache_dir = install_dir / ".DepotDownloader" + cache_dir.mkdir(parents=True) + (cache_dir / "228989_5753583882400741046.manifest").write_bytes(b"x") + + with pytest.raises(RecognizeError, match="shared depot"): + finish_manifest_manually(library, 1771300, install_dir, now_unix=1000) + + +def test_measure_content_size_excludes_depotdownloader_cache(tmp_path): + install_dir = tmp_path / "Game" + cache_dir = install_dir / ".DepotDownloader" / "staging" / "Data" + cache_dir.mkdir(parents=True) + (install_dir / "game.bin").write_bytes(b"x" * 100) + (install_dir / ".DepotDownloader" / "d.manifest").write_bytes(b"y" * 5000) + (cache_dir / "staged.pak").write_bytes(b"z" * 9000) + + assert measure_content_size(install_dir) == 100 + + +def test_download_counters_settled_detects_partial_download(): + assert not download_counters_settled( + {"BytesToDownload": "92", "BytesDownloaded": "22"} + ) + assert not download_counters_settled({"BytesToStage": "96", "BytesStaged": "22"}) + assert not download_counters_settled({"StagingSize": "25876914424"}) + assert download_counters_settled( + {"BytesToDownload": "92", "BytesDownloaded": "92", "StagingSize": "0"} + ) + # Steam omits these on some apps; absence must not be treated as a failure. + assert download_counters_settled({}) + + +def test_manifest_reflects_real_install_false_when_counters_unsettled(tmp_path): + library = SteamLibrary(tmp_path / "Steam") + library.steamapps.mkdir(parents=True) + data = { + "StateFlags": "4", + "installdir": "Game", + "InstalledDepots": {"1771303": {"manifest": "1999516201078544527"}}, + "BytesToDownload": "92034161488", + "BytesDownloaded": "22129058224", + } + (library.steamapps / "appmanifest_1771300.acf").write_text( + vdf.dumps("AppState", data) + ) + assert not manifest_reflects_real_install(library, 1771300, library.common / "Game") + + +def test_check_ready_to_finish_blocks_missing_depot(tmp_path, monkeypatch): + monkeypatch.setattr("steam_installer.recognize.steam_client_pids", lambda: []) + install_dir = tmp_path / "Game" + cache_dir = install_dir / ".DepotDownloader" + cache_dir.mkdir(parents=True) + (cache_dir / "1771302_257127247679847518.manifest").write_bytes(b"x") + + problems = check_ready_to_finish( + install_dir=install_dir, + app_state={"buildid": "23914554"}, + required_depots={"1771302", "1771303"}, + expected_build_id="23914554", + ) + assert any("1771303" in p for p in problems) + + +def test_check_ready_to_finish_blocks_zero_buildid(tmp_path, monkeypatch): + monkeypatch.setattr("steam_installer.recognize.steam_client_pids", lambda: []) + install_dir = tmp_path / "Game" + cache_dir = install_dir / ".DepotDownloader" + cache_dir.mkdir(parents=True) + (cache_dir / "1771303_1999516201078544527.manifest").write_bytes(b"x") + + problems = check_ready_to_finish( + install_dir=install_dir, + app_state={"buildid": "0", "TargetBuildID": "0"}, + required_depots={"1771303"}, + expected_build_id=None, + ) + assert any("buildid" in p for p in problems) + + +def test_check_ready_to_finish_blocks_build_mismatch(tmp_path, monkeypatch): + monkeypatch.setattr("steam_installer.recognize.steam_client_pids", lambda: []) + install_dir = tmp_path / "Game" + cache_dir = install_dir / ".DepotDownloader" + cache_dir.mkdir(parents=True) + (cache_dir / "1771303_1999516201078544527.manifest").write_bytes(b"x") + + problems = check_ready_to_finish( + install_dir=install_dir, + app_state={"buildid": "11111111"}, + required_depots={"1771303"}, + expected_build_id="23914554", + ) + assert any("different build" in p for p in problems) + + +def test_check_ready_to_finish_blocks_running_steam(tmp_path, monkeypatch): + """Steam owns the manifest while it runs and rewrites it from its own state.""" + monkeypatch.setattr("steam_installer.recognize.steam_client_pids", lambda: [4242]) + install_dir = tmp_path / "Game" + cache_dir = install_dir / ".DepotDownloader" + cache_dir.mkdir(parents=True) + (cache_dir / "1771303_1999516201078544527.manifest").write_bytes(b"x") + + problems = check_ready_to_finish( + install_dir=install_dir, + app_state={"buildid": "23914554"}, + required_depots={"1771303"}, + expected_build_id="23914554", + ) + assert any("4242" in p for p in problems) + + +def test_check_ready_to_finish_passes_when_everything_holds(tmp_path, monkeypatch): + monkeypatch.setattr("steam_installer.recognize.steam_client_pids", lambda: []) + install_dir = tmp_path / "Game" + cache_dir = install_dir / ".DepotDownloader" + cache_dir.mkdir(parents=True) + (cache_dir / "1771303_1999516201078544527.manifest").write_bytes(b"x") + (install_dir / "game.pak").write_bytes(b"x" * 1000) + + assert ( + check_ready_to_finish( + install_dir=install_dir, + app_state={"buildid": "23914554"}, + required_depots={"1771303"}, + expected_build_id="23914554", + ) + == [] + ) + + +def test_read_app_state_missing_file(tmp_path): + assert read_app_state(tmp_path / "nope.acf") == {} + + +def test_clear_steam_staging_removes_tree_and_patches(tmp_path): + """A StateFlags=4 manifest next to a full staging tree is the same + contradiction that made Steam resume a 90 GB download.""" + library = SteamLibrary(tmp_path / "Steam") + downloading = library.steamapps / "downloading" + staged = downloading / "1771300" + (staged / "Data").mkdir(parents=True) + (staged / "Data" / "big.pak").write_bytes(b"x" * 500) + (downloading / "state_1771300_1771303.patch").write_bytes(b"y" * 50) + # Another app's staging must be left completely alone. + other = downloading / "1628350" + other.mkdir(parents=True) + (other / "keep.pak").write_bytes(b"z" * 10) + (downloading / "state_1628350_1.patch").write_bytes(b"z" * 10) + + freed = clear_steam_staging(library, 1771300) + + assert freed == 550 + assert staged.is_dir() + assert list(staged.iterdir()) == [] + assert not (downloading / "state_1771300_1771303.patch").exists() + assert (other / "keep.pak").is_file() + assert (downloading / "state_1628350_1.patch").is_file() + + +def test_clear_steam_staging_when_nothing_staged(tmp_path): + library = SteamLibrary(tmp_path / "Steam") + (library.steamapps / "downloading").mkdir(parents=True) + assert clear_steam_staging(library, 1771300) == 0 + + +def test_check_ready_to_finish_blocks_empty_required_depot_set(tmp_path, monkeypatch): + """An empty required set would make the depot check vacuously true and wave + through a download that fetched nothing.""" + monkeypatch.setattr("steam_installer.recognize.steam_client_pids", lambda: []) + install_dir = tmp_path / "Game" + (install_dir / ".DepotDownloader").mkdir(parents=True) + + problems = check_ready_to_finish( + install_dir=install_dir, + app_state={"buildid": "23914554"}, + required_depots=set(), + expected_build_id="23914554", + ) + assert any("no depots match" in p for p in problems) + + +def test_backup_keeps_the_pristine_manifest_across_reruns(tmp_path): + """A second run must not overwrite the backup with run 1's patched output -- + that turns the recovery artifact for a 90+ GB install into a copy of the + thing it is supposed to protect against.""" + library = SteamLibrary(tmp_path / "Steam") + _write_partial_manifest(library.steamapps, 1771300) + manifest = library.steamapps / "appmanifest_1771300.acf" + pristine = manifest.read_text() + install_dir = library.common / "Game" + cache = install_dir / ".DepotDownloader" + cache.mkdir(parents=True) + (cache / "1771303_1999516201078544527.manifest").write_bytes(b"x") + + finish_manifest_manually(library, 1771300, install_dir, now_unix=1000) + finish_manifest_manually(library, 1771300, install_dir, now_unix=2000) + + assert manifest.with_suffix(".acf.bak").read_text() == pristine + + +def test_manifest_write_is_atomic(tmp_path, monkeypatch): + """A crash mid-write must not leave a truncated, unparseable manifest.""" + library = SteamLibrary(tmp_path / "Steam") + _write_partial_manifest(library.steamapps, 1771300) + manifest = library.steamapps / "appmanifest_1771300.acf" + before = manifest.read_text() + install_dir = library.common / "Game" + cache = install_dir / ".DepotDownloader" + cache.mkdir(parents=True) + (cache / "1771303_1999516201078544527.manifest").write_bytes(b"x") + + def explode(self, *args, **kwargs): + raise OSError(28, "No space left on device") + + monkeypatch.setattr("pathlib.Path.write_text", explode) + with pytest.raises(OSError): + finish_manifest_manually(library, 1771300, install_dir, now_unix=1000) + + # Original intact, and no temp file left behind. + assert manifest.read_text() == before + assert list(library.steamapps.glob("*.tmp*")) == [] + + +def test_check_ready_to_finish_blocks_when_no_game_content(tmp_path, monkeypatch): + """Cache filenames are not content: a dir holding only + .DepotDownloader/_.manifest must not be written as installed.""" + monkeypatch.setattr("steam_installer.recognize.steam_client_pids", lambda: []) + install_dir = tmp_path / "Game" + cache_dir = install_dir / ".DepotDownloader" + cache_dir.mkdir(parents=True) + (cache_dir / "1771303_1999516201078544527.manifest").write_bytes(b"x") + + problems = check_ready_to_finish( + install_dir=install_dir, + app_state={"buildid": "23914554"}, + required_depots={"1771303"}, + expected_build_id="23914554", + ) + assert any("no game content" in p for p in problems) + + +def test_check_ready_to_finish_blocks_unknown_public_build(tmp_path, monkeypatch): + """A None expected build means we cannot tell current from stale -- refuse + rather than silently skipping the comparison.""" + monkeypatch.setattr("steam_installer.recognize.steam_client_pids", lambda: []) + install_dir = tmp_path / "Game" + cache_dir = install_dir / ".DepotDownloader" + cache_dir.mkdir(parents=True) + (cache_dir / "1771303_1999516201078544527.manifest").write_bytes(b"x") + (install_dir / "game.pak").write_bytes(b"x" * 1000) + + problems = check_ready_to_finish( + install_dir=install_dir, + app_state={"buildid": "23914554"}, + required_depots={"1771303"}, + expected_build_id=None, + ) + assert any("current public build" in p for p in problems) + + +def test_gate_blocks_before_staging_is_destroyed(tmp_path, monkeypatch): + """finish_manifest_manually raises when every cached depot is shared. The + CLI deletes Steam's staging tree first, so the gate must catch this while + refusing is still free -- otherwise a failed run destroys tens of GB of + resumable download state.""" + monkeypatch.setattr("steam_installer.recognize.steam_client_pids", lambda: []) + install_dir = tmp_path / "Game" + cache_dir = install_dir / ".DepotDownloader" + cache_dir.mkdir(parents=True) + (cache_dir / "1001_555.manifest").write_bytes(b"x") + (install_dir / "game.pak").write_bytes(b"x" * 1000) + + problems = check_ready_to_finish( + install_dir=install_dir, + app_state={"buildid": "999", "SharedDepots": {"1001": "228980"}}, + required_depots={"1001"}, + expected_build_id="999", + ) + assert any("nothing to record as installed" in p for p in problems) + + +def _fake_proc(tmp_path, entries): + """Build a /proc-shaped tree: {pid: exe_target_path_or_None}.""" + proc = tmp_path / "proc" + proc.mkdir() + for name, target in entries.items(): + entry = proc / name + entry.mkdir() + if target is not None: + real = tmp_path / "bin" / target + real.parent.mkdir(parents=True, exist_ok=True) + real.write_text("") + (entry / "exe").symlink_to(real) + return proc + + +def test_steam_client_pids_finds_native_and_flatpak(tmp_path, monkeypatch): + """Matching on the executable name only: an earlier version also demanded + 'ubuntu12_32' in the path, so a Flatpak Steam (/app/bin/steam) silently + failed open and the whole guard stopped guarding.""" + proc = _fake_proc( + tmp_path, + { + "111": "steam", + "222": "steamwebhelper", + "333": "steamcmd", + "444": "bash", + "self": "steam", + "555": None, + }, + ) + monkeypatch.setattr("steam_installer.recognize.PROC_DIR", proc) + + assert sorted(steam_client_pids()) == [111, 222] + + +def test_steam_client_pids_ignores_vanished_processes(tmp_path, monkeypatch): + """A pid can exit between listing /proc and resolving its exe.""" + proc = _fake_proc(tmp_path, {"111": "steam"}) + (proc / "999").mkdir() + (proc / "999" / "exe").symlink_to(tmp_path / "gone") + monkeypatch.setattr("steam_installer.recognize.PROC_DIR", proc) + + class _Boom(type(proc)): + pass + + assert steam_client_pids() == [111] + + +def test_run_steamcmd_validate_argv_and_result(monkeypatch): + seen = {} + + def fake_run_logged(cmd, logger, timeout=None): + seen["cmd"] = cmd + seen["timeout"] = timeout + return 0, "all good" + + monkeypatch.setattr("steam_installer.recognize.runlog.run_logged", fake_run_logged) + + result = run_steamcmd_validate(1771300, "krzys2000", logging.getLogger("t")) + + cmd = seen["cmd"] + # The platform flag must precede +login, and no force_install_dir may appear: + # it sets a LIBRARY ROOT and pointing it at the game dir caused the original + # "Invalid platform" failure. + assert cmd.index("+@sSteamCmdForcePlatformType") < cmd.index("+login") + assert "force_install_dir" not in " ".join(cmd) + assert cmd[cmd.index("+app_update") + 1 : cmd.index("+app_update") + 3] == [ + "1771300", + "validate", + ] + assert result.completed and result.returncode == 0 + assert result.output == "all good" + assert not result.crashed_on_install_script + + +def test_run_steamcmd_validate_detects_the_install_script_segfault(monkeypatch): + """The known steamcmd bug kills the process with SIGSEGV; checking the + signal beats grepping captured text for a message string.""" + monkeypatch.setattr( + "steam_installer.recognize.runlog.run_logged", + lambda cmd, logger, timeout=None: (-signal.SIGSEGV, ""), + ) + + result = run_steamcmd_validate(1, "u", logging.getLogger("t")) + + assert result.crashed_on_install_script + assert not result.completed + + +def test_ensure_installdir_correct_ignores_malformed_manifest(tmp_path, monkeypatch): + """Defensive guard: vdf.parse always yields a dict today, so inject a parser + that does not, to keep the guard honest if vdf ever changes.""" + library = SteamLibrary(tmp_path / "Steam") + library.steamapps.mkdir(parents=True) + manifest = library.steamapps / "appmanifest_1771300.acf" + manifest.write_text(vdf.dumps("AppState", {"installdir": "Stale"})) + before = manifest.read_text() + monkeypatch.setattr( + "steam_installer.recognize.vdf.parse", lambda text: {"AppState": "scalar"} + ) + + ensure_installdir_correct(library, 1771300, library.common / "Game") + + assert manifest.read_text() == before + + +def test_ensure_installdir_correct_is_a_noop_when_already_right(tmp_path): + library = SteamLibrary(tmp_path / "Steam") + library.steamapps.mkdir(parents=True) + manifest = library.steamapps / "appmanifest_1771300.acf" + manifest.write_text(vdf.dumps("AppState", {"installdir": "Game"})) + + ensure_installdir_correct(library, 1771300, library.common / "Game") + + assert not manifest.with_suffix(".acf.bak").exists() + + +def test_manifest_reflects_real_install_false_on_malformed_appstate( + tmp_path, monkeypatch +): + library = SteamLibrary(tmp_path / "Steam") + library.steamapps.mkdir(parents=True) + (library.steamapps / "appmanifest_1771300.acf").write_text( + vdf.dumps("AppState", {"StateFlags": "4"}) + ) + monkeypatch.setattr( + "steam_installer.recognize.vdf.parse", lambda text: {"AppState": "scalar"} + ) + assert not manifest_reflects_real_install(library, 1771300, library.common / "Game") + + +def test_finish_manifest_rejects_malformed_appstate(tmp_path, monkeypatch): + library = SteamLibrary(tmp_path / "Steam") + _write_partial_manifest(library.steamapps, 1771300) + install_dir = library.common / "Game" + cache = install_dir / ".DepotDownloader" + cache.mkdir(parents=True) + (cache / "1771303_1.manifest").write_bytes(b"x") + monkeypatch.setattr( + "steam_installer.recognize.vdf.parse", lambda text: {"AppState": "scalar"} + ) + + with pytest.raises(RecognizeError, match="not a valid AppState"): + finish_manifest_manually(library, 1771300, install_dir, now_unix=1) + + +def test_steam_client_pids_skips_unreadable_exe(tmp_path, monkeypatch): + """/proc//exe raises for processes we don't own; that must not abort + the scan and silently disable the guard.""" + proc = tmp_path / "proc" + (proc / "111").mkdir(parents=True) + (proc / "222").mkdir() + real = tmp_path / "bin" / "steam" + real.parent.mkdir(parents=True) + real.write_text("") + (proc / "222" / "exe").symlink_to(real) + monkeypatch.setattr("steam_installer.recognize.PROC_DIR", proc) + + original = Path.resolve + + def flaky(self, *args, **kwargs): + if self.parent.name == "111": + raise PermissionError("not owned by this user") + return original(self, *args, **kwargs) + + monkeypatch.setattr(Path, "resolve", flaky) + + assert steam_client_pids() == [222] + + +def test_write_atomic_cleans_up_its_temp_file_on_failure(tmp_path, monkeypatch): + target = tmp_path / "appmanifest_1.acf" + target.write_text("original") + + def explode(self, *args, **kwargs): + raise OSError(28, "No space left on device") + + monkeypatch.setattr("pathlib.Path.write_text", explode) + with pytest.raises(OSError): + recognize._write_atomic(target, "new content") + + assert list(tmp_path.glob("*.tmp*")) == [] + + +def test_measure_content_size_skips_directories_and_symlinks(tmp_path): + """Directories have a size of their own, and a symlink would double-count + its target -- neither is game content Steam should see in SizeOnDisk.""" + install_dir = tmp_path / "Game" + (install_dir / "Data" / "Levels").mkdir(parents=True) + (install_dir / "Data" / "real.pak").write_bytes(b"x" * 250) + (install_dir / "Data" / "link.pak").symlink_to(install_dir / "Data" / "real.pak") + + assert measure_content_size(install_dir) == 250 diff --git a/_installer_import/tests/test_resolve.py b/_installer_import/tests/test_resolve.py new file mode 100644 index 0000000..e9a46a3 --- /dev/null +++ b/_installer_import/tests/test_resolve.py @@ -0,0 +1,99 @@ +import io +import json +import urllib.error + +import pytest + +from steam_installer import resolve + + +class _FakeResponse(io.BytesIO): + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + +def test_search_parses_items(monkeypatch): + payload = {"items": [{"id": 1771300, "name": "Kingdom Come: Deliverance II"}]} + monkeypatch.setattr( + resolve.urllib.request, + "urlopen", + lambda url, timeout: _FakeResponse(json.dumps(payload).encode()), + ) + + results = resolve.search("kingdom come") + + assert results == [ + resolve.SearchResult(appid=1771300, name="Kingdom Come: Deliverance II") + ] + + +def test_search_quotes_the_term(monkeypatch): + seen = {} + + def fake_urlopen(url, timeout): + seen["url"] = url + return _FakeResponse(b'{"items": []}') + + monkeypatch.setattr(resolve.urllib.request, "urlopen", fake_urlopen) + + resolve.search("kingdom come/2") + + assert "kingdom%20come/2" in seen["url"] or "kingdom%20come%2F2" in seen["url"] + + +def test_search_missing_items_key_returns_empty(monkeypatch): + monkeypatch.setattr( + resolve.urllib.request, "urlopen", lambda url, timeout: _FakeResponse(b"{}") + ) + assert resolve.search("nothing") == [] + + +@pytest.mark.parametrize( + "exc", [urllib.error.URLError("tls blocked"), TimeoutError("timed out")] +) +def test_search_network_failure_becomes_search_unavailable(monkeypatch, exc): + """store.steampowered.com is known to reject scripted clients on some + networks -- that is not a code bug, so it gets its own exception type.""" + + def boom(url, timeout): + raise exc + + monkeypatch.setattr(resolve.urllib.request, "urlopen", boom) + + with pytest.raises(resolve.SearchUnavailable): + resolve.search("kingdom come") + + +def _results(): + return [ + resolve.SearchResult(appid=1, name="One"), + resolve.SearchResult(appid=2, name="Two"), + ] + + +def test_prompt_confirm_returns_the_chosen_result(monkeypatch): + monkeypatch.setattr("builtins.input", lambda *a: "2") + assert resolve.prompt_confirm(_results()).appid == 2 + + +def test_prompt_confirm_reprompts_until_valid(monkeypatch, capsys): + answers = iter(["", "banana", "9", "1"]) + monkeypatch.setattr("builtins.input", lambda *a: next(answers)) + + assert resolve.prompt_confirm(_results()).appid == 1 + assert capsys.readouterr().out.count("Invalid choice") == 3 + + +def test_prompt_confirm_zero_cancels(monkeypatch): + monkeypatch.setattr("builtins.input", lambda *a: "0") + with pytest.raises(resolve.ResolveError, match="Cancelled"): + resolve.prompt_confirm(_results()) + + +def test_prompt_confirm_rejects_empty_result_list(): + """Never guess an app: no matches must be an error, not a default pick.""" + with pytest.raises(resolve.ResolveError, match="No matches"): + resolve.prompt_confirm([]) diff --git a/_installer_import/tests/test_runlog.py b/_installer_import/tests/test_runlog.py new file mode 100644 index 0000000..61521db --- /dev/null +++ b/_installer_import/tests/test_runlog.py @@ -0,0 +1,210 @@ +import errno +import logging +import os +import subprocess +import sys + +import pytest + +from steam_installer import runlog + + +@pytest.fixture(autouse=True) +def isolated_log_dir(tmp_path, monkeypatch): + """Never write to the real ~/.local/state during tests.""" + 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() + + +def test_setup_creates_log_file_and_latest_symlink(): + log = runlog.setup(1771300) + + assert log.path.is_file() + assert "1771300" in log.path.name + latest = runlog.LOG_DIR / "latest.log" + assert latest.is_symlink() + assert latest.resolve() == log.path.resolve() + + +def test_setup_without_appid_still_names_the_file(): + log = runlog.setup(None) + assert "noappid" in log.path.name + + +def test_setup_twice_does_not_duplicate_handlers(): + """A second setup() in one process must not write every line twice.""" + runlog.setup(1) + log = runlog.setup(2) + log.logger.info("once") + assert log.path.read_text().count("once") == 1 + + +def test_run_logged_records_command_output_and_exit_code(capfd): + log = runlog.setup(1771300) + + returncode, output = runlog.run_logged( + ["bash", "-c", "echo to-stdout; echo to-stderr >&2; exit 7"], log.logger + ) + + assert returncode == 7 + assert "to-stdout" in output + assert "to-stderr" in output + + # Mirrored to the terminal... + assert "to-stdout" in capfd.readouterr().out + # ...and recorded in the log, along with the argv and exit code. + contents = log.path.read_text() + assert "to-stdout" in contents + assert "echo to-stdout" in contents + assert "exit=7" in contents + + +def test_run_logged_child_sees_a_tty(): + """The whole reason for the pty: steamcmd only prompts interactively for a + password when it believes it is attached to a terminal. A plain pipe makes + the prompt invisible and the run looks hung. + """ + log = runlog.setup(1771300) + _, output = runlog.run_logged( + [sys.executable, "-c", "import sys; print(sys.stdout.isatty())"], log.logger + ) + assert "True" in output + + +def test_run_logged_times_out(): + log = runlog.setup(1771300) + with pytest.raises(subprocess.TimeoutExpired): + runlog.run_logged(["sleep", "10"], log.logger, timeout=0.5) + + +def test_file_contents_records_manifest_verbatim(tmp_path): + log = runlog.setup(1771300) + manifest = tmp_path / "appmanifest_1771300.acf" + manifest.write_text('"AppState"\n{\n\t"StateFlags"\t\t"4"\n}\n') + + log.file_contents("Manifest before run", manifest) + + contents = log.path.read_text() + assert "Manifest before run" in contents + assert '"StateFlags"' in contents + + +def test_file_contents_survives_missing_file(tmp_path): + """A first-ever install has no manifest yet; that must not kill the run.""" + log = runlog.setup(1771300) + log.file_contents("Manifest before run", tmp_path / "absent.acf") + assert "unreadable" in log.path.read_text() + + +def test_run_logged_records_output_even_on_timeout(): + """A steamcmd hang at the 3600s timeout is exactly when the log matters + most; discarding what the child said before hanging defeats the point.""" + log = runlog.setup(1771300) + marker = "TIMEOUT" + "MARKER" + with pytest.raises(subprocess.TimeoutExpired) as excinfo: + runlog.run_logged( + ["bash", "-c", f'printf "%s\\n" "{marker}"; sleep 30'], + log.logger, + timeout=1.0, + ) + + contents = log.path.read_text() + assert "--- output" in contents + assert marker in contents + assert "TIMED OUT" in contents + assert marker.encode() in excinfo.value.output + + +def test_point_latest_at_survives_a_broken_log_dir(monkeypatch, tmp_path): + """A stale or unwritable latest.log must never fail an otherwise fine run.""" + log = runlog.setup(1) + latest = runlog.LOG_DIR / "latest.log" + latest.unlink() + latest.mkdir() # a directory where the symlink should go + + runlog._point_latest_at(log.path) # must not raise + + assert latest.is_dir() + + +def test_run_logged_closes_pty_fds_when_spawn_fails(monkeypatch): + """A leaked master/slave pair per failed spawn would exhaust the fd table.""" + log = runlog.setup(1) + before = len(os.listdir("/proc/self/fd")) + + with pytest.raises(FileNotFoundError): + runlog.run_logged(["definitely-not-a-real-binary-xyz"], log.logger) + + assert len(os.listdir("/proc/self/fd")) == before + + +def test_run_logged_stops_when_select_fails(monkeypatch): + """A closed master fd surfaces as OSError from select; end the relay.""" + log = runlog.setup(1) + monkeypatch.setattr( + runlog.select, "select", lambda *a, **kw: (_ for _ in ()).throw(OSError) + ) + + returncode, output = runlog.run_logged(["true"], log.logger) + + assert returncode == 0 + assert output == "" + + +def test_run_logged_reraises_unexpected_read_errors(monkeypatch): + """EIO means "child closed the pty" and ends the loop; anything else is a + real failure and must not be swallowed.""" + log = runlog.setup(1) + # Force select to always report readable so os.read is definitely reached. + monkeypatch.setattr(runlog.select, "select", lambda *a, **kw: ([a[0][0]], [], [])) + + def bad_read(fd, size): + raise OSError(errno.EBADF, "bad file descriptor") + + monkeypatch.setattr(runlog, "_read_pty", bad_read) + + with pytest.raises(OSError) as excinfo: + runlog.run_logged(["bash", "-c", "echo hi; sleep 0.2"], log.logger) + assert excinfo.value.errno == errno.EBADF + + +def test_run_logged_exits_when_child_dies_without_output(monkeypatch): + """select never reports readable, so the loop must notice via poll() that + the child is gone rather than spinning forever.""" + log = runlog.setup(1) + monkeypatch.setattr(runlog.select, "select", lambda *a, **kw: ([], [], [])) + + returncode, output = runlog.run_logged(["true"], log.logger) + + assert returncode == 0 + assert output == "" + + +def test_run_logged_handles_empty_read(monkeypatch): + """A zero-byte read is EOF on the pty.""" + log = runlog.setup(1) + real_read = runlog._read_pty + calls = {"n": 0} + + def once_then_eof(fd, size): + calls["n"] += 1 + if calls["n"] == 1: + return real_read(fd, size) + return b"" + + monkeypatch.setattr(runlog, "_read_pty", once_then_eof) + + returncode, _ = runlog.run_logged(["bash", "-c", "echo hi"], log.logger) + assert returncode == 0 + + +def test_run_logged_survives_a_child_that_writes_nothing(): + """Exercises the poll()-based exit when the pty never becomes readable.""" + log = runlog.setup(1) + returncode, output = runlog.run_logged(["true"], log.logger) + assert returncode == 0 + assert output == "" diff --git a/_installer_import/tests/test_vdf.py b/_installer_import/tests/test_vdf.py index e742f07..bab3a95 100644 --- a/_installer_import/tests/test_vdf.py +++ b/_installer_import/tests/test_vdf.py @@ -1,3 +1,5 @@ +import pytest + from steam_installer import vdf @@ -66,3 +68,80 @@ def test_roundtrip_dumps_then_parse(): def test_empty_input_returns_empty_dict(): assert vdf.parse("") == {} + + +def test_dumps_reescapes_backslashes_so_round_trip_is_stable(): + r"""Real regression: appmanifest_228980.acf (Steamworks Common + Redistributables) stores Windows paths like + `_CommonRedist\\vcredist\\2015\\installscript.vdf`. The tokenizer consumes + the escapes, so writing values back unescaped halved the backslashes on + every parse/dump cycle and silently corrupted the InstallScripts paths.""" + original = ( + '"AppState"\n{\n\t"InstallScripts"\n\t{\n' + '\t\t"228990"\t\t"_CommonRedist\\\\vcredist\\\\2015\\\\installscript.vdf"\n' + "\t}\n}\n" + ) + once = vdf.dumps("AppState", vdf.parse(original)["AppState"]) + assert once.strip() == original.strip() + + # And it must be a fixed point, not merely correct on the first pass. + twice = vdf.dumps("AppState", vdf.parse(once)["AppState"]) + assert twice == once + assert ( + vdf.parse(twice)["AppState"]["InstallScripts"]["228990"] + == "_CommonRedist\\vcredist\\2015\\installscript.vdf" + ) + + +def test_dumps_escapes_embedded_quotes(): + data = {"name": 'Game "Deluxe" Edition'} + assert vdf.parse(vdf.dumps("AppState", data))["AppState"] == data + + +def test_parse_error_message_includes_position(): + err = vdf.VdfParseError("boom", 7) + assert str(err) == "boom (at position 7)" + + +def test_parse_empty_input_returns_empty_dict(): + assert vdf.parse("") == {} + assert vdf.parse(" \n\t ") == {} + + +def test_parse_rejects_root_key_without_a_block(): + with pytest.raises(vdf.VdfParseError, match="expected '{' after root key"): + vdf.parse('"AppState"\n') + + +def test_parse_rejects_truncated_input_after_a_key(): + """A crash mid-write used to leave exactly this shape on disk.""" + with pytest.raises(vdf.VdfParseError, match="unexpected end of input"): + vdf.parse('"AppState"\n{\n\t"installdir"') + + +def test_parse_tolerates_unquoted_tokens(): + """Rare in Steam's own files, but the tokenizer accepts them.""" + assert vdf.parse("AppState\n{\n\tinstalldir\tGame\n}\n") == { + "AppState": {"installdir": "Game"} + } + + +def test_parse_ignores_comment_lines(): + text = '// leading comment\n"AppState"\n{\n\t"installdir"\t\t"Game"\n}\n' + assert vdf.parse(text) == {"AppState": {"installdir": "Game"}} + + +def test_parse_reads_scalar_value_after_key(): + """The non-block branch: a key whose value is a plain token.""" + assert vdf.parse('"AppState"\n{\n\t"StateFlags"\t\t"4"\n}\n') == { + "AppState": {"StateFlags": "4"} + } + + +def test_parse_tolerates_an_unterminated_block(): + """A truncated manifest (what a crash mid-write leaves behind) parses to + whatever was complete, rather than raising -- the caller's own validity + checks then reject it.""" + assert vdf.parse('"AppState"\n{\n\t"installdir"\t\t"Game"\n') == { + "AppState": {"installdir": "Game"} + }