"""Offline Playwright Chromium verification for React Ch25 (router)."""
import http.server
import json
import threading
from playwright.sync_api import sync_playwright
def launch_browser(p):
for kwargs in (
dict(headless=True),
dict(headless=True, channel="chrome"),
dict(headless=True, channel="msedge"),
):
try:
return p.chromium.launch(**kwargs)
except Exception:
continue
raise RuntimeError("No Chromium/Chrome/Edge browser executable available")
SPA_HTML = """<!doctype html>
<html><head><meta charset="utf-8"><title>React Router Lab</title></head>
<body>
<nav id="top-nav">
<a href="/" data-link="/">Home</a>
<a href="/about" data-link="/about">About</a>
<a href="/contact" data-link="/contact">Contact</a>
<a href="/dashboard" data-link="/dashboard">Dashboard</a>
<a href="/user/1" data-link="/user/1">User 1</a>
<a href="/user/42" data-link="/user/42">User 42</a>
</nav>
<main id="outlet-root"></main>
<script>
window.__bootCount = (window.__bootCount || 0) + 1;
window.__fallbackMode = 'notfound'; // 'notfound' or 'redirect'
function navigate(to, opts = {}) {
if (opts.replace) {
window.history.replaceState({}, '', to);
} else {
window.history.pushState({}, '', to);
}
renderRoute();
}
window.__navigate = navigate;
function renderRoute() {
const path = window.location.pathname;
const root = document.getElementById('outlet-root');
if (path === '/') {
root.innerHTML = '<h2>Home</h2>';
return;
}
if (path === '/about') {
root.innerHTML = '<h2>About</h2>';
return;
}
if (path === '/contact') {
root.innerHTML = '<h2>Contact</h2>';
return;
}
if (path === '/dashboard' || path.startsWith('/dashboard/')) {
const sub = path.slice('/dashboard'.length);
let childHtml = '';
if (sub === '/profile') childHtml = '<h3 id="nested-view">Profile</h3>';
else if (sub === '/settings') childHtml = '<h3 id="nested-view">Settings</h3>';
root.innerHTML = `
<section id="dashboard-layout">
<h2>Dashboard</h2>
<a id="link-profile" href="/dashboard/profile" data-link="/dashboard/profile">Profile</a>
<a id="link-settings" href="/dashboard/settings" data-link="/dashboard/settings">Settings</a>
<div id="dashboard-outlet">${childHtml}</div>
</section>`;
return;
}
const userMatch = path.match(/^\\/user\\/([^/]+)$/);
if (userMatch) {
const userId = decodeURIComponent(userMatch[1]);
root.innerHTML = `<h2 id="user-view">User ID: ${userId}</h2>`;
return;
}
if (window.__fallbackMode === 'redirect') {
navigate('/', { replace: true });
return;
}
root.innerHTML = '<h2 id="notfound-view">404 Page Not Found</h2>';
}
document.addEventListener('click', (e) => {
const a = e.target.closest('a[data-link]');
if (!a) return;
e.preventDefault();
navigate(a.getAttribute('data-link'));
});
window.addEventListener('popstate', renderRoute);
renderRoute();
</script>
</body></html>"""
class SpaHandler(http.server.BaseHTTPRequestHandler):
def log_message(self, format, *args):
return
def do_GET(self):
body = SPA_HTML.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def case_basic_routes_and_link_navigation(page, base_url):
page.goto(base_url + "/")
home_h2 = page.text_content("#outlet-root h2")
page.click('a[data-link="/about"]')
about_h2 = page.text_content("#outlet-root h2")
about_path = page.evaluate("window.location.pathname")
page.click('a[data-link="/contact"]')
contact_h2 = page.text_content("#outlet-root h2")
page.go_back()
page.wait_for_function("window.location.pathname === '/about'")
back_h2 = page.text_content("#outlet-root h2")
boot_count = page.evaluate("window.__bootCount")
actual = {
"home": home_h2,
"about": about_h2,
"aboutPath": about_path,
"contact": contact_h2,
"afterBack": back_h2,
"bootCount": boot_count,
}
expected = {
"home": "Home",
"about": "About",
"aboutPath": "/about",
"contact": "Contact",
"afterBack": "About",
"bootCount": 1,
}
return dict(name="basic_routes_and_link_navigation", expected=expected, actual=actual, passed=(actual == expected))
def case_nested_routes_and_outlet(page, base_url):
page.goto(base_url + "/")
page.click('a[data-link="/dashboard"]')
base_heading = page.text_content("#dashboard-layout h2")
empty_outlet = page.text_content("#dashboard-outlet").strip()
page.click("#link-profile")
profile_path = page.evaluate("window.location.pathname")
profile_text = page.text_content("#nested-view")
page.click("#link-settings")
settings_path = page.evaluate("window.location.pathname")
settings_text = page.text_content("#nested-view")
parent_still_present = page.evaluate("Boolean(document.getElementById('dashboard-layout'))")
actual = {
"baseHeading": base_heading,
"emptyOutlet": empty_outlet,
"profilePath": profile_path,
"profileText": profile_text,
"settingsPath": settings_path,
"settingsText": settings_text,
"parentStillPresent": parent_still_present,
}
expected = {
"baseHeading": "Dashboard",
"emptyOutlet": "",
"profilePath": "/dashboard/profile",
"profileText": "Profile",
"settingsPath": "/dashboard/settings",
"settingsText": "Settings",
"parentStillPresent": True,
}
return dict(name="nested_routes_and_outlet", expected=expected, actual=actual, passed=(actual == expected))
def case_dynamic_route_useparams(page, base_url):
page.goto(base_url + "/")
page.click('a[data-link="/user/1"]')
u1 = page.text_content("#user-view")
page.click('a[data-link="/user/42"]')
u42 = page.text_content("#user-view")
u42_path = page.evaluate("window.location.pathname")
actual = {"user1": u1, "user42": u42, "user42Path": u42_path}
expected = {"user1": "User ID: 1", "user42": "User ID: 42", "user42Path": "/user/42"}
return dict(name="dynamic_route_useparams", expected=expected, actual=actual, passed=(actual == expected))
def case_wildcard_404_and_navigate_replace(page, base_url):
page.goto(base_url + "/")
page.evaluate("window.__fallbackMode = 'notfound'; window.__navigate('/missing/page');")
nf_text = page.text_content("#notfound-view")
nf_path = page.evaluate("window.location.pathname")
hist_before = page.evaluate("window.history.length")
page.evaluate("window.__fallbackMode = 'redirect'; window.__navigate('/bad/path', { replace: true });")
redir_path = page.evaluate("window.location.pathname")
redir_h2 = page.text_content("#outlet-root h2")
hist_after = page.evaluate("window.history.length")
actual = {
"notFoundText": nf_text,
"notFoundPath": nf_path,
"redirectPath": redir_path,
"redirectHeading": redir_h2,
"historyLengthUnchanged": hist_after == hist_before,
}
expected = {
"notFoundText": "404 Page Not Found",
"notFoundPath": "/missing/page",
"redirectPath": "/",
"redirectHeading": "Home",
"historyLengthUnchanged": True,
}
return dict(name="wildcard_404_and_navigate_replace", expected=expected, actual=actual, passed=(actual == expected))
def main():
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), SpaHandler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
base_url = f"http://127.0.0.1:{port}"
try:
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page()
cases = [
case_basic_routes_and_link_navigation(page, base_url),
case_nested_routes_and_outlet(page, base_url),
case_dynamic_route_useparams(page, base_url),
case_wildcard_404_and_navigate_replace(page, base_url),
]
finally:
browser.close()
finally:
server.shutdown()
server.server_close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/react-router-lab/explore-router.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-router.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3187.zip
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip