"""Self-input stats visual/data contract. Only loopback static assets reach the network.""" import argparse import io import json import re from pathlib import Path from urllib.parse import parse_qs, urlsplit from PIL import Image from playwright.sync_api import expect, sync_playwright from browser_contract import ACCOUNT, LOGIN, OFFICIAL, OVERVIEW, PASS, SELF, TOKEN, USER, Fixture, desktop_entry, loopback SOURCE = "离线验收来源" PERMS = {"edit": "stats.personal_yeji/edit", "delete": "stats.personal_yeji/delete"} PAGE = "main .self-input-stats-page" EMPTY = re.compile(r"^(?:[-–—―]+|暂无(?:数据)?|未(?:提供|返回|统计)|无数据|N/A)$", re.I) class StatsFixture(Fixture): def __init__(self, host, role): super().__init__(host, False, False) if role in PERMS: self.reads[SELF]["permissions"].append(PERMS[role]) self.reads["/stats.self_input/mediaSourceOptions"] = [{"name": SOURCE, "value": "native"}] self.reads["/dept.dept/all"] = [{"id": 42, "name": "离线部门", "children": []}] self.hold = {"today"} if role == "reader" else set() self.pending, self.queries = {}, [] self.large_amount, self.fail_next = False, False def route(self, route): req, url = route.request, urlsplit(route.request.url) if (f"{url.scheme}://{url.netloc}", url.path, req.method) != (OFFICIAL, "/adminapi" + OVERVIEW, "GET"): return super().route(route) if req.headers.get("token") != TOKEN: self.errors.append("overview without fixture session") return route.abort() self.calls.append(["GET", OVERVIEW]) query = {k: v[0] for k, v in parse_qs(url.query).items()} self.queries.append(query) period = query.get("time_type") if period not in {"today", "week", "month", "yesterday", "custom"}: self.errors.append("unexpected stats range") return route.abort() if period in self.hold: self.hold.remove(period) self.pending[period] = (route, query) else: self.respond(route, query) def release(self, period): self.respond(*self.pending.pop(period)) def respond(self, route, query): period = query["time_type"] if self.fail_next: self.fail_next = False return route.fulfill(headers={"Access-Control-Allow-Origin": self.base}, json={ "code": 0, "show": 0, "msg": "离线查询失败", "data": None}) n, date = {"today": (17, "2026-01-30"), "week": (31, "2026-01-24"), "month": (87, "2026-01-01"), "yesterday": (0, "2026-01-29"), "custom": (5, query.get("start_date", ""))}[period] fields = {"add_fans_count": n, "total_open_count": 0, "order_amount": 12.50, "paid_appointment_count": None, "total_open_rate": 0} if self.large_amount: fields["order_amount"] = 12345678901234.50 finance = period == "week" if finance: fields.update(account_cost=321.25, roi=1.5, cash_cost=0) empty = period == "yesterday" label = "ROW-" + period + ("-filtered" if "media_source" in query else "") row = dict(fields, id=1, media_source=label, yeji_date=date, creator_name="离线录入员") data = {"lists": [] if empty else [row], "count": 0 if empty else 1, "extend": {"date_range": [date, date if empty else "2026-01-30"], "summary": fields, "can_view_finance": finance}} route.fulfill(headers={"Access-Control-Allow-Origin": self.base, "Cache-Control": "no-store"}, json={"code": 1, "show": 0, "msg": "", "data": data}) def check(report, name, result, actual): report["checks"][name] = {"ok": bool(result), "actual": actual} def shot(page, out, name): if out: page.screenshot(path=str(out / f"stats-{name}.png"), animations="disabled") def card(stats, label): return stats.locator(".stats-kpi-card").filter(has=stats.page.get_by_text(label, exact=True)) def value(stats, label): return card(stats, label).locator(".stats-kpi-value").inner_text().strip() def row_visible(stats, period): expect(stats.locator(".el-table__body").get_by_text("ROW-" + period, exact=True)).to_be_visible() def row_value(stats, label): # Element's column id is shared by the header and the body, even with sticky columns. return stats.locator(".el-table").evaluate("""(table, name) => { const th = [...table.querySelectorAll('thead th')].find(h => h.innerText.trim() === name); const id = th && [...th.classList].find(n => /_column_/.test(n)); return id ? table.querySelector('tbody td.' + id)?.textContent.trim() : null; }""", label) def luminance(rgb): channels = [v / 255 for v in rgb[:3]] linear = [v / 12.92 if v <= .04045 else ((v + .055) / 1.055) ** 2.4 for v in channels] return sum(v * w for v, w in zip(linear, (.2126, .7152, .0722))) def palette(stats): target = card(stats, "加粉数") # Sample actual rendered pixels, not just backgroundColor (the baseline paints a gradient). im = Image.open(io.BytesIO(target.screenshot(animations="disabled"))).convert("RGB") background = im.getpixel((im.width * 3 // 4, im.height // 2)) colors = target.evaluate("""el => ['.stats-kpi-label','.stats-kpi-value'].map(s => { const c = document.createElement('canvas').getContext('2d'); c.fillStyle = getComputedStyle(el.querySelector(s)).color; c.fillRect(0,0,1,1); return [...c.getImageData(0,0,1,1).data]; })""") bg = luminance(background) ratios = [] for rgb in colors: alpha = rgb[3] / 255 fg = luminance([v * alpha + b * (1 - alpha) for v, b in zip(rgb, background)]) ratios.append(round((max(fg, bg) + .05) / (min(fg, bg) + .05), 2)) return {"rgb": background, "luminance": round(bg, 3), "label_contrast": ratios[0], "value_contrast": ratios[1]} def mobile_geometry(stats): return stats.evaluate("""root => { const visible = e => e.getClientRects().length && getComputedStyle(e).visibility !== 'hidden'; const w = document.documentElement.clientWidth, rect = e => e.getBoundingClientRect(); const elements = [...root.querySelectorAll('.stats-filter-form .el-radio-button,.stats-filter-form .el-select,' + '.stats-filter-form .el-button,.stats-kpi-card,.stats-detail-card,.el-pagination button,' + '.el-pagination .number,.el-pagination .el-select,.el-pagination .el-input')].filter(visible); const clipped = elements.filter(e => rect(e).x < -1 || rect(e).right > w + 1) .map(e => [e.textContent.trim().slice(0,20) || e.className, Math.round(rect(e).x),Math.round(rect(e).right)]); const table = root.querySelector('.el-table__body-wrapper .el-scrollbar__wrap'); const cards = [...root.querySelectorAll('.stats-kpi-card')].filter(visible).map(rect); const firstRow = cards.filter(r => Math.abs(r.top - cards[0].top) < 2); const overlap = firstRow.some((r,i) => i && r.left < firstRow[i - 1].right - 1); return {width:w,clipped,rootWidth:root.clientWidth,contentWidth:root.scrollWidth, cardsPerRow:firstRow.length,cardWidth:Math.round(firstRow[0]?.width || 0),overlap, detailOffset:Math.round(rect(root.querySelector('.stats-detail-card')).top - rect(root).top), tableWidth:table.clientWidth,tableContentWidth:table.scrollWidth}; }""") def wait_query(page, fixture, *, query_count=None, pending=None): # Pump browser events while a routed request is deliberately left unanswered. for _ in range(100): if ((query_count is None or len(fixture.queries) >= query_count) and (pending is None or pending in fixture.pending)): return page.wait_for_timeout(30) raise AssertionError(f"missing fixture query: pending={pending}, queries={fixture.queries}") def enter(page, fixture): 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) expect(page.locator("html")).to_have_attribute("data-admin-ui", "v2") desktop_entry(page, "自录转化统计").click() stats = page.locator(PAGE) expect(stats).to_be_visible() return stats def permission_checks(stats, role, report): table = stats.locator(".el-table") actions = { "column": table.locator("thead th").get_by_text("操作", exact=True).count(), "edit": table.get_by_role("button", name="编辑", exact=True).count(), "delete": table.get_by_role("button", name="删除", exact=True).count(), } wanted = {"column": int(role != "reader"), "edit": int(role == "edit"), "delete": int(role == "delete")} check(report, f"permissions_{role}", actions == wanted, actions) def reader_checks(page, stats, fx, report, out): wait_query(page, fx, pending="today") loading = card(stats, "加粉数") val = loading.locator(".stats-kpi-value").inner_text().strip() if loading.locator(".stats-kpi-value").count() else "" busy = stats.locator("[aria-busy=true]:visible,.el-skeleton:visible,.el-loading-mask:visible,[role=progressbar]:visible").count() loading_text = bool(re.search(r"加载|读取|统计中", stats.inner_text())) check(report, "initial_loading_not_zero", not re.search(r"\d", val) and (busy or loading_text), {"value": val, "busy": busy, "loading_text": loading_text}) shot(page, out, "loading") fx.release("today") row_visible(stats, "today") permission_checks(stats, "reader", report) values = {k: value(stats, k) for k in ("加粉数", "总开口", "未回复", "付费挂号", "订单金额", "总开口率")} cells = {k: row_value(stats, k) for k in ("总开口", "未回复", "付费挂号")} check(report, "known_values_and_real_zero", [values[k] for k in ("加粉数", "总开口", "总开口率")] == ["17", "0", "0.00%"] and values["订单金额"] in {"¥12.50", "¥12.50"} and cells["总开口"] == "0", values) check(report, "missing_and_null_not_zero", all(EMPTY.fullmatch(v or "") for v in (values["未回复"], values["付费挂号"], cells["未回复"], cells["付费挂号"])), cells) light = palette(stats) check(report, "light_cards", light["luminance"] > .5 and min(light["label_contrast"], light["value_contrast"]) >= 4.5, light) shot(page, out, "light") page.emulate_media(color_scheme="dark") expect(page.locator("html")).to_have_class(re.compile(r"\bdark\b")) dark = palette(stats) check(report, "dark_cards", dark["luminance"] < .2 and min(dark["label_contrast"], dark["value_contrast"]) >= 4.5, dark) shot(page, out, "dark") # First a normal finance-enabled result. Then the same period is delayed and must lose to month. stats.get_by_text("最近7天", exact=True).click() row_visible(stats, "week") check(report, "finance_granted", card(stats, "账户消耗").count() == 1 and value(stats, "ROI") == "1.50" and row_value(stats, "账户消耗") in {"¥321.25", "¥321.25"}, {"finance_cards": card(stats, "账户消耗").count(), "finance_column": row_value(stats, "账户消耗")}) stats.get_by_text("今天", exact=True).click() row_visible(stats, "today") fx.hold.add("week") stats.get_by_text("最近7天", exact=True).click() wait_query(page, fx, pending="week") stats.get_by_text("最近30天", exact=True).click() row_visible(stats, "month") # Observe completion of the *older* reply before checking that it did not replace the latest results. with page.expect_event("requestfinished", predicate=lambda r: urlsplit(r.url).path == "/adminapi" + OVERVIEW and parse_qs(urlsplit(r.url).query).get("time_type") == ["week"]): fx.release("week") page.evaluate("() => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))") race = {"value": value(stats, "加粉数"), "month": stats.get_by_text("ROW-month", exact=True).count(), "finance_card": card(stats, "账户消耗").count(), "finance_column": row_value(stats, "账户消耗"), "range": stats.locator(".stats-detail-card .el-card__header").inner_text()} check(report, "latest_response_wins", race["value"] == "87" and race["month"] == 1 and race["finance_card"] == 0 and race["finance_column"] is None and "2026-01-01" in race["range"], race) filters = stats.locator(".stats-filter-form") filters.locator(".el-form-item").filter(has_text="部门").locator(".el-select__wrapper").click() page.get_by_role("treeitem").get_by_text("离线部门", exact=True).click() filters.locator(".el-form-item").filter(has_text="自媒体来源").locator(".el-select__wrapper").click() page.get_by_role("option", name=SOURCE, exact=True).click() row_visible(stats, "month-filtered") query = fx.queries[-1] check(report, "filters_keep_real_parameters", all(query.get(k) == v for k, v in {"time_type":"month", "dept_id":"42", "media_source":SOURCE, "page_no":"1", "page_size":"15"}.items()), query) filters.get_by_role("button", name="重置").click() row_visible(stats, "today") query = fx.queries[-1] check(report, "reset_actual_query", query.get("time_type") == "today" and not query.get("media_source") and not query.get("dept_id") and query.get("page_no") == "1", query) page.set_viewport_size({"width":390, "height":844}) expect(page.locator(".app-aside .side")).to_be_hidden() dimensions = mobile_geometry(stats) check(report, "390px_two_column_cards", dimensions["cardsPerRow"] == 2, dimensions) check(report, "390px_controls_and_local_table_scroll", not dimensions["clipped"] and not dimensions["overlap"] and dimensions["contentWidth"] <= dimensions["rootWidth"] + 1 and dimensions["tableContentWidth"] > dimensions["tableWidth"] > 0, dimensions) shot(page, out, "mobile") fx.large_amount = True filters.get_by_role("button", name="查询", exact=True).click() amount = card(stats, "订单金额").locator(".stats-kpi-value") expect(amount).to_have_text(re.compile(r"12345678901234\.50")) box = amount.evaluate("""el => { const r = document.createRange(); r.selectNodeContents(el); const card = el.closest('.stats-kpi-card').getBoundingClientRect(); const fragments = [...r.getClientRects()].filter(r => r.width && r.height); return {count: fragments.length, fits: fragments.every(r => r.left >= card.left && r.right <= card.right && r.bottom <= card.bottom)}; }""") check(report, "390px_full_amount_fits", box["count"] and box["fits"], box) fx.large_amount = False fx.fail_next = True filters.get_by_text("最近7天", exact=True).click() expect(stats.locator(".el-table__body tbody tr")).to_have_count(0) expect(stats.get_by_role("alert")).to_be_visible() expect(filters.get_by_role("button", name="查询", exact=True)).to_be_enabled() stale = value(stats, "加粉数") check(report, "failed_query_clears_stale_results", EMPTY.fullmatch(stale or ""), stale) filters.get_by_role("button", name="查询", exact=True).click() row_visible(stats, "week") check(report, "retry_succeeds", value(stats, "加粉数") == "31", value(stats, "加粉数")) filters.get_by_text("昨天", exact=True).click() expect(stats.locator(".el-table__body tbody tr")).to_have_count(0) expect(card(stats, "加粉数").locator(".stats-kpi-value")).to_have_text("0") empty_state = stats.locator(".el-table__empty-text").inner_text().strip() check(report, "empty_result_has_true_zero", bool(empty_state) and value(stats, "加粉数") == "0", empty_state) # An incomplete custom range must not replay the preceding period's totals. n = len(fx.queries) filters.get_by_text("自定义", exact=True).click() submit = filters.get_by_role("button", name="查询", exact=True) expect(submit).to_be_disabled() check(report, "incomplete_custom_range", n == len(fx.queries) and EMPTY.fullmatch(value(stats, "加粉数")), {"queries":len(fx.queries)-n}) filters.get_by_placeholder("开始日期").click() dates = page.locator(".el-date-range-picker__content.is-left:visible td.available") dates.nth(2).click() dates.nth(4).click() row_visible(stats, "custom") query = fx.queries[-1] check(report, "custom_range_actual_dates", query.get("time_type") == "custom" and re.fullmatch(r"\d{4}-\d\d-\d\d", query.get("start_date","")) and query["start_date"] < query.get("end_date",""), query) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--host", type=loopback, default="127.0.0.1:5179") parser.add_argument("--out", type=Path, help="Write JSON and local screenshots to this directory") args = parser.parse_args() if args.out: args.out.mkdir(parents=True, exist_ok=True) report = {"checks": {}, "infrastructure_errors": []} with sync_playwright() as pw, pw.chromium.launch(headless=True, args=[ "--disable-background-networking", "--disable-quic", "--no-proxy-server", "--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1"]) as browser: for role in ("reader", "edit", "delete"): fixture = StatsFixture(args.host, role) with browser.new_context(service_workers="block", viewport={"width":1440,"height":960}, color_scheme="light") as ctx: ctx.set_default_timeout(6000) ctx.route("**/*", fixture.route) ctx.route_web_socket("**/*", lambda ws: (fixture.errors.append("unexpected WebSocket"), ws.close())) page = ctx.new_page() page.on("pageerror", lambda err: fixture.errors.append(str(err))) try: stats = enter(page, fixture) if role == "reader": reader_checks(page, stats, fixture, report, args.out) else: row_visible(stats, "today") permission_checks(stats, role, report) assert [p for m, p in fixture.calls if m == "POST"] == [LOGIN] except Exception as e: report["infrastructure_errors"].append({"role": role, "error": str(e)}) shot(page, args.out, f"failure-{role}") report["infrastructure_errors"].extend(fixture.errors) report["status"] = ("PASS" if report["checks"] and all(c["ok"] for c in report["checks"].values()) and not report["infrastructure_errors"] else "FAIL") report["real_api_calls"] = 0 if args.out: (args.out / "stats-visual.json").write_text(json.dumps(report, ensure_ascii=False, indent=2)+"\n") print(json.dumps(report, ensure_ascii=False)) return int(report["status"] != "PASS") if __name__ == "__main__": raise SystemExit(main())