Files
myrzx_bot/ranch_web/tests/browser/test_run_intent_browser.py
T

215 lines
12 KiB
Python

"""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()