nomadro/apps/miniprogram/h5/scripts/_h5_smoke.py
eric 3e5b7c2098 Monorepo super-optimize: src layout, workspace scripts, docs.
Collapse portal under src/, unify pnpm workspace/scripts, thin VIP topic re-exports, drop orphan vip scaffolds and one-shot scripts, ignore xhs/release, document root commands.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 00:34:04 +08:00

161 lines
6.4 KiB
Python

"""Taro H5 smoke: routes, console, hub style parity signals."""
from __future__ import annotations
import json
import sys
import time
from pathlib import Path
from playwright.sync_api import sync_playwright
BASE = "http://127.0.0.1:10086"
OUT = Path(__file__).resolve().parents[1] / "tmp" / "h5-smoke"
OUT.mkdir(parents=True, exist_ok=True)
ROUTES = [
("home", "/#/pages/index/index", ["nomadro", "随处工作", "自由生活", "出海导航", "数字游民小册", "旅居社群"]),
("nav", "/#/pages/nav/index", ["导航"]),
("book", "/#/pages/book/index", ["Nomadro"]), # cover brand after offline/API load
("community", "/#/pages/community/index", ["nomadro"]),
("mine", "/#/pages/mine/index", ["我的"]),
("vip", "/#/pages/vip/index", ["会员"]),
]
def main() -> int:
report: dict = {"ok": True, "routes": [], "errors": []}
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
# mobile H5 viewport
context = browser.new_context(
viewport={"width": 390, "height": 844},
device_scale_factor=2,
is_mobile=True,
user_agent=(
"Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) "
"AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 "
"Mobile/15E148 Safari/604.1"
),
)
page = context.new_page()
console_errors: list[str] = []
page_errors: list[str] = []
page.on(
"console",
lambda msg: console_errors.append(f"{msg.type}: {msg.text}")
if msg.type in ("error", "warning")
else None,
)
page.on("pageerror", lambda exc: page_errors.append(str(exc)))
for name, path, texts in ROUTES:
console_errors.clear()
page_errors.clear()
url = BASE + path
entry: dict = {"name": name, "url": url, "ok": True}
try:
page.goto(url, wait_until="networkidle", timeout=60000)
# Taro hash router + API / offline fallback
page.wait_for_timeout(2500)
if name == "book":
page.wait_for_function(
"""() => {
const t = document.body && document.body.innerText || '';
return t.includes('Nomadro') || t.includes('开始阅读') || t.includes('继续阅读') || t.includes('暂时打不开');
}""",
timeout=20000,
)
body = page.inner_text("body")
entry["body_len"] = len(body)
entry["body_preview"] = body[:240].replace("\n", " | ")
missing = [t for t in texts if t not in body]
entry["missing_texts"] = missing
if missing:
entry["ok"] = False
report["ok"] = False
if name == "home":
hub = page.locator(".hub-root").first
entry["has_hub_root"] = hub.count() > 0
if hub.count():
bg = page.evaluate(
"""() => {
const el = document.querySelector('.hub-root');
if (!el) return null;
const cs = getComputedStyle(el);
return {
bg: cs.backgroundColor,
color: cs.color,
fontSize: cs.fontSize,
minHeight: cs.minHeight,
hasPortal: !!document.querySelector('.hub-portal-grid'),
hasGlobe: !!document.querySelector('.hub-globe-container'),
portalCount: document.querySelectorAll('.hub-portal-card').length,
};
}"""
)
entry["hub_style"] = bg
if not bg or not bg.get("hasPortal") or bg.get("portalCount", 0) < 3:
entry["ok"] = False
report["ok"] = False
else:
entry["ok"] = False
report["ok"] = False
shot = OUT / f"{name}.png"
page.screenshot(path=str(shot), full_page=True)
entry["screenshot"] = str(shot)
# hard JS errors fail the route
hard = [e for e in page_errors if e]
# filter noisy webpack HMR / overlay noise
hard_console = [
e
for e in console_errors
if e.startswith("error:")
and "Download the React DevTools" not in e
and "favicon" not in e.lower()
]
entry["page_errors"] = hard
entry["console_errors"] = hard_console[:20]
if hard:
entry["ok"] = False
report["ok"] = False
except Exception as exc: # noqa: BLE001
entry["ok"] = False
entry["exception"] = str(exc)
report["ok"] = False
report["routes"].append(entry)
print(json.dumps(entry, ensure_ascii=True))
# Desktop viewport home check
page.set_viewport_size({"width": 1280, "height": 800})
page.goto(BASE + "/#/pages/index/index", wait_until="networkidle", timeout=60000)
page.wait_for_timeout(1500)
desk = page.evaluate(
"""() => {
const grid = document.querySelector('.hub-hero-inner');
if (!grid) return null;
const cs = getComputedStyle(grid);
return {
display: cs.display,
columns: cs.gridTemplateColumns,
areas: cs.gridTemplateAreas,
};
}"""
)
report["desktop_home_grid"] = desk
page.screenshot(path=str(OUT / "home-desktop.png"), full_page=True)
browser.close()
out_json = OUT / "report.json"
out_json.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
print("REPORT", out_json, "ok=", report["ok"])
return 0 if report["ok"] else 1
if __name__ == "__main__":
sys.exit(main())