Files
zyt/admin/live-native/browser_tabs.py
T

184 lines
8.3 KiB
Python

"""Offline Playwright contract for the real native work tabs (never contacts the official API)."""
import argparse
import json
import re
from pathlib import Path
from urllib.parse import parse_qs, urlsplit
from playwright.sync_api import expect, sync_playwright
from browser_contract import ACCOUNT, COST, LOGIN, OVERVIEW, PASS, SELF, USER, Fixture, loopback, menu, open_group
HOME = "自录转化统计"
LONG = "账户消耗录入与跨部门合作经营分析报表历史记录逐日统计明细汇总工作清单"
THIRD = "渠道复核"
TOOLS = "标签页操作"
def register_menu(fixture):
leaves = fixture.reads[SELF]["menu"][0]["children"][0]["children"]
leaves[1]["name"] = LONG
leaves.append(menu(305, THIRD, "review?via=tabs&team=qa", component="stats/self_input/index"))
def geometry(tab):
return tab.evaluate("""async el => {
const next = () => new Promise(r => requestAnimationFrame(r));
await next(); await next();
const strip = el.closest('.app-tabs');
await Promise.allSettled(strip.getAnimations({subtree:true})
.filter(a => a.effect?.getComputedTiming().endTime < Infinity).map(a => a.finished));
const r = el.getBoundingClientRect(), clip = strip.querySelector('.el-tabs__nav-scroll').getBoundingClientRect();
const x = el.querySelector('.is-icon-close'), c = x.getBoundingClientRect();
const hit = (node,rect) => node.contains(document.elementFromPoint(rect.x+rect.width/2, rect.y+rect.height/2));
const label = [...el.querySelectorAll('*')].find(n => n.innerText === el.innerText &&
getComputedStyle(n).textOverflow === 'ellipsis' && n.scrollWidth > n.clientWidth);
return {tabWidth:r.width, stripWidth:clip.width, inside: r.left >= clip.left-1 && r.right <= clip.right+1,
hitLabel: hit(el,r), hitClose: c.width > 0 && hit(x,c), ellipsis: !!label,
overlap: label ? label.getBoundingClientRect().right > c.left+1 : null,
title: el.title || [...el.querySelectorAll('[title]')].find(n=>n.title)?.title || '',
namedActions: !!strip.querySelector('button[aria-label="标签页操作"]')};
}""")
def shot(page, out, name):
if out:
page.screenshot(path=str(out / f"tabs-{name}.png"), animations="disabled")
def exercise(page, fixture, out):
page.goto(fixture.base + "/admin/login")
page.get_by_placeholder("请输入账号").fill(ACCOUNT)
page.get_by_placeholder("请输入密码").fill(PASS)
page.get_by_role("button", name="登录", exact=True).click()
expect(page.locator(".app-header").get_by_text(USER, exact=True)).to_be_visible(timeout=15000)
strip = page.locator(".app-tabs")
tabs = strip.get_by_role("tab")
actions = strip.get_by_role("button", name=TOOLS, exact=True)
tab = lambda name: strip.get_by_role("tab", name=name, exact=True)
cmd = lambda name: page.get_by_role("menuitem", name=name, exact=True)
menu_root = page.locator(".app-aside .menu:visible")
def visit(name):
parent = open_group(open_group(menu_root, "数据统计"), "自录数据统计")
parent.get_by_role("link", name=name, exact=True).click()
active(name)
def active(name):
expect(tab(name)).to_have_attribute("aria-selected", "true")
path, query, component = {
HOME: ("/admin/stats/self_input", {}, "self-input-stats-page"),
LONG: ("/admin/stats/self_input/account_cost", {"via": ["sidebar"]}, "personal-account-cost-page"),
THIRD: ("/admin/stats/self_input/review", {"via": ["tabs"], "team": ["qa"]}, "self-input-stats-page"),
}[name]
expect(page).to_have_url(re.compile(re.escape(path) + r"/?(?:\?.*)?$"))
assert parse_qs(urlsplit(page.url).query) == query, ("route query", name)
expect(page.locator("main ." + component)).to_be_visible()
expect(strip.locator('[role=tab][aria-selected="true"]')).to_have_count(1)
visit(HOME)
visit(LONG)
visit(THIRD)
expect(tabs).to_have_count(3)
tab(LONG).click()
active(LONG)
# An inactive close icon must remove *that* tab without first navigating to it.
tab(THIRD).locator(".is-icon-close").click()
expect(tabs).to_have_count(2)
active(LONG)
visit(THIRD)
# A user may follow an in-page bookmark; switching tabs must not drop it.
page.evaluate("location.hash = 'details'")
expect(tab(THIRD)).to_have_attribute("id", re.compile(r"#details$"))
tab(HOME).click()
active(HOME)
page.emulate_media(color_scheme="dark")
expect(page.locator("html")).to_have_class(re.compile(r"\bdark\b"))
page.set_viewport_size({"width": 390, "height": 844})
tab(HOME).focus()
page.keyboard.press("ArrowRight")
active(LONG)
metrics = geometry(tab(LONG))
# ElTabs schedules scrollToActiveTab after the route update and resize
# observer. Poll the painted hit targets, rather than assume two frames.
for _ in range(25):
if metrics["inside"] and metrics["hitClose"]:
break
page.wait_for_timeout(40)
metrics = geometry(tab(LONG))
print("dark 390px:", json.dumps(metrics, ensure_ascii=False), flush=True)
shot(page, out, "dark-390")
assert metrics["inside"] and metrics["hitClose"] and metrics["hitLabel"], metrics
assert metrics["ellipsis"] and not metrics["overlap"], metrics
if metrics["title"] != LONG:
tab(LONG).hover()
expect(page.get_by_role("tooltip").get_by_text(LONG, exact=True)).to_be_visible()
expect(actions).to_be_visible()
tab(LONG).focus()
page.keyboard.press("Tab")
expect(actions).to_be_focused()
page.keyboard.press("Enter")
expect(cmd("关闭当前")).to_be_visible()
page.keyboard.press("Escape")
expect(cmd("关闭当前")).to_be_hidden()
expect(actions).to_be_focused()
actions.press("Enter")
cmd("关闭当前").click()
expect(tabs).to_have_count(2)
expect(tab(LONG)).to_have_count(0)
active(HOME)
# Route & query of the retained tab must survive both the switch and bulk close.
tab(THIRD).click()
active(THIRD)
assert urlsplit(page.url).fragment == "details", page.url
actions.click()
cmd("关闭其他").click()
expect(tabs).to_have_count(1)
active(THIRD)
expect(tab(THIRD).locator(".is-icon-close")).to_have_count(0)
actions.press("Enter")
expect(cmd("关闭当前")).to_be_disabled()
expect(cmd("关闭其他")).to_be_disabled()
shot(page, out, "single")
page.keyboard.press("Escape")
expect(cmd("关闭其他")).to_be_hidden()
return metrics
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--host", type=loopback, default="127.0.0.1:5179")
parser.add_argument("--chrome", required=True)
parser.add_argument("--out", type=Path, help="Optional directory for local screenshots")
args = parser.parse_args()
if args.out:
args.out.mkdir(parents=True, exist_ok=True)
fixture = Fixture(args.host, False, False)
register_menu(fixture)
with sync_playwright() as pw, pw.chromium.launch(executable_path=args.chrome, args=[
"--disable-background-networking", "--disable-quic", "--no-proxy-server",
"--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1"]) as browser:
with browser.new_context(service_workers="block", viewport={"width": 1440, "height": 960},
color_scheme="light") as ctx:
ctx.set_default_timeout(8000)
ctx.route("**/*", fixture.route)
ctx.route_web_socket("**/*", lambda ws: (fixture.errors.append("unexpected WebSocket"), ws.close()))
ctx.on("page", lambda p: p.on("pageerror", lambda e: fixture.errors.append(str(e))))
page = ctx.new_page()
try:
metrics = exercise(page, fixture, args.out)
assert ["GET", COST] in fixture.calls and ["GET", OVERVIEW] in fixture.calls
assert [p for method, p in fixture.calls if method == "POST"] == [LOGIN], fixture.calls
assert not fixture.errors, fixture.errors
except Exception:
shot(page, args.out, "failure")
print("mocked:", fixture.calls, "errors:", fixture.errors, flush=True)
raise
print(json.dumps({"work_tabs": "PASS", "real_api_calls": 0, "dark390": metrics}, ensure_ascii=False))
if __name__ == "__main__":
main()