fix: preserve strategy intent and recover accounts automatically

This commit is contained in:
AttilaNet
2026-11-11 19:37:15 +08:00
parent ccb945631d
commit 5c253d5cf9
26 changed files with 1628 additions and 236 deletions
@@ -27,16 +27,14 @@ class AutoReloginSchemaTests(unittest.TestCase):
catalog = Catalog()
fields = next(page["form"] for page in schema(catalog)["pages"] if page["key"] == "login")
fields = {tuple(field["path"]): field for field in fields}
enabled = fields[("auto_relogin", "enabled")]
delay = fields[("auto_relogin", "delay_minutes")]
self.assertEqual(enabled["label"], "掉线后自动重新登录")
self.assertEqual(enabled["type"], "boolean")
self.assertIs(enabled["value"], False)
self.assertNotIn(("auto_relogin", "enabled"), fields)
self.assertIsInstance(default_config()["auto_relogin"]["enabled"], bool)
self.assertEqual((delay["type"], delay["min"], delay["max"], delay["value"]), ("integer", 1, 10080, 30))
engine = SimpleNamespace(catalog=catalog, snapshot=None, demo=False)
view = build_view(engine, "login", default_config())
values = {tuple(field["path"]): field["value"] for field in view["form"]}
self.assertIs(values[("auto_relogin", "enabled")], False)
self.assertNotIn(("auto_relogin", "enabled"), values)
self.assertEqual(values[("auto_relogin", "delay_minutes")], 30)
@@ -77,8 +75,9 @@ class AutoReloginBrowserTests(unittest.TestCase):
self.configs[identifier]["auto_relogin"] = {"enabled": False, "delay_minutes": 30}
summary = copy.deepcopy(self.manager.status(identifier))
summary.update(demo=False, connected=False, running=False, connection_state="offline",
connection_message="尚未连接游戏", error="", revision=9000)
summary["auto_relogin_status"] = {"state": "disabled", "message": "自动重登未开启", "next_attempt_at": None}
connection_message="尚未连接游戏", error="", revision=9000,
strategy_requested=False, strategy_state="stopped", strategy_message="", strategy_retry_at=None)
summary["auto_relogin_status"] = {"state": "missing_identity", "message": "尚未保存登录角色", "next_attempt_at": None}
self.summaries[identifier] = summary
self.login_data[identifier] = build_view(engine, "login", default_config())
self.login_data[identifier].update(account="offline-fixture", has_saved_password=True)
@@ -122,9 +121,10 @@ class AutoReloginBrowserTests(unittest.TestCase):
route.abort()
return
self.summaries[identifier].update(connected=False, running=False, connection_state="offline")
self.set_status(identifier, "cancelled", "手动退出登录,已取消本次自动重登")
self.waiting(identifier, message="退出登录后仍按设定时长自动重登",
requested=self.summaries[identifier]["strategy_requested"])
self.fulfill(route, {"id": "mock-logout", "operation": operation, "status": "succeeded",
"result": {"message": "已退出登录并取消自动重登"}})
"result": {"message": "已退出当前连接,仍会自动重登"}})
return
if request.method in ("POST", "PUT", "DELETE", "PATCH"):
self.unexpected_actions.append(path)
@@ -146,15 +146,21 @@ class AutoReloginBrowserTests(unittest.TestCase):
self.summaries[identifier]["auto_relogin_status"] = {
"state": state, "message": message, "next_attempt_at": next_attempt_at}
def waiting(self, identifier=None, *, seconds=45, message="掉线后等待自动重登"):
def waiting(self, identifier=None, *, seconds=45, message="掉线后等待自动重登", requested=True):
identifier = identifier or self.first
self.configs[identifier]["auto_relogin"]["enabled"] = True
summary = self.summaries[identifier]
summary["strategy_requested"] = requested
if not requested:
summary["strategy_state"] = "stopped"
elif summary["strategy_state"] == "stopped":
summary["strategy_state"] = "offline"
target = (datetime.now(timezone.utc) + timedelta(seconds=seconds)).isoformat().replace("+00:00", "Z")
self.set_status(identifier, "waiting", message, target)
return target
def controls(self, panel):
return panel.get_by_role("checkbox", name="掉线后自动重新登录", exact=True), panel.get_by_role("spinbutton", name="重登等待时长(分钟)", exact=True)
def delay_control(self, panel):
expect(panel.get_by_role("checkbox", name="掉线后自动重新登录", exact=True)).to_have_count(0)
return panel.get_by_role("spinbutton", name="重登等待时长(分钟)", exact=True)
def saved(self, identifier, enabled, minutes):
self.page.wait_for_function("() => document.querySelector('#save-status').textContent === '策略已自动保存'")
@@ -162,27 +168,27 @@ class AutoReloginBrowserTests(unittest.TestCase):
def complete_login(self, operation, *, running=True):
self.summaries[self.first].update(connected=True, connection_state="online",
connection_message="游戏连接正常", error="", running=running)
connection_message="游戏连接正常", error="", running=running,
strategy_requested=running, strategy_state="running" if running else "stopped")
return {"id": "mock-" + operation, "operation": operation, "status": "succeeded", "result": {}}
def test_defaults_visible_explanations_and_existing_layout(self):
self.open()
panel = self.go("login")
enabled, delay = self.controls(panel)
expect(enabled).to_be_visible()
expect(enabled).not_to_be_checked()
delay = self.delay_control(panel)
expect(delay).to_be_visible()
expect(delay).to_have_value("30")
for attribute, value in (("min", "1"), ("max", "10080"), ("step", "1")):
expect(delay).to_have_attribute(attribute, value)
for text in ("服务端", "记住账号和密码", "原区服", "角色", "恢复监控", "自动执行已勾选功能", "顶部“停止”", "关闭页面", "服务重启"):
for text in ("服务端", "记住账号和密码", "原区服", "角色", "恢复监控", "自动执行已勾选功能", "顶部“停止”", "关闭页面", "服务重启", "退出登录", "只有", "清除登录记录", "暂停"):
expect(panel).to_contain_text(text)
self.assertTrue(enabled.evaluate("node => Boolean(node.closest('.policy-form'))"))
self.assertTrue(enabled.evaluate("node => Boolean(node.compareDocumentPosition(document.querySelector('.login-layout')) & Node.DOCUMENT_POSITION_FOLLOWING)"))
self.assertTrue(delay.evaluate("node => Boolean(node.closest('.policy-form'))"))
self.assertTrue(delay.evaluate("node => Boolean(node.compareDocumentPosition(document.querySelector('.login-layout')) & Node.DOCUMENT_POSITION_FOLLOWING)"))
expect(panel.get_by_role("button", name="保存", exact=True)).to_have_count(0)
for width, height in ((1280, 800), (390, 844)):
self.page.set_viewport_size({"width": width, "height": height})
self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), width)
expect(enabled).to_be_visible()
expect(delay).to_be_visible()
self.assertEqual(self.writes, [])
self.assertEqual(self.actions, [])
@@ -196,7 +202,7 @@ class AutoReloginBrowserTests(unittest.TestCase):
return {"id": "mock-login", "operation": "login", "status": "succeeded", "result": candidates}
def stop(payload):
self.summaries[self.first]["running"] = False
self.summaries[self.first].update(running=False, strategy_requested=False, strategy_state="stopped")
return {"id": "mock-stop", "operation": "stop", "status": "succeeded", "result": {"message": "策略已停止"}}
self.action_handlers.update({(self.first, "login"): login,
@@ -230,13 +236,13 @@ class AutoReloginBrowserTests(unittest.TestCase):
self.assertEqual(self.configs[self.first], original)
self.assertEqual(self.writes, [])
def test_import_stays_stopped_and_next_restored_session_runs_imported_selection(self):
def test_import_and_restored_session_preserve_explicit_pause_and_imported_selection(self):
imported = copy.deepcopy(default_config())
imported["daily_policy"].update(enabled=True, selected=["gift"])
portable = export_config(imported)
imports = []
self.login_data[self.first]["saved_sessions"] = [{"id": "offline-session", "label": "离线区服 / 原角色"}]
self.action_handlers[(self.first, "restore_session")] = lambda payload: self.complete_login("restore_session")
self.action_handlers[(self.first, "restore_session")] = lambda payload: self.complete_login("restore_session", running=False)
def import_config(route):
imports.append(route.request.post_data_json)
@@ -253,15 +259,15 @@ class AutoReloginBrowserTests(unittest.TestCase):
self.page.locator('[data-command="import-config"]').click()
chooser.value.set_files({"name": "offline-policy.json", "mimeType": "application/json",
"buffer": json.dumps(portable).encode("utf-8")})
expect(self.page.locator("#dialog-content")).to_contain_text("下次成功登录会自动执行已勾选功能")
expect(self.page.locator("#dialog-content")).to_contain_text("仍遵循当前开启 / 停止设置")
self.page.locator("#dialog-confirm").click()
expect(self.page.locator("#notice")).to_contain_text("策略已导入,执行已停止")
expect(self.page.locator("#notice")).to_contain_text("策略已导入")
expect(self.page.locator("#strategy-toggle")).to_be_disabled()
self.assertEqual(imports, [portable])
self.assertEqual(self.actions, [])
panel.get_by_role("button", name="恢复选中会话(无需重新输密码)", exact=True).click()
expect(self.page.locator("#strategy-toggle")).to_have_text("停止")
expect(self.page.locator("#notice")).to_contain_text("已自动开启策略")
expect(self.page.locator("#strategy-toggle")).to_have_text("开启")
expect(self.page.locator("#notice")).to_contain_text("用户暂停")
self.assertEqual(self.actions, [(self.first, "restore_session", {"session_id": "offline-session"})])
self.assertEqual(self.configs[self.first], imported, "Restoring must preserve imported selections")
self.assertEqual(self.writes, [])
@@ -314,17 +320,12 @@ class AutoReloginBrowserTests(unittest.TestCase):
def test_native_autosave_range_validation_refresh_and_focus(self):
self.open()
panel = self.go("login")
enabled, delay = self.controls(panel)
enabled.check()
checkbox = enabled.element_handle()
self.page.wait_for_timeout(850)
self.saved(self.first, True, 30)
self.assertTrue(enabled.evaluate("(node, original) => node === original && node === document.activeElement", checkbox))
delay = self.delay_control(panel)
delay.fill("47")
original = delay.element_handle()
before = self.view_calls
self.page.wait_for_timeout(5200)
self.saved(self.first, True, 47)
self.saved(self.first, False, 47)
self.assertGreater(self.view_calls, before, "Offline login DTOs must keep refreshing")
self.assertTrue(delay.evaluate("(node, original) => node === original && node === document.activeElement", original))
for invalid in ("0", "10081", "1.5", ""):
@@ -336,9 +337,7 @@ class AutoReloginBrowserTests(unittest.TestCase):
for valid in (1, 10080):
delay.fill(str(valid))
self.page.wait_for_timeout(850)
self.saved(self.first, True, valid)
enabled.uncheck()
self.page.wait_for_timeout(850)
self.saved(self.first, False, valid)
self.saved(self.first, False, 10080)
self.assertEqual(self.actions, [])
@@ -350,14 +349,13 @@ class AutoReloginBrowserTests(unittest.TestCase):
remember = panel.get_by_role("checkbox", name="记住账号和密码", exact=True)
remember.uncheck()
panel.get_by_role("textbox", name="游戏密码", exact=True).fill("mock-secret-never-send")
enabled, _ = self.controls(panel)
enabled.check()
self.delay_control(panel).fill("10")
hint = panel.locator("[data-auto-relogin-credentials]")
expect(hint).to_be_visible()
expect(hint).to_contain_text("缺少")
expect(hint).to_contain_text("记住账号和密码")
self.page.wait_for_timeout(1000)
self.saved(self.first, True, 30)
self.saved(self.first, False, 10)
expect(remember).not_to_be_checked()
self.assertTrue(self.writes)
payloads = json.dumps(self.writes, ensure_ascii=False)
@@ -370,26 +368,24 @@ class AutoReloginBrowserTests(unittest.TestCase):
def test_account_switch_isolates_pending_edits_status_and_minutes(self):
self.waiting(message="账号一正在等待自动重登")
self.set_status(self.second, "disabled", "账号二未开启自动重登")
self.set_status(self.second, "missing_identity", "账号二尚未保存登录角色")
self.open()
panel = self.go("login")
_, delay = self.controls(panel)
delay = self.delay_control(panel)
delay.fill("17")
self.page.locator(f'.account-tab[data-account="{self.second}"]').click()
panel = self.go("login")
enabled, second_delay = self.controls(panel)
expect(enabled).not_to_be_checked()
second_delay = self.delay_control(panel)
expect(second_delay).to_have_value("30")
expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("账号二未开启")
expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("账号二尚未保存")
expect(panel).not_to_contain_text("账号一正在等待")
enabled.check()
second_delay.fill("9")
self.page.wait_for_timeout(1000)
self.saved(self.second, True, 9)
self.assertEqual(self.configs[self.first]["auto_relogin"], {"enabled": True, "delay_minutes": 17})
self.saved(self.second, False, 9)
self.assertEqual(self.configs[self.first]["auto_relogin"], {"enabled": False, "delay_minutes": 17})
self.page.locator(f'.account-tab[data-account="{self.first}"]').click()
panel = self.go("login")
expect(self.controls(panel)[1]).to_have_value("17")
expect(self.delay_control(panel)).to_have_value("17")
expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("账号一正在等待")
self.assertEqual({identifier for identifier, _ in self.writes}, {self.first, self.second})
self.assertEqual(self.actions, [])
@@ -404,8 +400,8 @@ class AutoReloginBrowserTests(unittest.TestCase):
expect(status).to_contain_text("掉线后等待自动重登")
expect(countdown).to_contain_text("秒后自动重新登录")
expect(countdown).to_contain_text("北京时间")
expect(self.controls(panel)[0]).to_be_enabled()
delay = self.controls(panel)[1]
delay = self.delay_control(panel)
expect(delay).to_be_enabled()
delay.focus()
original = delay.element_handle()
before = countdown.inner_text()
@@ -421,10 +417,12 @@ class AutoReloginBrowserTests(unittest.TestCase):
self.set_status(self.first, "failed", reason)
expect(status).to_contain_text(reason)
expect(status.locator("img")).to_have_count(0)
expect(self.page.locator("#strategy-toggle")).to_be_disabled()
expect(self.page.locator("#strategy-toggle")).to_have_text("停止")
expect(self.page.locator("#strategy-toggle")).to_be_enabled()
original = copy.deepcopy(self.configs[self.first])
self.set_status(self.first, "monitoring", "重登成功,已恢复监控并自动执行已勾选功能,可在顶部停止")
self.summaries[self.first].update(connected=True, connection_state="online", connection_message="游戏连接正常", running=True)
self.summaries[self.first].update(connected=True, connection_state="online", connection_message="游戏连接正常",
running=True, strategy_requested=True, strategy_state="running")
expect(status).to_contain_text("已恢复监控并自动执行已勾选功能")
expect(self.page.locator("#strategy-toggle")).to_have_text("停止")
expect(self.page.locator("#data-summary")).to_contain_text("正在自动执行已配置且已勾选的功能")
@@ -436,31 +434,35 @@ class AutoReloginBrowserTests(unittest.TestCase):
self.open()
panel = self.go("login")
expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("服务重启")
expect(self.page.locator("#strategy-toggle")).to_be_disabled()
expect(self.page.locator("#strategy-toggle")).to_have_text("停止")
expect(self.page.locator("#strategy-toggle")).to_be_enabled()
before = len(self.writes)
self.page.reload(wait_until="networkidle")
panel = self.go("login")
expect(self.controls(panel)[0]).to_be_checked()
expect(self.controls(panel)[1]).to_have_value("30")
expect(self.delay_control(panel)).to_have_value("30")
expect(panel.locator("[data-auto-relogin-countdown]")).to_contain_text("秒后自动重新登录")
expect(self.page.locator("#strategy-toggle")).to_have_text("开启")
expect(self.page.locator("#strategy-toggle")).to_be_disabled()
expect(self.page.locator("#strategy-toggle")).to_have_text("停止")
expect(self.page.locator("#strategy-toggle")).to_be_enabled()
self.page.goto("about:blank")
self.page.close()
self.assertEqual(len(self.writes), before)
self.assertEqual(self.summaries[self.first]["auto_relogin_status"]["next_attempt_at"], target)
self.assertEqual(self.actions, [])
def test_manual_logout_cancels_countdown_without_disabling_account_setting(self):
def test_manual_logout_keeps_countdown_and_preserves_strategy_pause(self):
self.waiting()
self.summaries[self.first].update(strategy_requested=False, strategy_state="stopped")
self.open()
panel = self.go("login")
expect(panel.locator("[data-auto-relogin-countdown]")).to_contain_text("秒后自动重新登录")
panel.get_by_role("button", name="退出登录", exact=True).click()
expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("已取消本次自动重登")
expect(panel.locator("[data-auto-relogin-countdown]")).to_be_hidden()
expect(self.controls(panel)[0]).to_be_checked()
expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("仍按设定时长自动重登")
expect(panel.locator("[data-auto-relogin-countdown]")).to_be_visible()
expect(self.page.locator("#strategy-toggle")).to_have_text("开启")
expect(self.page.locator("#data-summary")).to_contain_text("用户暂停")
expect(self.delay_control(panel)).to_have_value("30")
self.assertEqual(self.actions, [(self.first, "logout", {})])
self.assertEqual(self.writes, [])
if __name__ == "__main__":
@@ -72,7 +72,8 @@ class ConnectionBrowserTests(unittest.TestCase):
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="登录凭据已失效,请重新登录。")
failure_reason = "登录凭据已失效,请重新登录。"
self.summary.update(connection_state="expired", connection_message=failure_reason, error=failure_reason)
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("缓存")
@@ -89,10 +90,14 @@ class ConnectionBrowserTests(unittest.TestCase):
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("#connection")).to_have_attribute("title", "游戏连接正常")
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("[data-connection-status]")).to_have_text("")
for selector in ("#data-summary", "#status-text"):
expect(self.page.locator(selector)).to_be_visible()
expect(self.page.locator(selector)).to_contain_text(f"上次失败:{failure_reason}")
expect(self.page.locator(f'.account-tab[data-account="{self.first}"] .account-dot')).not_to_have_class("account-dot error")
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, [])
@@ -0,0 +1,214 @@
"""Durable execution intent with synthetic API responses and loopback HTTP only."""
from __future__ import annotations
import unittest
from . import test_auto_relogin_browser as relogin
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 RunIntentBrowserTests(unittest.TestCase):
setUpClass = classmethod(relogin.AutoReloginBrowserTests.setUpClass.__func__)
tearDownClass = classmethod(relogin.AutoReloginBrowserTests.tearDownClass.__func__)
tearDown = relogin.AutoReloginBrowserTests.tearDown
await_job = fixtures.WorkbenchBrowserTests.await_job
open = fixtures.WorkbenchBrowserTests.open
go = fixtures.WorkbenchBrowserTests.go
fulfill = staticmethod(fixtures.WorkbenchBrowserTests.fulfill)
set_status = relogin.AutoReloginBrowserTests.set_status
waiting = relogin.AutoReloginBrowserTests.waiting
def setUp(self):
relogin.AutoReloginBrowserTests.setUp(self)
for summary in self.summaries.values():
summary.update(strategy_requested=False, strategy_state="stopped",
strategy_message="", strategy_retry_at=None)
self.summary = self.summaries[self.first]
self.online()
self.page.add_init_script("""(() => {
const original = window.setInterval;
window.setInterval = (callback, delay, ...args) => {
if (callback.name === 'tick') {window.__pollIntent = callback;return -1;}
return original(callback, delay, ...args);
};
})();""")
def poll(self):
self.page.evaluate("async () => {await window.__pollIntent();}")
self.page.wait_for_load_state("networkidle")
def online(self, *, running=True):
self.summary.update(connected=True, connection_state="online", connection_message="游戏连接正常",
error="", running=running, strategy_requested=True,
strategy_state="running" if running else "recovering", strategy_message="",
strategy_retry_at=None, next_retry_at=None)
def recovering(self):
self.summary.update(running=False, strategy_requested=True, connection_state="retrying",
connection_message="游戏请求超时,正在恢复连接。", error="游戏请求超时",
strategy_state="recovering", strategy_message="网络超时,等待只读检查后恢复策略。")
self.summary["strategy_retry_at"] = self.page.evaluate("new Date(Date.now()+30000).toISOString()")
self.summary["next_retry_at"] = self.summary["strategy_retry_at"]
self.waiting(seconds=600)
def test_timeout_heartbeat_only_and_recovery_preserve_stop_and_failure_history(self):
self.open()
toggle = self.page.locator("#strategy-toggle")
expect(toggle).to_have_text("停止")
expect(self.page.locator("#log-panel")).to_be_hidden()
self.recovering()
self.poll()
expect(toggle).to_have_text("停止")
expect(toggle).to_be_enabled()
expect(toggle).to_have_class("run-button running")
expect(toggle).to_have_attribute("aria-pressed", "true")
expect(self.page.locator("#data-summary")).to_contain_text("等待")
expect(self.page.locator("#data-summary")).not_to_contain_text("用户暂停")
expect(self.page.locator("#connection")).to_have_text("正在重试")
expect(self.page.locator("#refresh")).to_be_disabled()
self.online(running=False)
self.poll()
expect(self.page.locator("#connection")).to_have_text("已登录")
expect(self.page.locator("#refresh")).to_be_enabled()
expect(self.page.locator("#data-summary")).to_contain_text("等待恢复")
expect(self.page.locator("#data-summary")).to_contain_text("上次失败")
expect(self.page.locator("#data-summary")).to_contain_text("游戏请求超时")
expect(toggle).to_have_text("停止")
expect(self.page.locator(f'.account-tab[data-account="{self.first}"] .account-dot')).not_to_have_class("account-dot error")
self.online()
self.poll()
expect(self.page.locator("#data-summary")).to_contain_text("正在自动执行")
expect(self.page.locator("#data-summary")).to_contain_text("上次失败")
expect(self.page.locator("#connection")).to_have_text("已登录")
expect(self.page.locator("#log-panel")).to_be_hidden()
self.assertEqual(self.actions, [])
self.assertEqual(self.writes, [])
def test_stop_during_recovery_persists_pause_while_relogin_continues(self):
self.open()
self.recovering()
self.poll()
def stop(payload):
self.summary.update(strategy_requested=False, running=False, strategy_state="stopped",
strategy_message="用户已停止策略,仍会保持登录。")
return {"id": "intent-stop", "operation": "stop", "status": "succeeded", "result": {}}
def start(payload):
self.online()
return {"id": "intent-start", "operation": "start", "status": "succeeded", "result": {}}
self.action_handlers[(self.first, "stop")] = stop
self.action_handlers[(self.first, "start")] = start
toggle = self.page.locator("#strategy-toggle")
toggle.click()
expect(toggle).to_have_text("开启")
expect(toggle).to_have_attribute("aria-pressed", "false")
expect(toggle).to_be_disabled()
expect(self.page.locator("#data-summary")).to_contain_text("用户暂停")
expect(self.page.locator('[data-auto-relogin-countdown]')).to_be_visible()
self.summary.update(connected=True, connection_state="online", connection_message="游戏连接正常", error="",
next_retry_at=None, strategy_retry_at=None)
self.poll()
expect(self.page.locator("#connection")).to_have_text("已登录")
expect(toggle).to_be_enabled()
expect(self.page.locator("#data-summary")).to_contain_text("用户暂停")
self.page.reload(wait_until="networkidle")
expect(toggle).to_have_text("开启")
expect(self.page.locator("#data-summary")).to_contain_text("用户暂停")
toggle.click()
expect(toggle).to_have_text("停止")
expect(self.page.locator("#data-summary")).to_contain_text("正在自动执行")
self.assertEqual([(account, operation) for account, operation, _ in self.actions],
[(self.first, "stop"), (self.first, "start")])
self.assertEqual(self.writes, [])
def test_online_execution_block_is_distinct_from_connection_health_and_can_be_stopped(self):
self.online(running=False)
reason = '交付结果待确认 <img src=x onerror="alert(1)">'
self.summary.update(strategy_state="blocked", strategy_message=reason)
self.open()
expect(self.page.locator("#connection")).to_have_text("已登录")
expect(self.page.locator("#refresh")).to_be_enabled()
expect(self.page.locator("#strategy-toggle")).to_have_text("停止")
expect(self.page.locator("#strategy-toggle")).to_be_enabled()
expect(self.page.locator("#data-summary")).to_contain_text(reason)
expect(self.page.locator("#data-summary img")).to_have_count(0)
expect(self.page.locator("#data-summary")).not_to_contain_text("正在自动执行")
expect(self.page.locator("#data-summary")).not_to_contain_text("用户暂停")
self.assertEqual(self.actions, [])
def test_legacy_status_falls_back_to_running_and_keeps_heartbeat_only_online(self):
for field in ("strategy_requested", "strategy_state", "strategy_message", "strategy_retry_at"):
self.summary.pop(field)
self.open()
toggle = self.page.locator("#strategy-toggle")
expect(toggle).to_have_text("停止")
self.summary["running"] = False
self.poll()
expect(toggle).to_have_text("开启")
expect(toggle).to_be_enabled()
expect(self.page.locator("#connection")).to_have_text("已登录")
expect(self.page.locator("#refresh")).to_be_enabled()
expect(self.page.locator("#data-summary")).not_to_contain_text("用户暂停")
self.assertEqual(self.actions, [])
def test_applying_preset_saves_rules_without_sending_stop_or_changing_intent(self):
view = {"loading": False, "data": {"page": "hatching", "form": [], "filters": [],
"columns": [], "rows": [], "actions": [], "details": {"preset": {
"label": "离线测试预设", "patch": {"policy": {"enabled": True, "collect": True}},
"egg_rules": {"1001010": {"enabled": True}}}}}}
self.page.route(f"**/api/accounts/{self.first}/views/hatching?*", lambda route: self.fulfill(route, view))
self.open()
panel = self.go("hatching")
panel.locator('button[data-operation="apply_preset"]').click()
expect(self.page.locator("#notice")).to_contain_text("预设已保存")
expect(self.page.locator("#notice")).to_contain_text("正在自动执行")
expect(self.page.locator("#strategy-toggle")).to_have_text("停止")
self.assertEqual(len(self.writes), 1)
self.assertTrue(self.configs[self.first]["policy"]["egg_rules"]["1001010"]["enabled"])
self.assertTrue(self.summary["strategy_requested"])
self.assertEqual(self.actions, [], "Applying a preset must not submit a durable user Stop")
def test_restart_wait_and_accounts_keep_intent_and_original_log_region_separate(self):
self.summary.update(connected=False, running=False, connection_state="offline", strategy_requested=True,
strategy_state="offline", strategy_message="等待重新登录后执行已勾选功能。")
self.configs[self.first]["auto_relogin"] = {"enabled": False, "delay_minutes": 10}
self.waiting(seconds=600, message="服务重启,等待返回原区服角色")
self.open()
toggle = self.page.locator("#strategy-toggle")
expect(toggle).to_have_text("停止")
expect(toggle).to_be_enabled()
expect(self.page.locator('[aria-label="重登等待时长(分钟)"]')).to_have_value("10")
expect(self.page.locator('[data-auto-relogin-countdown]')).to_be_visible()
expect(self.page.locator("#log-panel")).to_be_hidden()
self.page.locator("#log-toggle").click()
expect(self.page.locator("#log-panel")).to_be_visible()
self.page.locator("#log-search").fill("登录筛选")
original = self.page.locator("#log-panel").element_handle()
self.go("bag")
expect(self.page.locator("#log-panel")).to_be_visible()
expect(self.page.locator("#log-search")).to_have_value("")
self.page.locator(f'.account-tab[data-account="{self.second}"]').click()
expect(toggle).to_have_text("开启")
expect(self.page.locator("#log-panel")).to_be_hidden()
self.page.locator(f'.account-tab[data-account="{self.first}"]').click()
expect(toggle).to_have_text("停止")
self.go("login")
expect(self.page.locator("#log-panel")).to_be_visible()
expect(self.page.locator("#log-search")).to_have_value("登录筛选")
self.assertTrue(self.page.locator("#log-panel").evaluate("(node, original) => node === original", original))
expect(self.page.locator('[role="log"]')).to_have_count(1)
self.page.reload(wait_until="networkidle")
expect(toggle).to_have_text("停止")
expect(self.page.locator("#log-panel")).to_be_hidden()
self.assertEqual(self.actions, [])
self.assertEqual(self.writes, [])
if __name__ == "__main__":
unittest.main()