236 lines
13 KiB
Python
236 lines
13 KiB
Python
"""Native admin browser contract. Only loopback static assets leave the test interceptor."""
|
|
import argparse
|
|
import json
|
|
import re
|
|
from pathlib import Path
|
|
from urllib.parse import parse_qs, quote, urlsplit
|
|
|
|
from playwright.sync_api import expect, sync_playwright
|
|
|
|
|
|
OFFICIAL = "https://admin.zhenyangtang.com.cn"
|
|
WX, IAM = "/login/workWechatConfig", "/iam/config"
|
|
OVERVIEW, COST = "/stats.self_input/overview", "/stats.personal_account_cost/lists"
|
|
LOGIN, SELF, CONFIG = "/login/account", "/auth.admin/mySelf", "/config/getConfig"
|
|
ACCOUNT, PASS, TOKEN, USER = "offline-native", "offline-only-password", "fixture-session", "离线验收员"
|
|
PROJECTIONS = ["正式数据 · 只读", "刷新线上菜单", "退出预览", "切回旧版"]
|
|
BRAND = "data:image/svg+xml," + quote('<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><circle cx="8" cy="8" r="6" fill="green"/></svg>')
|
|
|
|
|
|
def loopback(value):
|
|
if not re.fullmatch(r"127\.0\.0\.1:[1-9]\d{0,4}", value) or int(value.split(":")[1]) > 65535:
|
|
raise argparse.ArgumentTypeError("expected 127.0.0.1:PORT")
|
|
return value
|
|
|
|
|
|
def menu(id_, name, path, *, children=None, component="", perm=""):
|
|
item = dict(id=id_, type="M" if children else "C", name=name, paths=path, component=component,
|
|
perms=perm, params="", icon="", selected="", is_show=1, is_disable=0, is_cache=0)
|
|
if children:
|
|
item["children"] = children
|
|
return item
|
|
|
|
|
|
def profile():
|
|
# The empty path is intentional: it is the index child in add_self_input_stats_menu.sql.
|
|
overview = menu(303, "自录转化统计", "", component="stats/self_input/index", perm=OVERVIEW[1:])
|
|
cost = menu(304, "账户消耗录入", "/account_cost?via=sidebar",
|
|
component="stats/self_input/account_cost", perm=COST[1:])
|
|
return {"user": {"id": 931, "name": USER, "is_paw": 1, "root": 0, "need_bind_work_wechat": False},
|
|
"permissions": [OVERVIEW[1:], COST[1:], "stats.personal_account_cost/add"],
|
|
"menu": [menu(301, "数据统计", "/stats", children=[
|
|
menu(302, "自录数据统计", "self_input", children=[overview, cost])])]}
|
|
|
|
|
|
class Fixture:
|
|
def __init__(self, host, wx, iam):
|
|
self.host, self.base = host, f"http://{host}"
|
|
self.public = {CONFIG: {"web_name": "后台登录", "version": "fixture", "login_image": BRAND,
|
|
"web_logo": BRAND, "copyright_config": []},
|
|
WX: {"enabled": wx, "corp_id": "offline-corp" if wx else "", "agent_id": "11" if wx else ""},
|
|
IAM: {"enabled": iam, "loginUrl": OFFICIAL + "/adminapi/iam/start" if iam else ""}}
|
|
self.reads = {SELF: profile(), "/chat/notifications": [], "/tcm.revisitDue/pending": {"items": [], "summary": {}},
|
|
"/tcm.prescription/esignConfig": {"enabled": False}, "/dept.dept/all": [],
|
|
"/stats.self_input/mediaSourceOptions": [], COST: {"lists": [], "count": 0, "extend": {}}}
|
|
self.calls, self.errors = [], []
|
|
self.allowed_handoff, self.documents = set(), []
|
|
|
|
def route(self, route):
|
|
req, url = route.request, urlsplit(route.request.url)
|
|
|
|
def deny(reason):
|
|
# Never print headers, credentials or the query string.
|
|
self.errors.append([reason, req.method, url.path])
|
|
route.abort()
|
|
|
|
if (url.scheme, url.netloc) == ("http", self.host):
|
|
if req.method == "GET" and (url.path.startswith("/admin/assets/") or
|
|
(req.resource_type == "document" and url.path.startswith("/admin/")) or
|
|
url.path in ("/favicon.ico", "/admin/favicon.ico")):
|
|
return route.continue_()
|
|
return deny("unexpected local request")
|
|
if f"{url.scheme}://{url.netloc}" != OFFICIAL:
|
|
return deny("unexpected origin")
|
|
if req.resource_type == "document":
|
|
if req.method != "GET" or url.path not in self.allowed_handoff or url.query or url.fragment:
|
|
return deny("unexpected navigation")
|
|
self.allowed_handoff.clear()
|
|
self.documents.append(url.path)
|
|
return route.fulfill(content_type="text/html", body="<title>Offline official site</title>")
|
|
if not url.path.startswith("/adminapi/"):
|
|
return deny("unexpected official resource")
|
|
path = url.path.removeprefix("/adminapi")
|
|
cors = {"Access-Control-Allow-Origin": self.base, "Access-Control-Allow-Methods": "GET,POST,OPTIONS",
|
|
"Access-Control-Allow-Headers": "accept,token,version,content-type", "Cache-Control": "no-store"}
|
|
if req.method == "OPTIONS":
|
|
return route.fulfill(status=204, headers=cors)
|
|
self.calls.append([req.method, path])
|
|
if req.method == "POST" and path == LOGIN:
|
|
if req.post_data_json != {"account": ACCOUNT, "password": PASS, "terminal": 1}:
|
|
return deny("unexpected sign-in body")
|
|
data = {"token": TOKEN, "is_paw": 1, "need_bind_work_wechat": False}
|
|
elif req.method != "GET":
|
|
return deny("unexpected mutation")
|
|
elif path in self.public:
|
|
data = self.public[path]
|
|
elif req.headers.get("token") != TOKEN:
|
|
return deny("missing fixture session")
|
|
elif path == OVERVIEW:
|
|
period = parse_qs(url.query).get("time_type", [""])[0]
|
|
if period not in ("today", "week"):
|
|
return deny("unexpected time range")
|
|
data = {"lists": [{"id": 1, "yeji_date": "2026-01-01", "media_source": "OFFLINE-" + period}],
|
|
"count": 1, "extend": {"date_range": ["2026-01-01", "2026-01-07"],
|
|
"summary": {"add_fans_count": 17 if period == "today" else 31}}}
|
|
elif path in self.reads:
|
|
data = self.reads[path]
|
|
else:
|
|
return deny("unknown API")
|
|
return route.fulfill(headers=cors, json={"code": 1, "show": 0, "msg": "", "data": data})
|
|
|
|
|
|
def desktop_entry(page, name, root="数据统计", nested="自录数据统计"):
|
|
"""Use the visible desktop controls; avoid reselecting a root that is already open."""
|
|
rail = page.get_by_role("navigation", name="一级菜单", exact=True)
|
|
panel = page.get_by_role("navigation", name="二级菜单", exact=True)
|
|
group = rail.get_by_role("button", name=root, exact=True)
|
|
if group.get_attribute("aria-expanded") != "true":
|
|
group.click()
|
|
expect(panel).to_be_visible()
|
|
if nested:
|
|
branch = panel.get_by_role("button", name=nested, exact=True)
|
|
if branch.get_attribute("aria-expanded") != "true":
|
|
branch.click()
|
|
return panel.get_by_role("link", name=name, exact=True)
|
|
|
|
|
|
def check_app(page, fixture, out):
|
|
page.get_by_placeholder("请输入账号").fill(ACCOUNT)
|
|
page.get_by_placeholder("请输入密码").fill(PASS)
|
|
page.get_by_role("button", name="登录", exact=True).click()
|
|
member = page.locator(".app-header").get_by_text(USER, exact=True)
|
|
expect(member).to_be_visible(timeout=15000)
|
|
expect(page.locator(".app-header [data-admin-ui-toggle]")).to_have_count(0)
|
|
for label in PROJECTIONS:
|
|
expect(page.locator(".app-header")).not_to_contain_text(label)
|
|
member.hover()
|
|
for label in ("个人设置", "切换账号", "退出登录"):
|
|
expect(page.get_by_text(label, exact=True)).to_be_visible()
|
|
page.mouse.move(1, 1)
|
|
|
|
# First visit the sibling; the empty child below must be selected by click, not just by initial redirect.
|
|
desktop_entry(page, "账户消耗录入").click()
|
|
expect(page.locator("main .personal-account-cost-page")).to_be_visible()
|
|
expect(page.locator("main .personal-account-cost-page").get_by_role("button", name="新增", exact=True)).to_be_visible() # Authorized control is present; never submit any business write.
|
|
assert parse_qs(urlsplit(page.url).query).get("via") == ["sidebar"], page.url
|
|
desktop_entry(page, "自录转化统计").click()
|
|
stats = page.locator("main .self-input-stats-page")
|
|
expect(stats.get_by_text("业绩明细", exact=True)).to_be_visible()
|
|
expect(stats.locator(".el-table").get_by_text("OFFLINE-today", exact=True)).to_be_visible()
|
|
expect(stats.locator(".stats-kpi-card").filter(has_text="加粉数")).to_contain_text("17")
|
|
stats.get_by_text("最近7天", exact=True).click()
|
|
expect(stats.locator(".el-table").get_by_text("OFFLINE-week", exact=True)).to_be_visible()
|
|
expect(stats.locator(".stats-kpi-card").filter(has_text="加粉数")).to_contain_text("31")
|
|
# Native SPA history fallback and dynamic route re-registration must also work on a direct refresh.
|
|
page.reload()
|
|
expect(stats.locator(".el-table").get_by_text("OFFLINE-today", exact=True)).to_be_visible()
|
|
if out:
|
|
page.screenshot(path=str(out / "native-self-input.png"))
|
|
assert ["GET", COST] in fixture.calls and ["GET", OVERVIEW] in fixture.calls
|
|
assert [p for m, p in fixture.calls if m == "POST"] == [LOGIN]
|
|
|
|
|
|
def scenario(browser, args, wx, iam):
|
|
fixture = Fixture(args.host, wx, iam)
|
|
with browser.new_context(service_workers="block", viewport={"width": 1460, "height": 950}) as context:
|
|
context.set_default_timeout(8000)
|
|
context.route("**/*", fixture.route)
|
|
context.route_web_socket("**/*", lambda ws: (fixture.errors.append("unexpected WebSocket"), ws.close()))
|
|
context.on("page", lambda p: p.on("pageerror", lambda err: fixture.errors.append(str(err))))
|
|
page = context.new_page()
|
|
try:
|
|
page.goto(fixture.base + "/admin/login", wait_until="networkidle")
|
|
assert {p for _, p in fixture.calls} == {CONFIG, WX, IAM}, fixture.calls
|
|
form = page.locator(".login-card .login-form")
|
|
expect(form.get_by_text("后台登录", exact=True)).to_be_visible()
|
|
brand = page.locator(".login-card img").filter(visible=True)
|
|
expect(brand).to_have_attribute("src", BRAND)
|
|
assert brand.evaluate("img => img.complete && img.naturalWidth > 0")
|
|
expect(form.get_by_placeholder("请输入账号")).to_be_visible()
|
|
expect(form.get_by_placeholder("请输入密码")).to_be_visible()
|
|
expect(form.get_by_role("button", name="登录", exact=True)).to_be_visible()
|
|
wx_tab = form.get_by_text("企业微信", exact=True)
|
|
iam_entry = form.get_by_role("button", name="统一账号快捷登录")
|
|
if wx:
|
|
expect(wx_tab).to_be_visible()
|
|
expect(form.get_by_text("账号登录", exact=True)).to_be_visible()
|
|
wx_tab.click()
|
|
scan = form.get_by_role("link", name=re.compile("企业微信扫码登录"))
|
|
expect(scan).to_be_visible()
|
|
dest = urlsplit(scan.get_attribute("href"))
|
|
query = parse_qs(dest.query)
|
|
assert (dest.scheme, dest.netloc, dest.path) == ("https", "open.work.weixin.qq.com", "/wwopen/sso/qrConnect")
|
|
assert query.get("redirect_uri") == [OFFICIAL + "/admin/login"]
|
|
assert query.get("appid") == ["offline-corp"] and query.get("agentid") == ["11"]
|
|
assert "noopener" in (scan.get_attribute("rel") or "").split()
|
|
assert not page.locator("iframe").count() and not fixture.documents
|
|
form.get_by_text("账号登录", exact=True).click()
|
|
else:
|
|
expect(wx_tab).to_be_hidden()
|
|
if iam:
|
|
expect(iam_entry).to_be_visible()
|
|
else:
|
|
expect(iam_entry).to_be_hidden()
|
|
if wx and iam:
|
|
if args.out:
|
|
page.screenshot(path=str(args.out / "native-login.png"))
|
|
check_app(page, fixture, args.out)
|
|
elif iam:
|
|
# No real navigation. The interceptor substitutes HTML for the user-initiated GET.
|
|
fixture.allowed_handoff.add("/adminapi/iam/start")
|
|
with context.expect_event("requestfinished", predicate=lambda r:
|
|
r.resource_type == "document" and r.url == OFFICIAL + "/adminapi/iam/start"):
|
|
iam_entry.click()
|
|
assert fixture.documents == ["/adminapi/iam/start"]
|
|
assert not fixture.errors, fixture.errors
|
|
except Exception:
|
|
print("Failed case:", wx, iam, "mocked:", fixture.calls, "errors:", fixture.errors, flush=True)
|
|
raise
|
|
return {"wx": wx, "iam": iam, "mocked": fixture.calls}
|
|
|
|
|
|
if __name__ == "__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 offline screenshots")
|
|
args = parser.parse_args()
|
|
if args.out:
|
|
args.out.mkdir(parents=True, exist_ok=True)
|
|
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:
|
|
results = [scenario(browser, args, wx, iam) for wx in (False, True) for iam in (False, True)]
|
|
print(json.dumps({"native_browser_contract": "PASS", "real_api_calls": 0, "cases": results}, ensure_ascii=False))
|