"""Black-box menu contract. Run against the local static build; no real network or account.""" 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 HOST = "admin.zhenyangtang.com.cn" LOGIN = "/adminapi/login/account" SELF = "/adminapi/auth.admin/mySelf" ORDERS = "/adminapi/order.order/lists" ACCOUNT, PASSWORD, TOKEN = "offline-menu-qa", "offline-only-password", "offline-only-session" ROW, FILTERED = "OFFLINE-ROW-001", "OFFLINE-MATCH-002" def node(id_, name, path, children=None, component="", perms="", **flags): entry = dict(id=id_, name=name, paths=path, type="M" if children is not None else "C", component=component, perms=perms, is_show=1, is_disable=0) entry.update(flags) if children is not None: entry["children"] = children return entry def profile(phase): first_group = node(91, "收费事务", "payments", [ node(83, "对账事务", "settlement", [ node(72, "处方收款明细", "receipts", component="order/index", perms="order.order/lists"), node(35, "业务台账", "ledger", component="settle/ledger", perms="settle.ledger/lists"), node(36, "隐藏的测试入口", "hidden", component="unused/index", is_show=0), node(37, "停用的测试入口", "disabled", component="unused/index", is_disable=1), ]), node(18, "阶段汇总", "summary", component="settle/summary", perms="settle.summary/lists"), node(19, "隐藏的目录", "secret", [node(20, "隐藏目录的子项", "child")], is_show=0), ]) second_group = node(12, "门诊事务", "clinic", [ node(31, "业务台账", "ledger", component="clinic/ledger", perms="clinic.ledger/lists"), # The visible menu alone is not a grant for this locally supported screen. node(40, "就诊人资料", "people", component="consumer/lists/index", perms="user.user/lists"), node(32, "操作按钮", "edit", type="A", perms="clinic.ledger/edit"), ]) menus = {"initial": [first_group, second_group], "empty": [], "clinic": [second_group]} grants = {"initial": ["order.order/lists", "settle.ledger/lists", "settle.summary/lists", "clinic.ledger/lists", "clinic.ledger/edit"], "empty": [], "clinic": ["clinic.ledger/lists"]} return {"user": {"id":991, "name":"菜单验收角色", "disable":0, "is_paw":1, "need_bind_work_wechat":False, "root":0}, "permissions":grants[phase], "menu":menus[phase]} class Offline: def __init__(self, base): self.base = base self.phase = "initial" self.calls = [] self.bad = [] self.documents = [] self.explicit = False def route(self, route): req = route.request url = urlsplit(req.url) key = (req.method, url.path) def deny(reason): self.bad.append((reason, *key)) route.abort() if (url.scheme, url.netloc) == ("http", urlsplit(self.base).netloc): if req.method == "GET" and (url.path.startswith("/admin/assets/") or (req.resource_type == "document" and url.path.startswith("/admin/"))): return route.continue_() return deny("unexpected local request") if (url.scheme, url.netloc) != ("https", HOST): return deny("non-fixture origin") if req.resource_type == "document": if (not self.explicit or req.method != "GET" or url.path.startswith("/adminapi") or any(s in req.url for s in (ACCOUNT, PASSWORD, TOKEN)) or any(req.headers.get(h) for h in ("cookie", "token", "authorization"))): return deny("unexpected official navigation") self.documents.append(url.path) return route.fulfill(content_type="text/html", body="Offline official-site fixture") if url.path not in (LOGIN, SELF, ORDERS): return deny("non-fixture API") cors = {"Access-Control-Allow-Origin":self.base, "Access-Control-Allow-Methods":"GET,POST,OPTIONS", "Access-Control-Allow-Headers":"token,version,content-type,accept", "Cache-Control":"no-store"} if req.method == "OPTIONS": return route.fulfill(status=204, headers=cors) self.calls.append(key) if req.headers.get("cookie"): return deny("unexpected cookie") if key == ("POST", LOGIN): if req.post_data_json != {"account":ACCOUNT, "password":PASSWORD, "terminal":1}: return deny("unexpected sign-in payload") data = {"token":TOKEN, "is_paw":1, "need_bind_work_wechat":False} elif req.headers.get("token") != TOKEN: return deny("missing fixture token") elif key == ("GET", SELF): data = profile(self.phase) elif key == ("GET", ORDERS) and self.phase == "initial": number = FILTERED if parse_qs(url.query).get("order_no") == [FILTERED] else ROW data = {"lists":[{"id":111, "order_no":number, "order_type":1, "status":2, "amount":"2.00", "is_exempt":0, "creator":{"name":"演示"}, "prescription_orders":[]}], "count":1, "extend":{}} else: return deny("method or permission mismatch") route.fulfill(headers=cors, json={"code":1, "show":0, "msg":"", "data":data}) def exact(label): return re.compile("^" + re.escape(label) + "$") def open_group(parent, name): title = parent.locator(".el-sub-menu__title").filter(has_text=exact(name)) expect(title).to_be_visible() group = title.locator("..") if "is-opened" not in (group.get_attribute("class") or "").split(): title.click() expect(group).to_have_class(re.compile(r"\bis-opened\b")) return group def visit(page, parent, name, base, id_): item = parent.locator(".el-menu-item").filter(has_text=exact(name)) item.click() expect(page).to_have_url(re.compile("^" + re.escape(f"{base}/admin/nav/m-{id_}") + r"(?:\?|$)")) def check(pw, args): base = f"http://127.0.0.1:{args.port}" mock, errors = Offline(base), [] with 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: context = browser.new_context(service_workers="block", viewport={"width":1440,"height":950}) context.route("**/*", mock.route) context.route_web_socket("**/*", lambda socket: (mock.bad.append(("websocket",)), socket.close())) context.on("page", lambda p: p.on("pageerror", lambda error: errors.append(str(error)))) page = context.new_page() page.goto(base + "/admin/login") page.get_by_placeholder("请输入账号").fill(ACCOUNT) page.get_by_placeholder("请输入密码").fill(PASSWORD) assert not mock.calls, mock.calls page.get_by_role("button", name="登录", exact=True).click() menu = page.locator(".menu:visible") refresh = page.locator("[data-refresh-online-menu]:visible") roots = menu.locator(".el-menu").first expect(roots.locator(":scope > .el-sub-menu > .el-sub-menu__title")).to_have_text(["收费事务","门诊事务"]) finance = open_group(menu, "收费事务") settlement = open_group(finance, "对账事务") expect(finance.locator(".el-sub-menu__title, .el-menu-item")).to_have_text( ["收费事务","对账事务","处方收款明细","业务台账","阶段汇总"]) visit(page, settlement, "处方收款明细", base, 72) table = page.locator("main .el-table") expect(table.get_by_text(ROW, exact=True)).to_be_visible() page.get_by_placeholder("请输入订单号").fill(FILTERED) page.get_by_role("button", name="查询", exact=True).click() expect(table.get_by_text(FILTERED, exact=True)).to_be_visible() expect(table.get_by_text(ROW, exact=True)).to_have_count(0) page.screenshot(path=str(args.out/"menu-orders.png")) calls = list(mock.calls) visit(page, settlement, "业务台账", base, 35) main = page.locator("main") expect(main.get_by_text("业务台账", exact=True)).to_be_visible() expect(main).to_contain_text("正式后台") clinic = open_group(menu, "门诊事务") expect(clinic.locator(".el-menu-item")).to_have_text(["业务台账","就诊人资料"]) visit(page, clinic, "就诊人资料", base, 40) expect(main).to_contain_text("正式后台") expect(main.locator(".el-table")).to_have_count(0) visit(page, clinic, "业务台账", base, 31) expect(main.get_by_text("业务台账", exact=True)).to_be_visible() expect(main).to_contain_text("正式后台") page.wait_for_load_state("networkidle") assert mock.calls == calls and not mock.documents, (mock.calls, mock.documents) page.screenshot(path=str(args.out/"menu-official-only.png")) # Revoke while the real local table is mounted: old rows and navigation must disappear. settlement = open_group(open_group(menu, "收费事务"), "对账事务") visit(page, settlement, "处方收款明细", base, 72) expect(table).to_be_visible() page.wait_for_load_state("networkidle") before = list(mock.calls) mock.phase = "empty" refresh.click() expect(menu.locator(".el-menu-item, .el-sub-menu__title")).to_have_count(0) expect(main.locator(".el-table")).to_have_count(0) expect(main).not_to_contain_text("OFFLINE-") page.wait_for_load_state("networkidle") assert mock.calls[len(before):] == [("GET", SELF)], mock.calls page.screenshot(path=str(args.out/"menu-empty.png")) # Same session receives a new, unadapted-only tree; never silently open the official site. mock.phase = "clinic" refresh.click() clinic = open_group(menu, "门诊事务") visit(page, clinic, "业务台账", base, 31) expect(menu.locator(".el-sub-menu__title")).to_have_text(["门诊事务"]) expect(main).to_contain_text("正式后台") page.wait_for_load_state("networkidle") assert mock.calls[len(before):] == [("GET", SELF), ("GET", SELF)] and not mock.documents link = main.get_by_role("link", name=re.compile("正式后台")).or_( main.get_by_role("button", name=re.compile("正式后台"))) expect(link).to_be_visible() mock.explicit = True with context.expect_event("requestfinished", predicate=lambda r: urlsplit(r.url).netloc == HOST and r.resource_type == "document"): link.click() assert mock.documents == ["/admin/clinic/ledger"], mock.documents assert mock.calls[len(before):] == [("GET", SELF), ("GET", SELF)] and not mock.bad and not errors, ( mock.calls, mock.bad, errors) return {"offline_menu_contract":"PASS", "intercepted_api_calls":mock.calls, "intercepted_official_navigation":mock.documents, "unexpected":mock.bad, "page_errors":errors} if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--out", type=Path, required=True) parser.add_argument("--port", type=int, default=5179) args = parser.parse_args() args.out.mkdir(parents=True, exist_ok=True) with sync_playwright() as pw: print(json.dumps(check(pw, args), ensure_ascii=False))