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

215 lines
11 KiB
Python

"""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
self.hold_after_real_retry_click = False
self.page.add_init_script("""(() => {
window.__loadingRetryClicked = false;
document.addEventListener('click', event => {
if (event.target instanceof Element && event.target.closest('.page-panel[data-page="bag"] .page-error button')) {
window.__loadingRetryClicked = true;
}
}, true);
})();""")
def view(route):
if self.hold_after_real_retry_click:
if not self.page.evaluate("window.__loadingRetryClicked"):
route.fulfill(status=503, content_type="application/json", body='{"detail":"读取失败"}')
return
self.hold_after_real_retry_click = False
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_without_inline_notes(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_count(0)
expect(panel).not_to_contain_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(panel).not_to_contain_text("金币不足,等待补货")
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()
# Passive polling must keep returning the error until the native click.
# Holding a passive request here would hide the button before it can click.
self.hold_after_real_retry_click = True
self.hold, self.fail = True, False
with self.page.expect_response(lambda response: "/views/bag?" in response.url and response.status == 503):
pass # Exercise a real passive refresh during this transition.
expect(panel.locator(".page-error")).to_be_visible()
self.assertEqual(self.pending, [], "Passive errors must not park a request before the retry click")
panel.get_by_role("button", name="重新读取").click()
self.assertTrue(self.page.evaluate("window.__loadingRetryClicked"))
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()