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

331 lines
19 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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()