"""Offline Playwright Chromium verification for Vue 3 Ch05 (dumate-dev-vue)."""
import json
import re
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")
def case_vue_qrcode_app_ui_chromium(page):
html = """<!doctype html><html><head><meta charset="utf-8"><title>在线二维码生成器</title></head><body>
<div id="app">
<div id="modes">
<button data-mode="text" class="active">文本</button>
<button data-mode="url">网址</button>
<button data-mode="wifi">WiFi</button>
</div>
<textarea id="qr-input">https://vuejs.org</textarea>
<input id="margin-input" type="number" value="4" />
<p id="margin-warn"></p>
<svg id="qr-preview" width="120" height="120" viewBox="0 0 21 21"></svg>
<span id="status-badge"></span>
</div>
<script>
const listeners = new Set();
const state = new Proxy({ mode: "text", content: "https://vuejs.org", margin: 4 }, {
set(t, k, v) { t[k] = v; listeners.forEach((f) => f()); return true; }
});
function buildMatrixSvg(text) {
let rects = "";
let hash = 0;
for (let i = 0; i < text.length; i++) hash = (hash * 31 + text.charCodeAt(i)) >>> 0;
for (let r = 0; r < 5; r++) {
for (let c = 0; c < 5; c++) {
if (((hash >> ((r * 5 + c) % 24)) & 1) || (r === 0 && c === 0)) {
rects += `<rect x="${c + 2}" y="${r + 2}" width="1" height="1" fill="#111"/>`;
}
}
}
return rects;
}
function render() {
const warn = document.getElementById("margin-warn");
warn.textContent = state.margin < 2 ? "静区边距小于2模块,可能识别失败" : "";
const svg = document.getElementById("qr-preview");
svg.innerHTML = buildMatrixSvg(`${state.mode}:${state.content}`);
document.getElementById("status-badge").textContent = `${state.mode}|m=${state.margin}|rects=${svg.querySelectorAll("rect").length}`;
}
listeners.add(render);
document.querySelectorAll("#modes button").forEach((btn) => {
btn.addEventListener("click", () => { state.mode = btn.dataset.mode; });
});
document.getElementById("qr-input").addEventListener("input", (e) => { state.content = e.target.value; });
document.getElementById("margin-input").addEventListener("input", (e) => { state.margin = Number(e.target.value); });
render();
</script></body></html>"""
page.set_content(html)
initial_badge = page.locator("#status-badge").inner_text()
initial_warn = page.locator("#margin-warn").inner_text()
page.click('button[data-mode="wifi"]')
page.fill("#margin-input", "1")
after_badge = page.locator("#status-badge").inner_text()
after_warn = page.locator("#margin-warn").inner_text()
actual = {
"initial_mode_ok": initial_badge.startswith("text|m=4|rects="),
"initial_warn_empty": initial_warn == "",
"switched_to_wifi": after_badge.startswith("wifi|m=1|rects="),
"low_margin_warn": after_warn,
"svg_has_rects": page.locator("#qr-preview rect").count() > 0,
}
expected = {
"initial_mode_ok": True,
"initial_warn_empty": True,
"switched_to_wifi": True,
"low_margin_warn": "静区边距小于2模块,可能识别失败",
"svg_has_rects": True,
}
return dict(name="vue_qrcode_app_ui_chromium", expected=expected, actual=actual, passed=(actual == expected))
def case_ai_generated_project_audit():
index_html = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8" /><title>在线二维码生成器</title></head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>"""
pkg = {
"name": "vue-qrcode-tool",
"private": True,
"type": "module",
"scripts": {"dev": "vite", "build": "vite build"},
"dependencies": {"vue": "^3.5.0"},
"devDependencies": {"vite": "^6.0.0", "@vitejs/plugin-vue": "^5.0.0"},
}
has_mount_div = '<div id="app"></div>' in index_html
has_module_entry = bool(re.search(r'<script\s+type="module"\s+src="/src/main\.js">', index_html))
actual = {
"project_name": pkg["name"],
"has_mount_div": has_mount_div,
"has_module_entry": has_module_entry,
"scripts": sorted(pkg["scripts"].keys()),
"default_dev_url": "http://localhost:5173/",
}
expected = {
"project_name": "vue-qrcode-tool",
"has_mount_div": True,
"has_module_entry": True,
"scripts": ["build", "dev"],
"default_dev_url": "http://localhost:5173/",
}
return dict(name="ai_generated_project_audit", expected=expected, actual=actual, passed=(actual == expected))
def case_qrcode_payload_encoders(page):
html = """<!doctype html><html><head><meta charset="utf-8"></head><body>
<script>
function encodePayload(kind, data) {
if (kind === "wifi") return `WIFI:T:${data.auth};S:${data.ssid};P:${data.pass};;`;
if (kind === "url") return data.href.startsWith("http") ? data.href : `https://${data.href}`;
return String(data.text || "");
}
function validateQuietZone(margin) {
return { valid: margin >= 2, warning: margin < 2 };
}
window.__out = {
wifi: encodePayload("wifi", { auth: "WPA", ssid: "StudioNet", pass: "pass1234" }),
url: encodePayload("url", { href: "cn.vuejs.org" }),
margin0: validateQuietZone(0),
margin4: validateQuietZone(4)
};
</script></body></html>"""
page.set_content(html)
actual = page.evaluate("window.__out")
expected = {
"wifi": "WIFI:T:WPA;S:StudioNet;P:pass1234;;",
"url": "https://cn.vuejs.org",
"margin0": {"valid": False, "warning": True},
"margin4": {"valid": True, "warning": False},
}
return dict(name="qrcode_payload_encoders", expected=expected, actual=actual, passed=(actual == expected))
def case_deliverable_verification_checklist():
files = [
"index.html",
"package.json",
"vite.config.js",
"README.md",
"src/main.js",
"src/App.vue",
]
required = {"index.html", "package.json", "vite.config.js", "src/main.js", "src/App.vue"}
missing = sorted(required - set(files))
platforms = {"macOS": "M 系列芯片", "Windows": "x86 架构"}
actual = {
"missing_required": missing,
"total_files": len(files),
"supported_platforms": sorted(platforms.keys()),
}
expected = {
"missing_required": [],
"total_files": 6,
"supported_platforms": ["Windows", "macOS"],
}
return dict(name="deliverable_verification_checklist", expected=expected, actual=actual, passed=(actual == expected))
def main():
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page()
cases = [
case_vue_qrcode_app_ui_chromium(page),
case_ai_generated_project_audit(),
case_qrcode_payload_encoders(page),
case_deliverable_verification_checklist(),
]
finally:
browser.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/vue3-dumate-dev-vue-lab/explore-dumate-dev-vue.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-dumate-dev-vue.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a801.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a820.zip