196 lines
10 KiB
Python
196 lines
10 KiB
Python
"""Cold startup, slow navigation, tab lifetime, recovery and reduced motion. Offline only."""
|
|
import argparse
|
|
import json
|
|
import re
|
|
from pathlib import Path
|
|
from urllib.parse import urlsplit
|
|
|
|
from playwright.sync_api import expect, sync_playwright
|
|
|
|
from browser_contract import ACCOUNT, PASS, USER, SELF, OVERVIEW, LOGIN, TOKEN, Fixture, desktop_entry, loopback, menu
|
|
|
|
CHROME_ARGS = ["--disable-background-networking","--disable-quic","--no-proxy-server",
|
|
"--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1"]
|
|
|
|
|
|
def snapshot(page, out, name):
|
|
if out:
|
|
page.screenshot(path=str(out / (name + ".png")), animations="disabled")
|
|
|
|
|
|
def setup(browser, host, *, dark=False, reduce=False):
|
|
fx = Fixture(host, False, False)
|
|
pages = fx.reads[SELF]["menu"][0]["children"][0]["children"]
|
|
pages.append(menu(409, "复核记录", "review", component="stats/self_input/index"))
|
|
for leaf in pages:
|
|
leaf["is_cache"] = 1
|
|
ctx = browser.new_context(service_workers="block", viewport={"width":1400,"height":900},
|
|
color_scheme="dark" if dark else "light", reduced_motion="reduce" if reduce else "no-preference")
|
|
ctx.route("**/*", fx.route)
|
|
ctx.route_web_socket("**/*", lambda ws: (fx.errors.append("unexpected websocket"),ws.close()))
|
|
return ctx,fx,ctx.new_page()
|
|
|
|
|
|
def wait_for_request(page, held):
|
|
for _ in range(150):
|
|
if held: return
|
|
page.wait_for_timeout(25)
|
|
raise AssertionError("expected lazy asset was not requested")
|
|
|
|
|
|
def boot(browser, host, out, reduce, fail=False):
|
|
ctx, fx, page = setup(browser,host,dark=reduce,reduce=reduce)
|
|
held=[]
|
|
# Keep the entry pending to allow the first HTML paint; release only to verified loopback assets.
|
|
def hold(route):
|
|
if (route.request.url.startswith(fx.base+"/admin/assets/") and route.request.resource_type=="script"
|
|
and page.url.startswith(fx.base) and not held):
|
|
held.append(route)
|
|
else: route.fallback()
|
|
page.route("**/assets/**",hold)
|
|
page.goto(fx.base+"/admin/login",wait_until="commit")
|
|
mark=page.locator("#admin-boot")
|
|
expect(mark).to_be_visible()
|
|
expect(mark.get_by_role("status")).to_contain_text("正在打开")
|
|
wait_for_request(page,held)
|
|
page.wait_for_function("() => !!document.querySelector('link[href*=\u0022admin-loading.css\u0022]')?.sheet")
|
|
motion=mark.locator(".boot-mark").evaluate("e => getComputedStyle(e).animationName")
|
|
assert (motion=="none") == reduce,(motion,reduce)
|
|
snapshot(page,out,"boot-dark-reduced" if reduce else "boot-light")
|
|
if fail:
|
|
held[0].abort("failed")
|
|
expect(mark).to_have_attribute("data-state","error",timeout=6500)
|
|
snapshot(page,out,"boot-error")
|
|
page.unroute("**/assets/**",hold)
|
|
mark.get_by_role("link",name="重新加载").click()
|
|
else:
|
|
held[0].continue_()
|
|
expect(mark).to_have_count(0,timeout=15000)
|
|
expect(page.get_by_placeholder("请输入账号")).to_be_visible()
|
|
assert not fx.errors,fx.errors
|
|
ctx.close()
|
|
return {"motion":motion,"manual_recovery":fail}
|
|
|
|
|
|
def journey(browser,host,out):
|
|
ctx,fx,page=setup(browser,host)
|
|
page.goto(fx.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")).to_contain_text(USER)
|
|
stats=page.locator("main .self-input-stats-page");expect(stats.get_by_text("OFFLINE-today",exact=True)).to_be_visible()
|
|
bar=page.locator("#admin-route-progress")
|
|
cost="账户消耗录入"; home="自录转化统计"; other="复核记录"
|
|
tab=lambda name:page.locator(".app-tabs").get_by_role("tab",name=name,exact=True)
|
|
def visit(name):
|
|
desktop_entry(page,name).click()
|
|
expect(tab(name)).to_have_attribute("aria-selected","true")
|
|
def row(period):
|
|
expect(stats.get_by_text("OFFLINE-"+period,exact=True)).to_be_visible()
|
|
# A real lazy import is held. Existing content and controls must not be covered.
|
|
held=[]
|
|
def hold_cost(route):
|
|
if urlsplit(route.request.url).netloc==host and route.request.resource_type=="script" and not held:
|
|
held.append(route)
|
|
else:route.fallback()
|
|
page.route("**/assets/account_cost-*.js",hold_cost)
|
|
desktop_entry(page,cost).click()
|
|
wait_for_request(page,held)
|
|
expect(bar).to_be_visible();expect(bar).to_have_attribute("role","progressbar")
|
|
assert bar.evaluate("e=>getComputedStyle(e).pointerEvents")=="none"
|
|
expect(stats).to_be_visible()
|
|
snapshot(page,out,"route-loading")
|
|
held[0].continue_()
|
|
expect(page.locator("main .personal-account-cost-page")).to_be_visible()
|
|
expect(bar).to_have_count(0);page.unroute("**/assets/account_cost-*.js",hold_cost)
|
|
visit(other);row("today");stats.get_by_text("最近7天",exact=True).click();row("week")
|
|
# Normalize index path by re-entering it from the sidebar.
|
|
visit(home);row("today");stats.get_by_text("最近7天",exact=True).click();row("week")
|
|
reads=lambda:sum(path==OVERVIEW and method=="GET" for method,path in fx.calls)
|
|
before=reads()
|
|
tab(other).locator(".is-icon-close").click();expect(tab(other)).to_have_count(0)
|
|
tab(cost).click();expect(page.locator("main .personal-account-cost-page")).to_be_visible()
|
|
refresh=page.get_by_role("button",name="刷新当前页面")
|
|
refresh.press("Enter");expect(page.locator("main .personal-account-cost-page")).to_be_visible()
|
|
tab(home).click();row("week")
|
|
assert reads()==before,("unrelated tab close or refresh refetched the current filter",before,reads())
|
|
# A closed tab using the same Vue page must start a new instance when reopened.
|
|
visit(other);row("today");assert reads()==before+1
|
|
tab(home).click();row("week")
|
|
page.evaluate("""() => {window.__bars=0;new MutationObserver(rs=>{for(const r of rs)for(const n of r.addedNodes)
|
|
if(n.id==='admin-route-progress')window.__bars++}).observe(document.body,{childList:true})}""")
|
|
tab(other).click();row("today");tab(home).click();row("week")
|
|
page.wait_for_timeout(300)
|
|
assert page.evaluate("window.__bars")==0,"fast cached navigation flashed a loader"
|
|
refresh.press("Enter");row("today")
|
|
assert not fx.errors,fx.errors
|
|
assert [path for method,path in fx.calls if method=="POST"]==[LOGIN]
|
|
ctx.close()
|
|
return {"slow_route_nonblocking":True,"fast_route_bars":0,"unrelated_refetches":0,"closed_tab_reinitialized":True,"manual_refresh_reinitialized":True}
|
|
|
|
|
|
def failed_page(browser,host,out):
|
|
ctx,fx,page=setup(browser,host,dark=True,reduce=True)
|
|
page.goto(fx.base+"/admin/login")
|
|
page.get_by_placeholder("请输入账号").fill(ACCOUNT)
|
|
page.get_by_placeholder("请输入密码").fill(PASS)
|
|
page.get_by_role("button",name="登录",exact=True).click()
|
|
stats=page.locator("main .self-input-stats-page")
|
|
expect(stats.get_by_text("OFFLINE-today",exact=True)).to_be_visible()
|
|
stats.get_by_text("最近7天",exact=True).click()
|
|
expect(stats.get_by_text("OFFLINE-week",exact=True)).to_be_visible()
|
|
original=page.url
|
|
held=[]
|
|
def deny(route):
|
|
if urlsplit(route.request.url).netloc==host and route.request.resource_type=="script":
|
|
held.append(route)
|
|
else:route.fallback()
|
|
page.route("**/assets/account_cost-*.js",deny)
|
|
desktop_entry(page,"账户消耗录入").click()
|
|
wait_for_request(page,held)
|
|
bar=page.get_by_role("progressbar",name="正在打开页面")
|
|
expect(bar).to_be_visible()
|
|
assert bar.evaluate("e=>getComputedStyle(e).animationName")=="none"
|
|
held[0].abort("failed")
|
|
notice=page.get_by_role("complementary",name="页面加载提示")
|
|
expect(notice.get_by_text("页面未能打开",exact=True)).to_be_visible()
|
|
expect(bar).to_have_count(0)
|
|
expect(stats.get_by_text("OFFLINE-week",exact=True)).to_be_visible()
|
|
assert page.url==original
|
|
snapshot(page,out,"page-error")
|
|
notice.get_by_role("button",name="关闭提示").press("Enter")
|
|
expect(notice).to_have_count(0)
|
|
desktop_entry(page,"复核记录").click()
|
|
expect(page.locator(".app-tabs").get_by_role("tab",name="复核记录")).to_have_attribute("aria-selected","true")
|
|
assert not fx.errors,fx.errors
|
|
ctx.close()
|
|
return {"old_filter_retained":True,"reduced_progress_static":True,"can_continue_without_reload":True}
|
|
|
|
|
|
def protected_startup(browser,host):
|
|
found=[]
|
|
for mode,target in [("signed_out","login"),("no_menu","403"),("initial_password","change-password"),("binding","bind-work-wechat")]:
|
|
ctx,fx,page=setup(browser,host)
|
|
if mode!="signed_out":
|
|
ctx.add_init_script("if (location.origin==="+json.dumps(fx.base)+")localStorage.setItem('like_admin_token',"+json.dumps(json.dumps({"value":TOKEN,"expire":""}))+")")
|
|
if mode=="no_menu": fx.reads[SELF]["menu"]=[]
|
|
if mode=="initial_password": fx.reads[SELF]["user"]["is_paw"]=0
|
|
if mode=="binding": fx.reads[SELF]["user"]["need_bind_work_wechat"]=True
|
|
page.goto(fx.base+"/admin/stats/self_input")
|
|
expect(page).to_have_url(re.compile("/admin/"+target+r"(?:\?|$)"),timeout=15000)
|
|
expect(page.locator("#admin-boot")).to_have_count(0)
|
|
expect(page.locator("main .self-input-stats-page")).to_have_count(0)
|
|
assert not fx.errors and not [p for m,p in fx.calls if m=="POST" or p==OVERVIEW],fx.errors
|
|
found.append(target);ctx.close()
|
|
return found
|
|
|
|
|
|
if __name__=="__main__":
|
|
ap=argparse.ArgumentParser(description=__doc__);ap.add_argument("--host",type=loopback,default="127.0.0.1:5179")
|
|
ap.add_argument("--chrome",required=True);ap.add_argument("--out",type=Path)
|
|
a=ap.parse_args()
|
|
if a.out: a.out.mkdir(parents=True,exist_ok=True)
|
|
with sync_playwright() as pw,pw.chromium.launch(executable_path=a.chrome,headless=True,args=CHROME_ARGS) as browser:
|
|
report={"light":boot(browser,a.host,a.out,False),"dark_reduced":boot(browser,a.host,a.out,True,True),
|
|
"journey":journey(browser,a.host,a.out),"asset_failure":failed_page(browser,a.host,a.out),"startup_guards":protected_startup(browser,a.host),"real_api_calls":0,"status":"PASS"}
|
|
print(json.dumps(report,ensure_ascii=False))
|