Files
uconsole_asw_game/tests/test_uconsole_updater.py
T
Claude b4e468fe20 uConsole updater: large release downloads no longer cut off after 60 s (1.3.293)
The uConsole stayed on 1.3.262: every "Update now" logged
"git fetch ... +refs/tags/v1.3.292 ... timed out after 60 seconds".
Releases since then carry many MB of new manual pictures, and git drops a
fetch that is cut off half way, so on a slower WLAN it could never finish.

- Release and main fetches get a 30 min cap (DOWNLOAD_TIMEOUT_S); a stalled
  remote still stops after 15 s below 1 KB/s (GIT_ENV).
- The start window says "Downloading update" before the tag fetch instead
  of "Checking for updates" for the whole wait.
- Regression test; uConsole install guide (EN/DE) explains the new limit and
  the one-time manual fetch for checkouts still on the old updater.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JVnJn1auJiS3FRATib8EGp
2026-10-07 16:12:37 +00:00

564 lines
22 KiB
Python

"""Self-updating uConsole launcher: runs against throwaway local git repos."""
from importlib.machinery import SourceFileLoader
from importlib.util import module_from_spec, spec_from_loader
from pathlib import Path
import os
import stat
import subprocess
import sys
import time
import pytest
if os.name != "posix":
# The uConsole helpers (fcntl, root checks, executable bits) are Linux-only.
pytest.skip("uConsole (Linux) only", allow_module_level=True)
ROOT = Path(__file__).parents[1]
UPDATER = ROOT / "packaging/uconsole/u_jagd_updater.py"
LAUNCH = ROOT / "packaging/uconsole/u-jagd-launch"
INSTALL = ROOT / "packaging/uconsole/install.sh"
SPLASH = ROOT / "packaging/uconsole/u_jagd_splash.py"
def load_updater():
loader = SourceFileLoader("u_jagd_updater_test", str(UPDATER))
spec = spec_from_loader(loader.name, loader)
module = module_from_spec(spec)
loader.exec_module(module)
return module
def run(cwd, *args):
return subprocess.run(args, cwd=cwd, check=True, capture_output=True,
text=True).stdout.strip()
def commit_version(work, version, extra=None):
(work / "src/core").mkdir(parents=True, exist_ok=True)
(work / "src/core/version.py").write_text(f'APP_VERSION = "{version}"\n')
(work / "requirements.txt").write_text(extra or "pygame\n")
run(work, "git", "add", "-A")
run(work, "git", "commit", "-qm", version)
return run(work, "git", "rev-parse", "HEAD")
@pytest.fixture
def repos(tmp_path, monkeypatch):
"""(upstream work tree, installed clone) sharing a bare origin."""
monkeypatch.setenv("HOME", str(tmp_path / "home"))
for key, value in (("GIT_AUTHOR_NAME", "t"), ("GIT_AUTHOR_EMAIL", "t@t"),
("GIT_COMMITTER_NAME", "t"), ("GIT_COMMITTER_EMAIL", "t@t")):
monkeypatch.setenv(key, value)
monkeypatch.delenv("U_JAGD_NO_UPDATE", raising=False)
monkeypatch.delenv("U_JAGD_UPDATE_CHANNEL", raising=False)
bare = tmp_path / "origin.git"
run(tmp_path, "git", "init", "-q", "--bare", "-b", "main", str(bare))
work = tmp_path / "work"
run(tmp_path, "git", "clone", "-q", str(bare), str(work))
run(work, "git", "checkout", "-qb", "main")
commit_version(work, "1.3.8")
run(work, "git", "push", "-q", "origin", "main")
app = tmp_path / "app"
run(tmp_path, "git", "clone", "-q", "-b", "main", str(bare), str(app))
return work, app
def publish(work, version, extra=None, tag=True):
head = commit_version(work, version, extra)
run(work, "git", "push", "-q", "origin", "main")
if tag:
run(work, "git", "tag", f"v{version}")
run(work, "git", "push", "-q", "origin", f"v{version}")
return head
@pytest.fixture
def updater(monkeypatch):
module = load_updater()
calls = {"install": [], "verify": "1.3.9"}
monkeypatch.setattr(module, "ensure_venv",
lambda app, force_install=False: calls["install"].append(force_install))
monkeypatch.setattr(module, "verify", lambda app: calls["verify"])
monkeypatch.setattr(module, "notify", lambda message: None)
monkeypatch.setattr(module, "online", lambda timeout=None: True)
module.calls = calls
return module
def head(app):
return run(app, "git", "rev-parse", "HEAD")
def test_newer_release_fast_forwards_and_keeps_branch(repos, updater, monkeypatch):
work, app = repos
target = publish(work, "1.3.9")
publish(work, "1.3.10", tag=False) # unreleased main commit is not taken
monkeypatch.setattr(updater, "fetch_latest_release", lambda url=None: "v1.3.9")
assert updater.update(app) is True
assert head(app) == target
assert run(app, "git", "rev-parse", "--abbrev-ref", "HEAD") == "main"
assert updater.calls["install"] == [False]
assert updater.installed_version(app) == (1, 3, 9)
def test_dependency_change_reinstalls(repos, updater, monkeypatch):
work, app = repos
publish(work, "1.3.9", extra="pygame\nnumpy\n")
monkeypatch.setattr(updater, "fetch_latest_release", lambda url=None: "v1.3.9")
assert updater.update(app) is True
assert updater.calls["install"] == [True]
@pytest.mark.parametrize("answer", [None, "v1.3.8", "v1.3.7"])
def test_offline_or_not_newer_starts_installed_version(repos, updater, monkeypatch, answer):
work, app = repos
before = head(app)
publish(work, "1.3.9")
monkeypatch.setattr(updater, "fetch_latest_release", lambda url=None: answer)
assert updater.update(app) is False
assert head(app) == before
def test_without_release_follows_main(repos, updater, monkeypatch):
work, app = repos
target = publish(work, "1.3.9", tag=False)
monkeypatch.setattr(updater, "fetch_latest_release", lambda url=None: "")
assert updater.update(app) is True
assert head(app) == target
def test_local_changes_and_other_branches_are_never_touched(repos, updater, monkeypatch):
work, app = repos
before = head(app)
publish(work, "1.3.9")
monkeypatch.setattr(updater, "fetch_latest_release", lambda url=None: "v1.3.9")
(app / "requirements.txt").write_text("edited\n")
assert updater.update(app) is False
assert head(app) == before
assert (app / "requirements.txt").read_text() == "edited\n"
run(app, "git", "checkout", "-q", "--", "requirements.txt")
run(app, "git", "checkout", "-qb", "feature")
assert updater.update(app) is False
assert head(app) == before
def test_broken_update_rolls_back(repos, updater, monkeypatch):
work, app = repos
before = head(app)
publish(work, "1.3.9")
monkeypatch.setattr(updater, "fetch_latest_release", lambda url=None: "v1.3.9")
updater.calls["verify"] = None
assert updater.update(app) is False
assert head(app) == before
assert updater.installed_version(app) == (1, 3, 8)
log = (Path(os.environ["HOME"]) / ".u-jagd/updater.log").read_text()
assert "rolling back" in log
updater.calls["verify"] = "1.3.9"
assert updater.update(app) is False # the failed commit is not retried
target = publish(work, "1.3.10")
monkeypatch.setattr(updater, "fetch_latest_release", lambda url=None: "v1.3.10")
assert updater.update(app) is True
assert head(app) == target
def test_no_update_env_skips(repos, updater, monkeypatch):
work, app = repos
publish(work, "1.3.9")
monkeypatch.setenv("U_JAGD_NO_UPDATE", "1")
monkeypatch.setattr(updater, "fetch_latest_release",
lambda url=None: pytest.fail("no network while disabled"))
assert updater.update(app) is False
def test_tag_and_version_parsing():
module = load_updater()
assert module.parse_tag("v1.3.10") == (1, 3, 10)
assert module.parse_tag("v1.3.10") > module.parse_tag("v1.3.9")
for bad in ("1.3.9", "v1.3", "v1.3.9-rc1", None, 7):
assert module.parse_tag(bad) is None
assert module.parse_version('X = 1\nAPP_VERSION = "1.3.8"\n') == (1, 3, 8)
def test_running_game_blocks_background_update(tmp_path, monkeypatch):
module = load_updater()
monkeypatch.setenv("HOME", str(tmp_path))
held = module.GameLock()
assert held.try_acquire()
monkeypatch.setattr(module, "update", lambda app=None: pytest.fail("updated under game"))
assert module.background_update() == 0
os.close(held.fd)
def test_setup_and_uninstall_desktop_integration(tmp_path, monkeypatch):
module = load_updater()
home = tmp_path / "home"
(home / "Desktop").mkdir(parents=True)
monkeypatch.setenv("HOME", str(home))
monkeypatch.delenv("XDG_DATA_HOME", raising=False)
monkeypatch.delenv("XDG_CONFIG_HOME", raising=False)
monkeypatch.setattr(module, "ensure_venv", lambda app, force_install=False: None)
monkeypatch.setattr(module, "systemctl", lambda *args: True)
monkeypatch.setattr(module, "desktop_dir", lambda: home / "Desktop")
old_units = home / ".config/systemd/user"
old_units.mkdir(parents=True)
for name in module.TIMER_UNITS:
(old_units / name).write_text("[Unit]\n")
assert module.setup(ROOT) == 0
entry = (home / ".local/share/applications/u-jagd.desktop").read_text()
assert f'Exec="{LAUNCH}"' in entry and "Categories=Game;" in entry
assert (home / "Desktop/u-jagd.desktop").stat().st_mode & stat.S_IXUSR
assert (home / ".local/bin/u-jagd").resolve() == LAUNCH
assert "aktualisiert sich selbst" not in entry
# No background timer any more; the one of older releases is removed.
assert not (home / ".config/systemd/user/u-jagd-update.timer").exists()
assert module.uninstall() == 0
assert not (home / ".local/bin/u-jagd").is_symlink()
assert not (home / ".local/share/applications/u-jagd.desktop").exists()
assert not (home / "Desktop/u-jagd.desktop").exists()
def test_scripts_are_executable_posix_shell():
for script in (LAUNCH, INSTALL, UPDATER):
assert script.stat().st_mode & stat.S_IXUSR, script
for script in (LAUNCH, INSTALL):
subprocess.run(["sh", "-n", str(script)], check=True)
assert "releases/latest" in UPDATER.read_text()
@pytest.mark.skipif(os.geteuid() == 0, reason="the installer refuses to run as root")
def test_installer_updates_checkout_that_predates_it(repos, tmp_path):
"""An old ~/games/u-jagd without the updater is fast-forwarded first."""
work, app = repos
stub = work / "packaging/uconsole/u_jagd_updater.py"
stub.parent.mkdir(parents=True)
stub.write_text("import sys\nprint('stub', *sys.argv[1:])\n")
run(work, "git", "add", "-A")
run(work, "git", "commit", "-qm", "installer")
run(work, "git", "push", "-q", "origin", "main")
result = subprocess.run(["sh", str(INSTALL)], capture_output=True, text=True,
env={**os.environ, "U_JAGD_DIR": str(app),
"U_JAGD_NO_HOTSPOT": "1"}, check=True)
assert "stub update" in result.stdout and "stub setup" in result.stdout
assert (app / "packaging/uconsole/u_jagd_updater.py").exists()
def test_update_reports_each_step(repos, updater, monkeypatch):
work, app = repos
publish(work, "1.3.9", extra="pygame\nnumpy\n")
monkeypatch.setattr(updater, "fetch_latest_release", lambda url=None: "v1.3.9")
steps = []
assert updater.update(app, progress=lambda key, **v: steps.append((key, v))) is True
assert steps == [("check", {}), ("download", {"label": "v1.3.9"}),
("deps", {}), ("verify", {})]
def test_release_download_is_announced_and_not_cut_off_after_a_minute(repos, updater, monkeypatch):
# A release with new manual pictures is tens of MB: on the uConsole's
# WLAN the tag fetch took longer than the 60 s git cap, timed out at
# every "Update now" and the game stayed on 1.3.262.
work, app = repos
publish(work, "1.3.9")
monkeypatch.setattr(updater, "fetch_latest_release", lambda url=None: "v1.3.9")
events = []
real_git = updater.git
def git(app_dir, *args, timeout=updater.GIT_TIMEOUT_S):
if args[0] == "fetch":
events.append(("fetch", timeout))
return real_git(app_dir, *args, timeout=timeout)
monkeypatch.setattr(updater, "git", git)
assert updater.update(app, progress=lambda key, **v: events.append((key, v))) is True
assert events[:3] == [("check", {}), ("download", {"label": "v1.3.9"}),
("fetch", updater.DOWNLOAD_TIMEOUT_S)]
assert updater.DOWNLOAD_TIMEOUT_S >= 15 * 60
assert updater.GIT_ENV["GIT_HTTP_LOW_SPEED_TIME"] == "15" # stalls still stop
def test_messages_have_same_keys_and_follow_saved_language(tmp_path, monkeypatch):
module = load_updater()
assert module.MESSAGES["de"].keys() == module.MESSAGES["en"].keys()
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setenv("LANG", "en_US.UTF-8")
monkeypatch.delenv("LC_ALL", raising=False)
monkeypatch.delenv("LC_MESSAGES", raising=False)
assert module.language() == "en"
(tmp_path / ".u-jagd").mkdir()
(tmp_path / ".u-jagd/settings.json").write_text('{"language": "de"}')
assert module.message("download", label="v1.3.9") == "Lade Update v1.3.9 …"
class Execed(Exception):
pass
def launch_env(module, tmp_path, monkeypatch):
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setenv("U_JAGD_NO_SPLASH", "1")
calls = {"shown": [], "updated": 0}
monkeypatch.setattr(module, "show_briefly", lambda app, key: calls["shown"].append(key))
monkeypatch.setattr(module, "ensure_venv", lambda app, force_install=False: None)
def fake_update(app=None, channel=None, progress=None):
calls["updated"] += 1
return False
def fake_exec(path, args, env):
calls["env"] = env
raise Execed
monkeypatch.setattr(module, "update", fake_update)
monkeypatch.setattr(module.os, "execve", fake_exec)
monkeypatch.setattr(module.os, "chdir", lambda path: None)
return calls
@pytest.mark.parametrize("role", ["game", "launch", ""])
def test_second_start_does_not_open_the_game_twice(tmp_path, monkeypatch, role):
module = load_updater()
calls = launch_env(module, tmp_path, monkeypatch)
first = module.GameLock()
assert first.try_acquire()
if role:
first.set_role(role)
assert module.launch([]) == 0
assert calls["shown"] == ["running"] and calls["updated"] == 0
assert "env" not in calls
os.close(first.fd)
def test_start_during_background_update_waits_then_starts(tmp_path, monkeypatch):
module = load_updater()
calls = launch_env(module, tmp_path, monkeypatch)
first = module.GameLock()
assert first.try_acquire()
first.set_role("update")
released = []
def acquire(self, timeout_s):
os.close(first.fd) # the background update finishes
released.append(timeout_s)
return self.try_acquire()
monkeypatch.setattr(module.GameLock, "acquire", acquire)
with pytest.raises(Execed):
module.launch(["--windowed"])
assert released and calls["shown"] == [] and calls["updated"] == 0
assert (tmp_path / ".u-jagd/updater.lock").read_text().startswith("game ")
def test_start_never_updates_and_marks_game(tmp_path, monkeypatch):
module = load_updater()
calls = launch_env(module, tmp_path, monkeypatch)
with pytest.raises(Execed):
module.launch([])
assert calls["updated"] == 0 and "U_JAGD_SPLASH_FD" not in calls["env"]
def test_update_now_waits_for_the_game_then_updates_and_starts(tmp_path, monkeypatch):
module = load_updater()
calls = launch_env(module, tmp_path, monkeypatch)
game = module.GameLock()
assert game.try_acquire()
game.set_role("game")
waited = []
def acquire(self, timeout_s):
os.close(game.fd) # the game has saved and closed
waited.append(timeout_s)
return self.try_acquire()
monkeypatch.setattr(module.GameLock, "acquire", acquire)
with pytest.raises(Execed):
module.main(["install", "--windowed"])
assert waited == [module.INSTALL_WAIT_S] and calls["shown"] == []
assert calls["updated"] == 1
def test_update_now_gives_up_when_the_game_stays_open(tmp_path, monkeypatch):
module = load_updater()
calls = launch_env(module, tmp_path, monkeypatch)
game = module.GameLock()
assert game.try_acquire()
monkeypatch.setattr(module.GameLock, "acquire", lambda self, timeout_s: False)
assert module.launch([], install=True) == 1
assert calls["updated"] == 0 and "env" not in calls
os.close(game.fd)
def test_old_background_timer_only_switches_itself_off(tmp_path, monkeypatch):
module = load_updater()
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.delenv("U_JAGD_UPDATE_NOW", raising=False)
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config"))
units = tmp_path / "config/systemd/user"
units.mkdir(parents=True)
for name in module.TIMER_UNITS:
(units / name).write_text("[Unit]\n")
commands = []
monkeypatch.setattr(module, "systemctl", lambda *args: commands.append(args) or True)
monkeypatch.setattr(module, "update", lambda app=None: pytest.fail("installed by timer"))
assert module.background_update() == 0
assert ("disable", "--now", "u-jagd-update.timer") in commands
assert not any(units.iterdir())
def test_installer_update_still_installs(tmp_path, monkeypatch):
module = load_updater()
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setenv("U_JAGD_UPDATE_NOW", "1")
done = []
monkeypatch.setattr(module, "update", lambda app=None: done.append(app) or True)
assert module.background_update() == 0 and len(done) == 1
assert 'U_JAGD_UPDATE_NOW=1 python3' in INSTALL.read_text()
def test_game_closes_start_window_pipe_once(monkeypatch):
import importlib
import src.core.launch_signal as launch_signal
launch_signal = importlib.reload(launch_signal)
read_fd, write_fd = os.pipe()
monkeypatch.setenv("U_JAGD_SPLASH_FD", str(write_fd))
launch_signal.game_visible()
assert os.read(read_fd, 1) == b"" # EOF: the start window closes
assert "U_JAGD_SPLASH_FD" not in os.environ
launch_signal.game_visible() # idempotent
os.close(read_fd)
def test_start_window_follows_status_and_closes_on_eof():
env = {**os.environ, "SDL_VIDEODRIVER": "dummy", "SDL_AUDIODRIVER": "dummy"}
proc = subprocess.Popen([sys.executable, str(SPLASH)], stdin=subprocess.PIPE, env=env)
proc.stdin.write("status\tSuche nach Updates …\nstatus\tStarte U-Jagd …\n".encode())
proc.stdin.flush()
proc.stdin.close()
assert proc.wait(timeout=30) == 0
def test_start_window_keeps_a_final_message_after_eof():
env = {**os.environ, "SDL_VIDEODRIVER": "dummy", "SDL_AUDIODRIVER": "dummy"}
proc = subprocess.Popen([sys.executable, str(SPLASH)], stdin=subprocess.PIPE, env=env)
proc.stdin.write("status\tU-Jagd läuft bereits.\nclose\t1\n".encode())
proc.stdin.close()
started = time.monotonic()
assert proc.wait(timeout=30) == 0
assert time.monotonic() - started >= 0.8
def test_offline_skips_the_update_check_at_once(repos, updater, monkeypatch):
work, app = repos
before = head(app)
publish(work, "1.3.9")
monkeypatch.setattr(updater, "online", lambda timeout=None: False)
monkeypatch.setattr(updater, "fetch_latest_release",
lambda url=None: pytest.fail("no GitHub request while offline"))
steps = []
assert updater.update(app, progress=lambda key, **v: steps.append(key)) is False
assert head(app) == before and steps == ["check"]
assert "offline" in (Path(os.environ["HOME"]) / ".u-jagd/updater.log").read_text()
def test_online_probe_gives_up_on_a_hanging_lookup(monkeypatch):
module = load_updater()
monkeypatch.delenv("https_proxy", raising=False)
monkeypatch.delenv("HTTPS_PROXY", raising=False)
def hang(address, timeout=None):
time.sleep(2)
raise OSError("unreachable")
monkeypatch.setattr(module.socket, "create_connection", hang)
started = time.monotonic()
assert module.online(timeout=0.3) is False
assert time.monotonic() - started < 1.5
def test_online_probe_uses_the_https_proxy(monkeypatch):
module = load_updater()
monkeypatch.delenv("https_proxy", raising=False)
monkeypatch.setenv("HTTPS_PROXY", "http://proxy.lan:3128")
assert module.probe_address() == ("proxy.lan", 3128)
monkeypatch.delenv("HTTPS_PROXY")
assert module.probe_address() == ("github.com", 443)
def installer_sandbox(tmp_path, *, nmcli=None, sudo_status=0, sudo=True, extra_env=None):
"""A fake checkout plus a PATH of stubs, so install.sh runs hermetically
(also as root: the stub ``id`` reports a normal user)."""
app = tmp_path / "app"
kit = app / "packaging/uconsole"
kit.mkdir(parents=True)
(app / ".git").mkdir()
(kit / "u_jagd_updater.py").write_text("import sys\nprint('stub', *sys.argv[1:])\n")
for name in ("install-hotspot-helper.sh", "u-jagd-hotspot-helper",
"io.github.db9979.u-jagd.hotspot.policy"):
(kit / name).write_text((ROOT / "packaging/uconsole" / name).read_text())
bin_dir = tmp_path / "bin"
bin_dir.mkdir()
log = tmp_path / "sudo.log"
def stub(name, body):
path = bin_dir / name
path.write_text("#!/bin/sh\n" + body + "\n")
path.chmod(0o755)
stub("id", "echo 1000")
stub("git", "exit 0")
stub("python3", f'exec "{sys.executable}" "$@"')
if sudo:
stub("sudo", f'printf "%s\\n" "$*" >> "{log}"\nexit {sudo_status}')
if nmcli is not None:
stub("nmcli", f"printf '%s\\n' {nmcli}")
for tool in ("sh", "dirname", "mkdir", "cmp", "grep", "cat"):
real = next((Path(folder) / tool for folder in ("/usr/bin", "/bin")
if (Path(folder) / tool).exists()), None)
if real is not None:
(bin_dir / tool).symlink_to(real)
env = {"PATH": str(bin_dir), "HOME": str(tmp_path / "home"),
"U_JAGD_DIR": str(app), **(extra_env or {})}
result = subprocess.run(["/bin/sh", str(INSTALL)], capture_output=True, text=True,
env=env, timeout=60)
calls = log.read_text().splitlines() if log.exists() else []
return result, calls, kit
def test_installer_sets_up_the_hotspot_helper_with_sudo(tmp_path):
result, calls, kit = installer_sandbox(tmp_path, nmcli="'eth0:ethernet' 'wlan0:wifi'")
assert result.returncode == 0, result.stderr
assert "stub update" in result.stdout and "stub setup" in result.stdout
assert f"sh {kit}/install-hotspot-helper.sh" in calls
assert "hotspot helper installed" in result.stdout
@pytest.mark.parametrize("case, hint", [
("no_networkmanager", "NetworkManager not found"),
("no_wifi", "no Wi-Fi device wlan0"),
("no_sudo", "sudo not found"),
("sudo_fails", "the hotspot helper was not installed"),
])
def test_installer_continues_without_the_hotspot_helper(tmp_path, case, hint):
options = dict(nmcli="'wlan0:wifi'")
if case == "no_networkmanager":
options["nmcli"] = None
elif case == "no_wifi":
options["nmcli"] = "'eth0:ethernet' 'wlan1:wifi'"
elif case == "no_sudo":
options["sudo"] = False
else:
options["sudo_status"] = 1
result, calls, kit = installer_sandbox(tmp_path, **options)
assert result.returncode == 0, result.stderr
assert "stub setup" in result.stdout and "installed. Start it" in result.stdout
assert hint in result.stderr
if case != "sudo_fails":
assert not any("install-hotspot-helper" in call for call in calls)
def test_installer_hotspot_opt_out(tmp_path):
result, calls, _ = installer_sandbox(tmp_path, nmcli="'wlan0:wifi'",
extra_env={"U_JAGD_NO_HOTSPOT": "1"})
assert result.returncode == 0, result.stderr
assert "skipping the hotspot helper" in result.stdout and not calls