Files
WoW-Hybrid-gateway/tests/forever_launcher_test.py
praxisandClaude Fable 5.2 7f2139d8d0 Offline test fixtures
883 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

298 lines
16 KiB
Python

#!/usr/bin/env python3
"""Portable launcher contracts; no client, credentials, DNS or server access."""
import hashlib
import importlib.util
import json
from pathlib import Path
import sys
import io
import os
import tempfile
import unittest
from unittest.mock import patch, Mock
from types import SimpleNamespace
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "ops"))
def module(name, relative):
spec = importlib.util.spec_from_file_location(name, ROOT / relative)
result = importlib.util.module_from_spec(spec)
spec.loader.exec_module(result)
return result
launcher = module("launcher", "launcher/launcher.py")
package = module("launcher_package", "launcher/package.py")
backend = module("launcher_backend", "ops/forever_launcher_backend.py")
class LauncherContracts(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix="forever launcher ")
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.backend = self.root / "ops/forever_launcher_backend.py"
self.backend.parent.mkdir()
self.backend.write_text("# installed test backend\n")
self.profile = self.root / "profile.json"
self.data = dict(schema=1, runtime_root=".", platforms={"linux": dict(
status="available", backend="ops/forever_launcher_backend.py", python=sys.executable,
sha256=hashlib.sha256(self.backend.read_bytes()).hexdigest()),
"windows": dict(status="blocked-native-runtime-port", backend="bin/ForeverBootstrap.exe")})
self.write()
def write(self):
self.profile.write_text(json.dumps(self.data))
def plan(self, endpoint="local-explicit", system="Linux"):
with patch.object(launcher.shutil, "which", side_effect=lambda x: str(x)):
return launcher.launch_plan(self.profile, endpoint, system)
def test_linux_uses_argument_vector_and_preserves_spaces(self):
command, root = self.plan()
self.assertEqual(root, self.root)
self.assertEqual(command, [sys.executable, "-u", str(self.backend), "--endpoint-profile", "local-explicit"])
def test_headless_launcher_is_fixed_to_octo_and_check_is_offline(self):
with patch.object(sys,"argv",["launcher","--check","--profile",str(self.profile)]), \
patch.object(launcher,"launch_plan",return_value=(["unused"],self.root)) as plan, \
patch.object(launcher,"supervise",side_effect=AssertionError("Check cannot launch")), \
patch.object(sys,"stdout",io.StringIO()):
self.assertEqual(launcher.main(),0)
self.assertEqual(plan.call_args.args[1],"octo")
def test_local_save_guard_not_sent_to_public_profile(self):
self.data["character_guid"] = 4518
self.write()
self.assertEqual(self.plan()[0][-2:], ["--character-guid", "4518"])
self.assertNotIn("--character-guid", self.plan("octo")[0])
def test_modified_backend_rejected_before_start(self):
self.backend.write_text("different")
with self.assertRaisesRegex(ValueError, "checksum"):
self.plan()
def test_windows_unavailable_is_explicit(self):
with self.assertRaisesRegex(ValueError, "not installed/verified"):
self.plan(system="Windows")
def test_windows_cannot_launch_linux_python_adapter(self):
self.data["platforms"]["windows"] = dict(self.data["platforms"]["linux"])
self.write()
with self.assertRaisesRegex(ValueError, "native bootstrap"):
self.plan(system="Windows")
def test_windows_native_backend_contract(self):
backend = self.root / "bin/ForeverBootstrap.exe"
backend.parent.mkdir()
backend.write_bytes(b"fixture-only-not-a-working-PE")
self.data["platforms"]["windows"] = dict(status="available", backend="bin/ForeverBootstrap.exe",
sha256=hashlib.sha256(backend.read_bytes()).hexdigest())
self.write()
self.assertEqual(self.plan(system="Windows")[0], [str(backend), "--endpoint-profile", "local-explicit"])
def test_profile_cannot_supply_credentials_or_shell(self):
for key in ("password", "account", "command", "shell"):
self.data[key] = "never-used"
self.write()
with self.assertRaisesRegex(ValueError, "Unsupported launcher profile"):
self.plan()
del self.data[key]
def test_backend_cannot_escape_runtime(self):
self.data["platforms"]["linux"]["backend"] = "../elsewhere.py"
self.write()
with self.assertRaisesRegex(ValueError, "inside the runtime"):
self.plan()
def test_folder_selection_resolves_prepared_client_not_original(self):
client = self.root / "runtime/native-client"
game = client / "_classic_beta_"
game.mkdir(parents=True)
(game / "WowB.exe").write_bytes(b"fixture")
for selected in (self.root, client, game):
self.assertEqual(launcher.locate_installation(selected), (self.root, client))
original = self.root / "original-client"
original.mkdir()
(original / "WowB.exe").write_bytes(b"fixture")
with self.assertRaisesRegex(ValueError, "not a prepared"):
launcher.locate_installation(original)
def test_public_status_excludes_rpc_and_unknown_fields(self):
good = dict(schema=1, phase="login", message="Login ready")
self.assertEqual(launcher.public_event(json.dumps(good)), good)
self.assertIsNone(launcher.public_event(json.dumps(dict(good, credentials="private"))))
self.assertIsNone(launcher.public_event("raw private diagnostic"))
self.assertIsNone(launcher.public_event("x" * 4097))
def test_realm_rows_require_real_indices_and_availability(self):
good = dict(schema=1, phase="realms", message="Choose", realms=[dict(index=3, name="Realm", offline=True)])
self.assertEqual(launcher.public_event(json.dumps(good)), good)
good["realms"] *= 2
self.assertIsNone(launcher.public_event(json.dumps(good)))
def test_stage_is_launcher_only_and_never_overwrites(self):
output = self.root / "package"
result = package.stage(output, self.root, sys.executable)
self.assertFalse(result["credentials_included"])
self.assertFalse(result["game_files_included"])
self.assertFalse(result["windows_runtime_available"])
self.assertEqual(set(p.name for p in output.iterdir()),
{"launcher.py", "compat", "manifest.json", "WoW-Hybrid Forever.desktop"})
self.assertTrue((output/"compat/launcher.json").is_file())
self.assertFalse(result["launcher_interface"])
self.assertEqual(result["fixed_endpoint"],"play.octowow.st")
with self.assertRaisesRegex(ValueError, "preserved"):
package.stage(output, self.root, sys.executable)
class BackendContracts(unittest.TestCase):
def test_existing_world_reuses_proof_and_enables_existing_route_once(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / "runtime").mkdir()
pid = os.getpid()
(root / "runtime/native-client.pid").write_text(str(pid))
(root / "runtime/engine-poll-binding.json").write_text(json.dumps(dict(pid=pid, restored=False, wire_ping_only=False)))
calls, events = [], []
reads = iter([dict(error=0, closed=0, world_auth=1, world=dict(login_sent=1, self_create=True)),
dict(error=0, closed=1)])
def rpc(operation):
calls.append(operation)
if operation == "inspect-wire-account":
return dict(selected_index=0,state=2,transport_prepared=1)
return next(reads)
owner = SimpleNamespace(rpc=rpc)
with patch.dict(sys.modules, {
"native_engine_character_test": SimpleNamespace(Controller=lambda actual: owner),
"native_manual_login": SimpleNamespace(run=lambda *x: self.fail("No authentication replay"),
character_selection=None, require_realm=lambda *x: None, binding_for=lambda *x: None,
authenticated_world_ready=lambda *x: True),
"native_world_entry_test": SimpleNamespace(enable_gameplay=lambda controller, **kwargs: calls.append("enable-route"))}), \
patch.object(backend, "ROOT", root), \
patch.object(backend, "retire_for_manual_login", side_effect=RuntimeError("fixture closed without new user intent")), \
patch.object(backend.subprocess, "run") as process, \
patch.object(backend.time, "sleep"), \
patch.object(backend, "emit", side_effect=lambda phase, message, **fields: events.append(phase)):
self.assertEqual(backend.supervise(SimpleNamespace(endpoint_profile="local-explicit", character_guid=4518), io.StringIO()), 2)
self.assertEqual(calls.count("enable-route"), 1)
self.assertEqual(events[:4], ['starting', 'host', 'characters', 'world'])
self.assertEqual(events[-1], 'blocked');self.assertNotIn('login',events)
self.assertEqual(process.call_count, 1)
self.assertNotIn("shell", process.call_args.kwargs)
def test_log_forwards_only_complete_marker_with_actual_armed_report_once(self):
log, events = io.StringIO(), []
marker = "Original Login is armed for octo. Enter your account and password yourself in the existing game form, then press Enter once. No automatic submission or retry.\n"
report = dict(phase="install-verified-native-bindings", authentication_armed=False)
with patch.object(backend, "emit", side_effect=lambda *x: events.append(x)):
stream = backend.StatusLog(log, report)
stream.write("private diagnostic not displayed\n")
stream.write(marker)
self.assertEqual(events, [])
report.update(phase="awaiting-user-login", authentication_armed=True)
stream.write(marker[:-1])
self.assertEqual(events, [])
stream.write("\n")
stream.write(marker)
self.assertEqual(len(events), 1)
self.assertEqual(events[0][0], "login")
self.assertNotIn("private diagnostic", events[0][1])
def test_readiness_marker_alone_cannot_signal_ready(self):
marker = "Original Login is armed for octo. Enter your account and password yourself in the existing game form, then press Enter once. No automatic submission or retry.\n"
with patch.object(backend, "emit") as emit:
backend.StatusLog(io.StringIO()).write(marker)
backend.StatusLog(io.StringIO(), dict(phase="awaiting-user-login", authentication_armed=False)).write(marker)
backend.StatusLog(io.StringIO(), dict(phase="awaiting-user-login", authentication_armed=True)).write("diagnostic prefix " + marker)
emit.assert_not_called()
def test_authentication_observer_reads_only_real_report_phase(self):
report = dict(phase="awaiting-user-login")
stop = Mock()
def wait(interval):
self.assertEqual(interval, .1)
if report["phase"] == "awaiting-user-login":
report["phase"] = "awaiting-genuine-srp-and-realms"
return False
stop.wait.side_effect = wait
with patch.object(backend, "emit") as emit:
backend.observe_authentication(report, stop)
self.assertEqual(emit.call_args.args[0], "authenticating")
self.assertEqual(emit.call_count, 1)
class ReadinessPanelContracts(unittest.TestCase):
def panel(self):
with patch.dict(os.environ, DISPLAY=":fixture"), patch.object(launcher.shutil, "which", side_effect=lambda name: "/usr/bin/"+name):
return launcher.LoginReadinessPanel()
def test_missing_os_ui_fails_before_client_launch(self):
with patch.object(launcher.shutil, "which", return_value=None), patch.object(launcher.subprocess, "Popen") as spawn:
with self.assertRaisesRegex(ValueError, "Visible login readiness requires"):
launcher.supervise(["never-start"], ROOT)
spawn.assert_not_called()
def test_stage_bar_only_finishes_on_login_event(self):
panel = self.panel(); panel.reference = ["org.kde.kdialog-123", "/ProgressDialog"]
with patch.object(panel, "call") as call, patch.object(launcher.subprocess, "Popen") as popup:
for phase in ("starting", "host", "preparing"):
panel.update(dict(phase=phase, message="bounded public status"))
self.assertEqual(panel.value, 2);self.assertFalse(panel.ready);popup.assert_not_called()
values = [args.args[-1] for args in call.call_args_list if args.args[0] == "org.freedesktop.DBus.Properties.Set"]
self.assertEqual(values, [0, 1, 2])
panel.update(dict(phase="login", message="Login ready"))
self.assertTrue(panel.ready);self.assertEqual(panel.value, 3)
self.assertIn("account and password in the Forever game window", popup.call_args.args[0][4])
self.assertFalse(panel.keep_above.is_set())
panel.update(dict(phase="preparing", message="old status"))
self.assertEqual(popup.call_count, 1)
def test_ready_panel_dismisses_after_authentication_or_character_phase(self):
for phase in ("authenticating", "characters", "blocked", "closed"):
panel = self.panel();process = Mock();process.poll.return_value = None;panel.ready_process = process
panel.update(dict(phase=phase, message="bounded"))
process.terminate.assert_called_once();self.assertIsNone(panel.ready_process)
def test_closed_progress_window_does_not_suppress_later_real_readiness(self):
panel = self.panel();panel.reference=["org.kde.kdialog-123","/ProgressDialog"]
with patch.object(panel,"call",side_effect=OSError("dialog closed")), patch.object(launcher.subprocess,"Popen") as popup:
panel.update(dict(phase="preparing",message="Preparing"))
popup.assert_not_called();self.assertIsNone(panel.reference)
panel.update(dict(phase="login",message="Ready"))
popup.assert_called_once();self.assertTrue(panel.ready)
def test_progress_dialog_disables_autoclose_and_copies_no_raw_output(self):
panel = self.panel()
result = SimpleNamespace(stdout="org.kde.kdialog-123 /ProgressDialog\n")
with patch.object(launcher.subprocess, "run", return_value=result) as run, patch.object(launcher.threading, "Thread") as thread:
panel.open()
self.assertEqual(panel.reference, ["org.kde.kdialog-123", "/ProgressDialog"])
commands = [x.args[0] for x in run.call_args_list]
self.assertEqual(commands[0][-1], "3")
self.assertIn([panel.qdbus, *panel.reference, "org.freedesktop.DBus.Properties.Set", panel.interface, "autoClose", "false"], commands)
self.assertIn([panel.qdbus, *panel.reference, "showCancelButton", "false"], commands)
thread.return_value.start.assert_called_once()
def test_invalid_dbus_reference_is_never_executed(self):
panel = self.panel()
with patch.object(launcher.subprocess, "run", return_value=SimpleNamespace(stdout="private diagnostic; shell /foreign")) as run:
with self.assertRaisesRegex(ValueError, "expected OS window reference"):panel.open()
self.assertEqual(run.call_count, 1)
def test_supervisor_forwards_only_valid_status_and_closes_panel(self):
panel = Mock();child = Mock();child.stdout = io.StringIO('private diagnostic\n'+json.dumps(dict(schema=1,phase="preparing",message="Preparing"))+'\n'+json.dumps(dict(schema=1,phase="login",message="Ready"))+'\n');child.wait.return_value=0
context = Mock();context.__enter__=Mock(return_value=child);context.__exit__=Mock(return_value=False)
with patch.object(launcher.subprocess, "Popen", return_value=context):
self.assertEqual(launcher.supervise(["fixture"],ROOT,panel_factory=lambda:panel),(0,"Ready"))
self.assertEqual([c.args[0]["phase"]for c in panel.update.call_args_list],["preparing","login"])
panel.open.assert_called_once();panel.close.assert_called_once()
if __name__ == "__main__":
unittest.main(verbosity=2)