ui: simplify helper copy and center page loading feedback

This commit is contained in:
AttilaNet
2026-11-11 21:08:48 +08:00
parent d1e7f3c717
commit e23e7586c4
25 changed files with 747 additions and 141 deletions
@@ -172,7 +172,7 @@ class AutoReloginBrowserTests(unittest.TestCase):
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):
def test_defaults_visible_controls_and_existing_layout(self):
self.open()
panel = self.go("login")
delay = self.delay_control(panel)
@@ -180,8 +180,13 @@ class AutoReloginBrowserTests(unittest.TestCase):
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 ("服务端", "记住账号和密码", "原区服", "角色", "恢复监控", "自动执行已勾选功能", "顶部“停止”", "关闭页面", "服务重启", "退出登录", "只有", "清除登录记录", "暂停"):
expect(panel).to_contain_text(text)
expect(panel.get_by_label("游戏账号", exact=True)).to_have_value("offline-fixture")
expect(panel.get_by_label("游戏密码", exact=True)).to_be_visible()
expect(panel.get_by_role("checkbox", name="记住账号和密码", exact=True)).to_be_checked()
expect(panel.get_by_label("区服 / 角色", exact=True)).to_be_visible()
expect(panel.get_by_role("button", name="进入选中区服", exact=True)).to_be_disabled()
expect(panel.get_by_role("button", name="恢复选中会话(无需重新输密码)", exact=True)).to_be_disabled()
expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("尚未保存登录角色")
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)
@@ -224,8 +229,8 @@ class AutoReloginBrowserTests(unittest.TestCase):
expect(toggle).to_have_text("停止")
expect(toggle).to_have_attribute("aria-pressed", "true")
expect(self.page.locator("#notice")).to_contain_text("已自动开启策略")
expect(self.page.locator("#status-text")).to_contain_text("已配置且已勾选的功能")
expect(self.page.locator("#data-summary")).to_contain_text("顶部“停止”")
expect(self.page.locator("#status-text")).to_contain_text("正在自动执行")
expect(self.page.locator("#data-summary")).to_contain_text("正在自动执行")
expect(self.page.locator("#page-tabs [role=tab]")).to_have_count(15)
self.assertEqual(self.configs[self.first], original, "Logging in must preserve every feature selection")
toggle.click()
@@ -352,8 +357,7 @@ class AutoReloginBrowserTests(unittest.TestCase):
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("记住账号和密码")
expect(hint).to_have_text("未保存账号或密码,自动重登不可用。")
self.page.wait_for_timeout(1000)
self.saved(self.first, False, 10)
expect(remember).not_to_be_checked()
@@ -425,7 +429,7 @@ class AutoReloginBrowserTests(unittest.TestCase):
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("正在自动执行已配置且已勾选的功能")
expect(self.page.locator("#data-summary")).to_contain_text("正在自动执行")
self.assertEqual(self.configs[self.first], original)
self.assertEqual(self.actions, [])
@@ -76,7 +76,9 @@ class ConnectionBrowserTests(unittest.TestCase):
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("缓存")
expect(panel.locator("[data-connection-status]")).to_contain_text(failure_reason)
expect(panel).to_have_attribute("aria-busy", "false")
expect(panel.locator(".page-loading")).to_be_hidden()
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()
@@ -98,7 +100,8 @@ class ConnectionBrowserTests(unittest.TestCase):
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("缓存")
expect(panel.locator(".page-loading")).to_have_attribute("data-loading", "false")
expect(panel.locator(".page-loading")).to_be_hidden()
self.assertEqual(self.page.locator("#page-tabs [role=tab]").count(), 15)
self.assertEqual(self.external_requests, [])
self.assertEqual(self.errors, [])
@@ -187,7 +190,10 @@ class ConnectionBrowserTests(unittest.TestCase):
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("缓存")
expect(panel.get_by_text("已保存的背包", exact=True)).to_be_visible()
expect(panel).to_have_attribute("aria-busy", "false")
expect(panel.locator(".page-loading")).to_have_attribute("data-loading", "false")
expect(panel.locator(".page-loading")).to_be_hidden()
self.page.locator('[data-command="start"]').dispatch_event("click")
self.page.locator("#refresh").dispatch_event("click")
self.page.wait_for_timeout(1800)
@@ -0,0 +1,190 @@
"""Focused loading regressions using disposable demo accounts and local routes only."""
from __future__ import annotations
import copy
from pathlib import Path
import time
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 PageLoadingBrowserTests(unittest.TestCase):
setUpClass = classmethod(fixtures.WorkbenchBrowserTests.setUpClass.__func__)
tearDownClass = classmethod(fixtures.WorkbenchBrowserTests.tearDownClass.__func__)
await_job = fixtures.WorkbenchBrowserTests.await_job
open = fixtures.WorkbenchBrowserTests.open
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, self.script_errors, self.pending = [], [], []
self.page.on("pageerror", lambda failure: self.script_errors.append(str(failure)))
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, connection_state="online", error="",
connection_message="游戏连接正常", running=False)
self.page.route("**/api/accounts", lambda route: self.fulfill(
route, [self.summary, self.manager.status(self.second)]))
self.response = {"loading": False, "data": {
"page": "bag", "summary": "32 项库存", "filters": [], "actions": [],
"form": [{"path": ["policy", "protect_star"], "label": "保护星级", "type": "integer", "min": 0, "max": 5}],
"columns": [{"key": "name", "label": "名称"}, {"key": "count", "label": "数量"},
{"key": "status", "label": "状态"}],
"rows": [{"id": str(i), "name": f"库存魔物 {i + 1}", "count": i + 1, "status": "可用"} for i in range(32)],
"details": {"help": "STATIC_HELP_SENTINEL", "note": "STATIC_NOTE_SENTINEL",
"notes": ["金币不足,等待补货"]}}}
self.hold, self.fail = False, False
def view(route):
if self.hold:
self.pending.append(route)
elif self.fail:
route.fulfill(status=503, content_type="application/json", body='{"detail":"读取失败"}')
else:
self.fulfill(route, self.response)
self.page.route(f"**/api/accounts/{self.first}/views/bag?*", view)
def tearDown(self):
try:
self.assertEqual(self.external_requests, [])
self.assertEqual(self.script_errors, [])
finally:
self.context.close()
def wait_request(self):
deadline = time.monotonic() + 8
while not self.pending and time.monotonic() < deadline:
self.page.wait_for_timeout(50)
self.assertTrue(self.pending, "Expected a delayed local view request")
return self.pending.pop(0)
def bag(self):
self.page.locator('.page-tab[data-page="bag"]').click()
return self.page.locator('.page-panel[data-page="bag"]:not([hidden])')
def assert_centered(self, panel):
spinner = panel.locator(".loading-spinner")
expect(spinner).to_be_visible()
body, circle = panel.locator(".page-body").bounding_box(), spinner.bounding_box()
for axis, size in (("x", "width"), ("y", "height")):
self.assertAlmostEqual(body[axis] + body[size] / 2, circle[axis] + circle[size] / 2, delta=2)
self.assertAlmostEqual(circle["width"], circle["height"], delta=1)
expect(panel).to_have_attribute("aria-busy", "true")
expect(panel.locator(".page-loading")).to_have_attribute("aria-label", "正在加载背包")
expect(panel.locator(".page-loading")).to_have_text("")
self.assertEqual(panel.locator(".page-header").inner_text(), "背包")
def test_delayed_empty_load_resolves_and_saves_screenshots(self):
self.open()
self.assertEqual(self.page.locator("#page-host > .loading-state").count(), 0)
self.hold = True
panel = self.bag()
route = self.wait_request()
self.assert_centered(panel)
artifacts = Path(__file__).resolve().parents[3] / "test-artifacts" / "ui205"
artifacts.mkdir(parents=True, exist_ok=True)
self.page.screenshot(path=str(artifacts / "loading-centered.png"))
self.fulfill(route, {"loading": True, "data": None})
route = self.wait_request()
self.assert_centered(panel)
self.page.emulate_media(reduced_motion="reduce")
self.assertEqual(panel.locator(".loading-spinner").evaluate("node => getComputedStyle(node).animationName"), "none")
self.page.set_viewport_size({"width": 375, "height": 812})
self.assert_centered(panel)
self.page.set_viewport_size({"width": 1280, "height": 800})
self.hold = False
self.fulfill(route, self.response)
expect(panel).to_have_attribute("aria-busy", "false")
expect(panel.locator(".page-loading")).to_be_hidden()
expect(panel.locator("tbody tr")).to_have_count(32)
self.page.screenshot(path=str(artifacts / "settled-dense.png"))
def test_passive_refresh_preserves_editing_table_and_business_reasons(self):
self.open()
panel = self.bag()
expect(panel.locator("tbody tr")).to_have_count(32)
expect(panel.locator('[data-view-status="planner_notes"]')).to_have_text("金币不足,等待补货")
self.assertNotIn("STATIC_HELP_SENTINEL", panel.inner_text())
self.assertNotIn("STATIC_NOTE_SENTINEL", panel.inner_text())
self.assertEqual(panel.locator(".info-note, .field-help").count(), 0)
field = panel.get_by_role("spinbutton", name="保护星级")
field.fill("")
field.evaluate("node => { window.loadingField = node; window.loadingTable = node.closest('.page-panel').querySelector('table'); }")
self.hold = True
route = self.wait_request() # The ordinary passive polling path.
self.assert_centered(panel)
self.assertEqual(panel.locator(".page-loading").evaluate("node => getComputedStyle(node).pointerEvents"), "none")
field.click(timeout=1500) # A visible spinner must allow native editing.
expect(field).to_be_focused()
self.fulfill(route, {**self.response, "loading": True})
route = self.wait_request() # The 650 ms pending-data follow-up.
self.hold = False
self.fulfill(route, self.response)
expect(panel).to_have_attribute("aria-busy", "false")
expect(field).to_be_focused()
expect(field).to_have_value("")
self.assertTrue(field.evaluate("node => node === window.loadingField && window.loadingTable.isConnected && node.closest('.page-panel').querySelector('table') === window.loadingTable"))
expect(self.page.locator("#log-panel")).to_be_hidden()
self.assertEqual(self.page.locator("#log-panel").count(), 1)
def test_failure_offline_and_account_switch_stop_loading(self):
self.open()
self.hold = True
panel = self.bag()
route = self.wait_request()
self.assert_centered(panel)
self.hold, self.fail = False, True
route.fulfill(status=503, content_type="application/json", body='{"detail":"读取失败"}')
expect(panel.locator(".page-error")).to_be_visible()
expect(panel).to_have_attribute("aria-busy", "false")
expect(panel.locator(".page-loading")).to_be_hidden()
self.hold, self.fail = True, False
panel.get_by_role("button", name="重新读取").click()
route = self.wait_request()
self.assert_centered(panel)
self.summary.update(connection_state="offline", connected=False, connection_message="连接已中断")
expect(self.page.locator("#connection")).to_have_text("游戏离线")
expect(panel).to_have_attribute("aria-busy", "false")
expect(panel.locator(".page-loading")).to_be_hidden()
self.hold = False
self.fulfill(route, {**self.response, "loading": True})
expect(panel.locator("tbody tr")).to_have_count(32)
expect(panel.get_by_role("spinbutton", name="保护星级")).to_be_enabled()
expect(panel.locator(".page-loading")).to_be_hidden()
self.summary.update(connection_state="online", connected=True, connection_message="游戏连接正常")
expect(self.page.locator("#connection")).to_have_text("已登录")
self.hold = True
self.page.locator('.page-tab[data-page="bag"]').click()
route = self.wait_request()
self.assert_centered(panel)
self.page.locator(f'.account-tab[data-account="{self.second}"]').click()
old_panel = self.page.locator('.page-panel[data-page="bag"]')
expect(old_panel).to_be_hidden()
expect(old_panel).to_have_attribute("aria-busy", "false")
self.fulfill(route, {**self.response, "loading": True})
self.page.wait_for_timeout(800)
expect(old_panel.locator(".page-loading")).to_be_hidden()
expect(old_panel).to_have_attribute("aria-busy", "false")
self.assertEqual(self.pending, [], "Inactive accounts must not retain pending-load retries")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,330 @@
"""Quiet shared UI with synthetic DTOs and browser-fulfilled HTTP only.
Run: python -B -m unittest ranch_web.tests.browser.test_quiet_ui_browser -v
Shared renderers use the real index shell with application bootstrap stubbed out.
Administrator-login tests load the real standalone HTML, JavaScript and CSS.
No server, account directory, backend API or external network is used.
"""
from __future__ import annotations
import json
from pathlib import Path
import time
import unittest
from urllib.parse import urlsplit
from .test_workbench_browser import AVAILABLE, EDGE
if AVAILABLE:
from playwright.sync_api import expect, sync_playwright
STATIC = Path(__file__).resolve().parents[2] / "static"
@unittest.skipUnless(AVAILABLE, "Python Playwright and a system Chromium browser are required")
class QuietUIBrowserTests(unittest.TestCase):
base = "http://quiet-ui.invalid"
@classmethod
def setUpClass(cls):
cls.playwright = sync_playwright().start()
cls.addClassCleanup(cls.playwright.stop)
cls.browser = cls.playwright.chromium.launch(executable_path=str(EDGE), headless=True)
cls.addClassCleanup(cls.browser.close)
def setUp(self):
self.context = self.browser.new_context(viewport={"width": 1280, "height": 800})
self.addCleanup(self.context.close)
self.addCleanup(self.context.unroute_all, behavior="ignoreErrors")
self.context.set_default_timeout(5000)
self.unexpected_requests, self.errors, self.login_requests = [], [], []
self.pending_status, self.pending_login = [], []
self.hold_status = self.hold_login = False
self.context.route("**/*", self.fixture)
self.page = self.context.new_page()
self.page.on("pageerror", lambda error: self.errors.append(str(error)))
def tearDown(self):
self.assertEqual(self.unexpected_requests, [])
self.assertEqual(self.errors, [])
@staticmethod
def reply(route, data, status=200):
route.fulfill(status=status, content_type="application/json", body=json.dumps(data, ensure_ascii=False))
def fixture(self, route):
request = route.request
path = urlsplit(request.url).path
if request.url.startswith(self.base + "/"):
if path == "/api/auth/status" and request.method == "GET":
if self.hold_status:
self.pending_status.append(route)
else:
self.reply(route, {"required": True, "authenticated": False})
return
if path == "/api/auth/login" and request.method == "POST":
self.login_requests.append(request.post_data_json)
if self.hold_login:
self.pending_login.append(route)
else:
self.reply(route, {"detail": "管理密码错误,请重试。"}, status=401)
return
if path == "/static/app.js":
route.fulfill(content_type="application/javascript", body="// Shared-renderer fixture; no application bootstrap.\n")
return
filename = {"/": "index.html", "/login": "login.html"}.get(path)
if path.startswith("/static/") and Path(path).name == path.removeprefix("/static/"):
filename = Path(path).name
if filename and (STATIC / filename).is_file():
content_type = {".html": "text/html", ".js": "application/javascript", ".css": "text/css"}.get(Path(filename).suffix)
if content_type:
route.fulfill(content_type=content_type, body=(STATIC / filename).read_bytes())
return
self.unexpected_requests.append((request.method, request.url))
route.abort()
def pending(self, requests):
deadline = time.monotonic() + 5
while not requests and time.monotonic() < deadline:
self.page.wait_for_timeout(10)
self.assertTrue(requests, "Expected an intercepted fixture request")
return requests.pop(0)
def open_shell(self):
self.page.goto(self.base + "/", wait_until="networkidle")
self.page.locator("#app").evaluate("node => {node.hidden = false;}")
def render_form(self, fields):
self.open_shell()
self.page.evaluate("""async fields => {
const {PolicyForm} = await import('/static/forms.js');
const {getPath, setPath} = await import('/static/dom.js');
window.values = {}; window.writes = [];
const host = document.querySelector('#page-host');
host.replaceChildren();
window.quietForm = new PolicyForm(host, {
get: (path, fallback) => getPath(window.values, path, fallback),
set: (path, value) => {
setPath(window.values, path, value);
window.writes.push({path, value});
},
});
window.quietForm.update(fields);
}""", fields)
def test_help_metadata_is_not_rendered_and_all_control_labels_remain(self):
fields = [
{"path": ["enabled"], "label": "自动领取", "type": "boolean", "value": True, "group": "策略"},
{"path": ["count"], "label": "领取数量", "type": "integer", "value": 2, "min": 1, "max": 5, "group": "策略"},
{"path": ["mode"], "label": "领取方式", "type": "select", "value": "all", "options": {"all": "全部", "daily": "每日"}},
{"path": ["name"], "label": "账号名称", "value": "离线账号"},
{"path": ["items"], "label": "物品编号", "type": "id_list", "value": [1]},
{"path": ["selected"], "label": "任务类型", "type": "multiselect", "value": ["daily"], "options": {"daily": "每日任务"}},
{"path": ["reserves"], "label": "物品保留", "type": "id_counts", "value": {"42": 2}},
{"path": ["locked"], "label": "只读设置", "value": "保留", "readonly": True},
{"path": ["rules"], "label": "魔物蛋", "type": "add_rule", "options": {"42": "测试蛋"}},
]
for index, field in enumerate(fields):
field["help" if index % 2 else "description"] = f"redundant-helper-{index}"
self.render_form(fields)
host = self.page.locator("#page-host")
expect(host.locator(".field-help")).to_have_count(0)
expect(host.locator(".field-label")).to_have_text([field["label"] for field in fields])
self.assertNotIn("redundant-helper-", host.evaluate("node => node.outerHTML"))
expect(host.get_by_role("checkbox", name="自动领取", exact=True)).to_be_checked()
expect(host.get_by_role("spinbutton", name="领取数量", exact=True)).to_have_value("2")
expect(host.get_by_role("combobox", name="领取方式", exact=True)).to_have_value("all")
expect(host.get_by_role("textbox", name="账号名称", exact=True)).to_have_value("离线账号")
expect(host.get_by_role("group", name="任务类型", exact=True)).to_be_visible()
expect(host.get_by_role("checkbox", name="每日任务", exact=True)).to_be_checked()
expect(host.get_by_role("group", name="物品保留", exact=True)).to_be_visible()
expect(host.get_by_role("spinbutton", name="物品保留数量", exact=True)).to_have_value("2")
expect(host.get_by_role("textbox", name="只读设置", exact=True)).to_be_disabled()
expect(host.get_by_role("combobox", name="魔物蛋", exact=True)).to_be_visible()
fields.append({"path": ["new"], "label": "新增设置", "help": "redundant-helper-new"})
self.page.evaluate("fields => window.quietForm.update(fields)", fields)
expect(host.get_by_role("textbox", name="新增设置", exact=True)).to_be_visible()
expect(host.locator(".field-help")).to_have_count(0)
self.assertNotIn("redundant-helper-", host.evaluate("node => node.outerHTML"))
self.assertEqual(self.page.evaluate("window.writes"), [])
def test_numeric_and_id_validation_still_reject_invalid_values_and_save_corrections(self):
self.render_form([
{"path": ["count"], "label": "领取数量", "type": "integer", "value": 2, "min": 1, "max": 5, "help": "redundant-helper-count"},
{"path": ["ids"], "label": "物品编号", "type": "id_list", "value": [1], "description": "redundant-helper-ids"},
])
count = self.page.get_by_role("spinbutton", name="领取数量", exact=True)
count.fill("0")
self.assertTrue(count.evaluate("node => node.validity.rangeUnderflow"))
self.assertEqual(self.page.evaluate("window.writes"), [])
count.fill("3")
ids = self.page.get_by_role("textbox", name="物品编号", exact=True)
ids.fill("1, wrong")
self.assertEqual(ids.evaluate("node => node.validationMessage"), "编号须为正整数,多个编号用逗号分隔")
self.assertEqual(self.page.evaluate("window.writes"), [{"path": ["count"], "value": 3}])
ids.fill("2, 2,3")
self.assertTrue(ids.evaluate("node => node.checkValidity()"))
self.assertEqual(self.page.evaluate("window.values"), {"count": 3, "ids": [2, 3]})
expect(self.page.locator(".field-help")).to_have_count(0)
def test_table_keeps_actionable_empty_state_and_member_validation_reasons(self):
self.open_shell()
self.page.evaluate("""async () => {
const {DataTable} = await import('/static/table.js');
const host = document.querySelector('#page-host'); host.replaceChildren();
window.writes = [];
window.quietTable = new DataTable(host, {
get: (path, fallback) => fallback,
set: (path, value) => window.writes.push({path, value}),
}, {emptyMessage: '没有可用队伍,请先添加魔物。'});
window.columns = [{key: 'name', label: '队伍'}, {key: 'members', label: '探险队伍', edit: {
type: 'members', path: ['teams', '*', 'members'],
options: [{value: 1, label: '队长', level: 30}, {value: 2, label: '队员甲', level: 20}, {value: 3, label: '队员乙', level: 10}],
}}];
window.quietTable.update(window.columns, []);
}""")
expect(self.page.locator(".empty-state")).to_have_text("没有可用队伍,请先添加魔物。")
self.page.evaluate("window.quietTable.update(window.columns, [{id: 'one', name: '第一队', members: []}])")
leader = self.page.get_by_role("combobox", name="探险队伍 · 第一队队长", exact=True)
member = self.page.get_by_role("combobox", name="探险队伍 · 第一队队员1", exact=True)
leader.select_option("1")
expect(self.page.locator(".member-draft-note")).to_have_text("已选择 1/3 只;选满队长和两名队员后保存")
member.select_option("1")
expect(self.page.locator(".member-draft-note")).to_have_text("探险队员不可重复")
self.assertEqual(member.evaluate("node => node.validationMessage"), "探险队员不可重复")
self.assertEqual(self.page.evaluate("window.writes"), [])
member.select_option("2")
self.page.get_by_role("combobox", name="探险队伍 · 第一队队员2", exact=True).select_option("3")
expect(self.page.locator(".member-draft-note")).to_be_hidden()
self.assertEqual(self.page.evaluate("window.writes"), [{"path": ["teams", "one", "members"], "value": [1, 2, 3]}])
def test_dialog_keeps_resource_fees_business_status_errors_and_destructive_confirmation(self):
self.open_shell()
self.page.evaluate("""async () => {
const {dialog} = await import('/static/ui.js');
const {el} = await import('/static/dom.js');
window.attempts = 0; window.result = null;
const count = el('input', {type: 'number', required: true, min: 1, 'aria-label': '扩建数量'});
const content = el('div', {}, el('p', {text: '扩建费用:金币 100、木材 20。消费后无法撤销。'}),
el('p', {class: 'info-note', role: 'status', text: '等待宿主机返回扩建结果…'}),
el('label', {}, '扩建数量', count));
dialog('确认扩建', content, {confirm: '确认消费', danger: true, read: async () => {
window.attempts += 1;
if (window.attempts === 1) throw new Error('金币不足:需要 100,当前 80,请补充后重试。');
return Number(count.value);
}}).then(value => {window.result = value;});
}""")
dialog = self.page.locator("#action-dialog")
expect(dialog).to_contain_text("扩建费用:金币 100、木材 20。消费后无法撤销。")
expect(dialog.get_by_role("status")).to_have_text("等待宿主机返回扩建结果…")
confirm = dialog.get_by_role("button", name="确认消费", exact=True)
expect(confirm).to_have_class("danger")
confirm.click()
self.assertEqual(self.page.evaluate("window.attempts"), 0)
dialog.get_by_role("spinbutton", name="扩建数量", exact=True).fill("1")
confirm.click()
expect(dialog.get_by_role("alert")).to_have_text("金币不足:需要 100,当前 80,请补充后重试。")
expect(confirm).to_be_enabled()
confirm.click()
expect(dialog).to_be_hidden()
self.assertEqual(self.page.evaluate("window.result"), 1)
self.page.evaluate("""async () => {
const {confirm} = await import('/static/ui.js');
window.result = null;
confirm('移除账号', '将删除此账号的配置和登录记录,无法撤销。', {danger: true})
.then(value => {window.result = value;});
}""")
expect(dialog).to_contain_text("将删除此账号的配置和登录记录,无法撤销。")
expect(self.page.locator("#dialog-cancel")).to_be_focused()
self.page.locator("#dialog-cancel").click()
self.assertFalse(self.page.evaluate("window.result"))
def test_login_check_has_centered_spinner_without_text_and_preserves_status_error(self):
self.hold_status = True
self.page.goto(self.base + "/login", wait_until="domcontentloaded")
pending = self.pending(self.pending_status)
status = self.page.locator("#auth-status")
expect(status).to_be_visible()
expect(status).to_have_class("loading-state")
expect(status).to_have_attribute("role", "status")
expect(status).to_have_attribute("aria-label", "加载中")
expect(status).to_have_text("")
expect(status.locator(".loading-spinner")).to_have_attribute("aria-hidden", "true")
expect(self.page.get_by_label("管理密码", exact=True)).to_be_disabled()
expect(self.page.get_by_role("button", name="登录", exact=True)).to_be_disabled()
expect(self.page.locator("#app, nav, #auth-description, .info-note, .field-help")).to_have_count(0)
for width, height in ((1280, 800), (390, 844)):
self.page.set_viewport_size({"width": width, "height": height})
spinner_box = status.locator(".loading-spinner").bounding_box()
status_box = status.bounding_box()
self.assertEqual(status.locator(".loading-spinner").evaluate("node => [node.offsetWidth, node.offsetHeight, getComputedStyle(node).borderRadius]"), [32, 32, "50%"])
self.assertAlmostEqual(spinner_box["x"] + spinner_box["width"] / 2, status_box["x"] + status_box["width"] / 2, delta=1)
self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), width)
self.page.emulate_media(reduced_motion="reduce")
self.assertEqual(status.locator(".loading-spinner").evaluate("node => getComputedStyle(node).animationName"), "none")
self.reply(pending, {"detail": "管理服务暂不可用(HTTP 503),请稍后重试。"}, status=503)
expect(status).to_be_hidden()
expect(self.page.get_by_role("alert")).to_have_text("管理服务暂不可用(HTTP 503),请稍后重试。")
expect(self.page.get_by_label("管理密码", exact=True)).to_be_enabled()
expect(self.page.locator("#auth-form")).to_have_attribute("aria-busy", "false")
def test_login_keeps_required_label_error_retry_and_spinner_during_submission(self):
self.page.goto(self.base + "/login", wait_until="networkidle")
password = self.page.get_by_label("管理密码", exact=True)
button = self.page.get_by_role("button", name="登录", exact=True)
status = self.page.locator("#auth-status")
expect(password).to_have_attribute("autocomplete", "current-password")
expect(password).to_have_attribute("aria-describedby", "auth-error")
expect(status).to_be_hidden()
button.click()
self.assertTrue(password.evaluate("node => node.validity.valueMissing"))
self.assertEqual(self.login_requests, [])
self.hold_login = True
password.fill("synthetic-admin-password")
button.click()
pending = self.pending(self.pending_login)
expect(status).to_be_visible()
expect(status).to_have_text("")
expect(status.locator(".loading-spinner")).to_have_count(1)
expect(password).to_be_disabled()
expect(password).to_have_value("")
expect(button).to_be_disabled()
reason = '管理密码错误,请重试。 <img src=x onerror="alert(1)">'
self.reply(pending, {"detail": reason}, status=401)
expect(self.page.get_by_role("alert")).to_have_text(reason)
expect(self.page.locator("#auth-error img")).to_have_count(0)
expect(status).to_be_hidden()
expect(password).to_be_enabled()
expect(button).to_be_enabled()
expect(self.page).to_have_url(self.base + "/login")
password.fill("synthetic-retry-password")
button.click()
pending = self.pending(self.pending_login)
expect(self.page.get_by_role("alert")).to_be_hidden()
expect(status.locator(".loading-spinner")).to_have_count(1)
self.reply(pending, {"required": True, "authenticated": True})
expect(self.page).to_have_url(self.base + "/")
self.assertEqual(self.login_requests, [{"password": "synthetic-admin-password"}, {"password": "synthetic-retry-password"}])
def test_initial_workspace_spinner_version_and_single_bottom_log_are_preserved(self):
self.page.goto(self.base + "/", wait_until="networkidle")
expect(self.page.locator("#app")).to_be_hidden()
spinner = self.page.locator("#page-host > .loading-state")
expect(spinner).to_have_attribute("role", "status")
expect(spinner).to_have_attribute("aria-label", "加载中")
expect(spinner).to_have_text("")
expect(spinner.locator(".loading-spinner")).to_have_attribute("aria-hidden", "true")
expect(self.page.locator("#app-version")).to_have_text("2.0.5")
expect(self.page.locator("#access-mode")).to_have_text("")
expect(self.page.locator("#log-panel")).to_have_count(1)
expect(self.page.locator('[role="log"]')).to_have_count(1)
expect(self.page.locator("#log-panel")).to_be_hidden()
self.assertTrue(self.page.locator("#log-panel").evaluate("""node =>
Boolean(document.querySelector('#workspace').compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING)
&& Boolean(node.compareDocumentPosition(document.querySelector('.status-bar')) & Node.DOCUMENT_POSITION_FOLLOWING)
"""))
if __name__ == "__main__":
unittest.main()
@@ -74,14 +74,14 @@ class RunIntentBrowserTests(unittest.TestCase):
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(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("#data-summary")).to_contain_text("上次失败")
expect(self.page.locator("#connection")).to_have_text("已登录")
expect(self.page.locator("#log-panel")).to_be_hidden()
@@ -122,7 +122,7 @@ class RunIntentBrowserTests(unittest.TestCase):
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("正在自动执行")
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, [])
@@ -138,7 +138,7 @@ class RunIntentBrowserTests(unittest.TestCase):
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("策略运行中")
expect(self.page.locator("#data-summary")).not_to_contain_text("用户暂停")
self.assertEqual(self.actions, [])
@@ -167,7 +167,7 @@ class RunIntentBrowserTests(unittest.TestCase):
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("#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"])
@@ -110,8 +110,10 @@ class WorkbenchBrowserTests(unittest.TestCase):
def go(self, key, page=None):
page=page or self.page
page.locator(f'.page-tab[data-page="{key}"]').click()
page.wait_for_selector(f'.page-panel[data-page="{key}"]:not([hidden]) .page-loading[data-loading="false"]')
return page.locator(f'.page-panel[data-page="{key}"]:not([hidden])')
page.wait_for_selector(f'.page-panel[data-page="{key}"]:not([hidden]) .page-loading[data-loading="false"]', state="attached")
panel = page.locator(f'.page-panel[data-page="{key}"]:not([hidden])')
expect(panel).to_have_attribute("aria-busy", "false")
return panel
@staticmethod
def field(root,path):