"""Offline browser regressions for game and Web connection feedback. All accounts are disposable demos. Game status/action responses are synthetic; Python HTTP and browser requests outside this test's loopback server are blocked. """ from __future__ import annotations import copy import unittest from unittest.mock import patch from . import test_workbench_browser as fixtures if fixtures.AVAILABLE: from playwright.sync_api import expect @unittest.skipUnless(fixtures.AVAILABLE, "Python Playwright and a system Chromium browser are required") class ConnectionBrowserTests(unittest.TestCase): setUpClass = classmethod(fixtures.WorkbenchBrowserTests.setUpClass.__func__) tearDownClass = classmethod(fixtures.WorkbenchBrowserTests.tearDownClass.__func__) tearDown = fixtures.WorkbenchBrowserTests.tearDown await_job = fixtures.WorkbenchBrowserTests.await_job open = fixtures.WorkbenchBrowserTests.open go = fixtures.WorkbenchBrowserTests.go fulfill = staticmethod(fixtures.WorkbenchBrowserTests.fulfill) def setUp(self): guard = patch("requests.sessions.Session.request", side_effect=AssertionError("Live HTTP is forbidden")) guard.start() self.addCleanup(guard.stop) fixtures.WorkbenchBrowserTests.setUp(self) self.external_requests = [] def local_only(route): if route.request.url.startswith(self.base + "/"): route.continue_() else: self.external_requests.append(route.request.url) route.abort() self.context.route("**/*", local_only) self.summary = copy.deepcopy(self.manager.status(self.first)) self.summary.update(demo=False, connected=True, running=False, error="", connection_state="online", connection_message="游戏连接正常", last_game_success_at="2026-11-11T00:00:00Z", next_retry_at=None) self.calls = {"accounts": 0, "logs": 0, "views": 0} self.fail_accounts = False self.fail_logs = False def accounts(route): self.calls["accounts"] += 1 if self.fail_accounts: route.abort("connectionrefused") else: self.fulfill(route, [self.summary, self.manager.status(self.second)]) def logs(route): self.calls["logs"] += 1 if self.fail_logs: route.abort("connectionrefused") else: self.fulfill(route, {"entries": [], "next": 0}) self.page.route("**/api/accounts", accounts) self.page.route(f"**/api/accounts/{self.first}/status", lambda route: self.fulfill(route, self.summary)) self.page.route(f"**/api/accounts/{self.first}/logs?*", logs) self.page.on("request", lambda request: self.calls.__setitem__("views", self.calls["views"] + 1) if f"/api/accounts/{self.first}/views/" in request.url else None) def test_expired_cached_snapshot_stops_view_polling_and_recovers(self): self.open() panel = self.go("ranch") expect(panel.locator("tbody tr").first).to_be_visible() row_count = panel.locator("tbody tr").count() self.summary.update(connection_state="expired", connection_message="登录凭据已失效,请重新登录。") expect(self.page.locator("#connection")).to_have_text("登录已过期") expect(self.page.locator("#data-summary")).to_contain_text(self.summary["connection_message"]) expect(panel.locator(".page-loading")).to_contain_text("缓存") expect(panel.locator("[data-connection-status]")).to_contain_text("2026/11/11") expect(self.page.locator("#strategy-toggle")).to_be_disabled() expect(self.page.locator("#refresh")).to_be_disabled() expect(self.page.locator('[data-command="start"]')).to_be_disabled() count = dict(self.calls) self.page.wait_for_timeout(5200) self.assertEqual(self.calls["views"], count["views"]) self.assertGreater(self.calls["accounts"], count["accounts"]) self.assertGreater(self.calls["logs"], count["logs"]) self.assertEqual(panel.locator("tbody tr").count(), row_count) self.assertTrue(panel.locator("input[data-config-path]").first.is_enabled()) self.summary.update(connection_state="online", connection_message="游戏连接正常", error="", last_game_success_at="2026-11-11T00:01:00Z") expect(self.page.locator("#connection")).to_have_text("已登录") expect(self.page.locator("#strategy-toggle")).to_be_enabled() expect(panel.locator("[data-connection-status]")).to_be_hidden() expect(self.page.locator("#data-summary")).not_to_contain_text("凭据已失效") expect(self.page.locator("#status-text")).not_to_contain_text("凭据已失效") expect(panel.locator(".page-loading")).not_to_contain_text("缓存") self.assertEqual(self.page.locator("#page-tabs [role=tab]").count(), 15) self.assertEqual(self.external_requests, []) self.assertEqual(self.errors, []) def test_retry_countdown_offline_reason_and_login_metadata(self): self.open() self.summary.update(connection_state="retrying", connection_message="游戏请求暂时失败(网络连接中断),即将重试。") self.summary["next_retry_at"] = self.page.evaluate("new Date(Date.now()+30000).toISOString()") expect(self.page.locator("#connection")).to_have_text("正在重试") panel = self.go("bag") expect(panel.locator("[data-connection-status]")).to_contain_text(self.summary["connection_message"]) expect(self.page.locator("#data-summary")).to_contain_text("秒后重试") first = self.page.locator("#data-summary").inner_text() self.page.wait_for_timeout(2100) self.assertNotEqual(first, self.page.locator("#data-summary").inner_text()) self.summary.update(connection_state="offline", connection_message="尚未连接游戏,请在登录页恢复会话。", next_retry_at=None) expect(self.page.locator("#connection")).to_have_text("游戏离线") expect(self.page.locator("#data-summary")).to_contain_text("尚未连接游戏") expect(self.page.locator("#data-summary")).not_to_contain_text("过期") expect(self.page.locator("#data-summary")).not_to_contain_text("秒后重试") login_calls = [] self.page.on("request", lambda request: login_calls.append(request.url) if "/views/login?" in request.url else None) login = self.go("login") expect(login.get_by_role("button", name="恢复选中会话(无需重新输密码)")).to_be_visible() before = len(login_calls) self.page.wait_for_timeout(5200) self.assertGreater(len(login_calls), before, "Disconnected login metadata must continue refreshing") self.assertEqual(self.external_requests, []) self.assertEqual(self.errors, []) def test_web_status_and_log_failures_clear_only_the_recovered_channel(self): self.open() self.go("ranch") self.fail_accounts = True expect(self.page.locator("#data-summary")).to_contain_text("Web 状态读取失败") expect(self.page.locator("#strategy-toggle")).to_be_disabled() expect(self.page.locator("#connection")).not_to_have_text("已登录") count = dict(self.calls) self.page.wait_for_timeout(5100) self.assertGreater(self.calls["accounts"], count["accounts"]) self.assertGreater(self.calls["logs"], count["logs"]) self.assertEqual(self.calls["views"], count["views"]) self.fail_logs = True expect(self.page.locator("#data-summary")).to_contain_text("日志读取失败") self.fail_accounts = False expect(self.page.locator("#data-summary")).not_to_contain_text("Web 状态读取失败") expect(self.page.locator("#data-summary")).to_contain_text("日志读取失败") self.fail_logs = False expect(self.page.locator("#data-summary")).not_to_contain_text("日志读取失败") expect(self.page.locator("#status-text")).not_to_contain_text("读取失败") expect(self.page.locator("#strategy-toggle")).to_be_enabled() self.assertEqual(self.external_requests, []) def test_successful_refresh_job_with_disconnected_summary_never_reports_success(self): self.open() def refresh(route): self.summary.update(connection_state="retrying", connection_message="游戏请求超时,稍后重试。", next_retry_at=None) self.fulfill(route, {"id": "fixture-refresh", "status": "succeeded", "operation": "refresh", "result": {"message": "刷新成功"}}) self.page.route(f"**/api/accounts/{self.first}/actions/refresh", refresh) self.page.locator("#refresh").click() expect(self.page.locator("#connection")).to_have_text("正在重试") expect(self.page.locator("#status-text")).to_contain_text("游戏请求超时") expect(self.page.locator("#status-text")).not_to_contain_text("刷新成功") expect(self.page.locator("#status-text")).not_to_contain_text("刷新 / 预览已完成") expect(self.page.locator("#notice")).not_to_have_text("刷新成功") self.assertEqual(self.external_requests, []) def test_closing_page_never_stops_or_logs_out_account(self): self.summary["running"] = True self.open() writes = [] self.page.on("request", lambda request: writes.append(request.url) if request.method in ("POST", "PUT", "DELETE") else None) self.page.goto("about:blank") self.page.close() self.assertEqual(writes, []) self.assertEqual(self.external_requests, []) def test_disconnected_loading_response_is_cached_and_config_remains_editable(self): self.open() self.summary.update(connection_state="offline", connection_message="Web 服务已重启,请手动恢复会话。", last_game_success_at=None) expect(self.page.locator("#connection")).to_have_text("游戏离线") response = {"loading": True, "data": {"page": "bag", "summary": "已保存的背包", "filters": [], "columns": [], "rows": [], "form": [{"path": ["policy", "collect"], "label": "收取魔物", "type": "checkbox"}], "actions": []}} view_calls, actions = [], [] self.page.route(f"**/api/accounts/{self.first}/views/bag?*", lambda route: (view_calls.append(route.request.url), self.fulfill(route, response))) self.page.on("request", lambda request: actions.append(request.url) if "/actions/" in request.url else None) panel = self.go("bag") expect(panel.locator("[data-connection-status]")).to_contain_text("Web 服务已重启") expect(panel.locator(".page-loading")).to_contain_text("缓存") self.page.locator('[data-command="start"]').dispatch_event("click") self.page.locator("#refresh").dispatch_event("click") self.page.wait_for_timeout(1800) self.assertEqual(len(view_calls), 1, "Disconnected loading=true must not create a 650ms reload chain") self.assertEqual(actions, [], "Disconnected starts and refreshes must be guarded beyond button disabled state") control = panel.locator("input[data-config-path]").first expect(control).to_be_enabled() control.set_checked(not control.is_checked()) expect(self.page.locator("#save-status")).to_have_text("策略已自动保存") self.page.wait_for_timeout(800) self.assertEqual(self.manager.get_config(self.first)["config"]["policy"]["collect"], control.is_checked()) self.assertEqual(actions, []) self.assertEqual(self.external_requests, []) self.assertEqual(self.errors, []) def test_job_transport_failure_retries_and_clears_on_job_recovery(self): self.open() fail_job = True job_calls = [] self.page.route(f"**/api/accounts/{self.first}/actions/refresh", lambda route: self.fulfill(route, {"id": "fixture-job", "status": "queued", "operation": "refresh"})) def job(route): job_calls.append(route.request.url) if fail_job: route.abort("connectionrefused") else: self.fulfill(route, {"id": "fixture-job", "status": "succeeded", "operation": "refresh", "result": {}}) self.page.route(f"**/api/accounts/{self.first}/jobs/fixture-job", job) self.page.locator("#refresh").click() expect(self.page.locator("#data-summary")).to_contain_text("任务状态读取失败") self.page.wait_for_timeout(1200) self.assertGreater(len(job_calls), 1) expect(self.page.locator("#data-summary")).to_contain_text("任务状态读取失败") fail_job = False expect(self.page.locator("#data-summary")).not_to_contain_text("任务状态读取失败") expect(self.page.locator("#status-text")).not_to_contain_text("任务状态读取失败") self.assertEqual(self.external_requests, []) def test_view_failure_survives_successful_logs_and_clears_on_view_recovery(self): self.open() fail_view = True response = {"loading": False, "data": {"page": "bag", "summary": "已恢复页面数据", "form": [], "filters": [], "actions": [], "columns": [], "rows": []}} def view(route): if fail_view: route.abort("connectionrefused") else: self.fulfill(route, response) self.page.route(f"**/api/accounts/{self.first}/views/bag?*", view) self.page.locator('.page-tab[data-page="bag"]').click() panel = self.page.locator('.page-panel[data-page="bag"]:not([hidden])') expect(panel.locator(".page-error")).to_be_visible() expect(self.page.locator("#data-summary")).to_contain_text("页面数据读取失败") self.page.wait_for_timeout(1200) expect(self.page.locator("#data-summary")).to_contain_text("页面数据读取失败") fail_view = False panel.get_by_role("button", name="重新读取").click() expect(panel.locator(".page-error")).to_be_hidden() expect(self.page.locator("#data-summary")).not_to_contain_text("页面数据读取失败") expect(self.page.locator("#status-text")).not_to_contain_text("页面数据读取失败") self.assertEqual(self.external_requests, []) if __name__ == "__main__": unittest.main()