"""Offline Playwright Chromium lab for Chapter 37 (ci-cd): CI headless config resolution, JUnit XML & HTML report artifacts, always-upload failure screenshot/trace artifacts, and CI workflow/Docker lint."""
import http.server
import json
import os
import re
import struct
import tempfile
import threading
import xml.etree.ElementTree as ET
import zipfile
from pathlib import Path
from playwright.sync_api import sync_playwright, expect
class _Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
pages = {
"/home": "<!doctype html><html><head><meta charset='utf-8'><title>CI 首页</title></head><body><h1>构建门禁首页</h1></body></html>",
"/health": "<!doctype html><html><head><meta charset='utf-8'><title>健康检查</title></head><body><span id='health'>UP</span></body></html>",
"/broken": "<!doctype html><html><head><meta charset='utf-8'><title>故障页</title></head><body><div id='msg'>错误 503</div></body></html>",
}
data = pages.get(self.path, pages["/home"]).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, format, *args):
pass
def launch_browser(p):
exe = p.chromium.executable_path
if exe and os.path.exists(exe):
return p.chromium.launch(headless=True)
for ch in ("chrome", "msedge"):
try:
return p.chromium.launch(channel=ch, headless=True)
except Exception:
continue
return p.chromium.launch(headless=True)
def resolve_ci_config(is_ci: bool):
return {
"headless": True,
"workers": 1 if is_ci else None,
"retries": 2 if is_ci else 0,
"timeout_ms": 60000 if is_ci else 30000,
"reporter": ["html", "junit"] if is_ci else ["list"],
}
def main():
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
port = server.server_address[1]
base_url = f"http://127.0.0.1:{port}"
threading.Thread(target=server.serve_forever, daemon=True).start()
cases = []
try:
with sync_playwright() as p:
browser = launch_browser(p)
# Case 1: CI vs local config resolution + real headless launch check
local_cfg = resolve_ci_config(False)
ci_cfg = resolve_ci_config(True)
ctx_h = browser.new_context()
pg_h = ctx_h.new_page()
pg_h.goto(f"{base_url}/home")
is_headless_ua = pg_h.evaluate("() => navigator.userAgent.includes('Headless') || navigator.webdriver === true")
ctx_h.close()
exp1 = {
"ci_workers": 1,
"ci_retries": 2,
"local_retries": 0,
"ci_reporters": ["html", "junit"],
"headless_verified": True,
}
act1 = {
"ci_workers": ci_cfg["workers"],
"ci_retries": ci_cfg["retries"],
"local_retries": local_cfg["retries"],
"ci_reporters": ci_cfg["reporter"],
"headless_verified": is_headless_ua,
}
cases.append(dict(name="ci_headless_config_resolution", expected=exp1, actual=act1, passed=act1 == exp1))
# Case 2: Real Chromium suite producing JUnit XML + HTML report artifacts
with tempfile.TemporaryDirectory() as tmp:
tp = Path(tmp)
junit_path = tp / "test-results" / "junit.xml"
html_path = tp / "playwright-report" / "index.html"
junit_path.parent.mkdir(parents=True, exist_ok=True)
html_path.parent.mkdir(parents=True, exist_ok=True)
suite_specs = [
("home_heading", "/home", "h1", "构建门禁首页"),
("health_status", "/health", "#health", "UP"),
]
results = []
ctx = browser.new_context()
pg = ctx.new_page()
for name, path, sel, expected_txt in suite_specs:
pg.goto(f"{base_url}{path}")
expect(pg.locator(sel)).to_have_text(expected_txt)
results.append((name, "passed"))
ctx.close()
suite_el = ET.Element("testsuite", name="playwright-ci", tests=str(len(results)), failures="0")
for name, _ in results:
ET.SubElement(suite_el, "testcase", classname="ci.spec", name=name)
ET.ElementTree(suite_el).write(junit_path, encoding="utf-8", xml_declaration=True)
html_rows = "".join(f"<li>{n}: {st}</li>" for n, st in results)
html_path.write_text(f"<!doctype html><html><body><h1>Playwright Report</h1><ul>{html_rows}</ul></body></html>", encoding="utf-8")
parsed = ET.parse(junit_path).getroot()
exp2 = {"junit_tests": 2, "junit_failures": 0, "html_has_both_cases": True}
html_txt = html_path.read_text(encoding="utf-8")
act2 = {
"junit_tests": int(parsed.attrib["tests"]),
"junit_failures": int(parsed.attrib["failures"]),
"html_has_both_cases": ("home_heading" in html_txt and "health_status" in html_txt),
}
cases.append(dict(name="junit_xml_and_html_report_artifacts", expected=exp2, actual=act2, passed=act2 == exp2))
# Case 3: Controlled failure capturing screenshot PNG + Trace ZIP (if: always() artifact preservation)
with tempfile.TemporaryDirectory() as tmp:
tp = Path(tmp)
shot_path = tp / "failure.png"
trace_path = tp / "failure-trace.zip"
ctx_f = browser.new_context(viewport={"width": 640, "height": 480})
ctx_f.tracing.start(screenshots=True, snapshots=True)
pg_f = ctx_f.new_page()
pg_f.goto(f"{base_url}/broken")
failed_caught = False
try:
expect(pg_f.locator("#msg")).to_have_text("正常 200", timeout=200)
except AssertionError:
failed_caught = True
pg_f.screenshot(path=str(shot_path))
finally:
ctx_f.tracing.stop(path=str(trace_path))
ctx_f.close()
raw_png = shot_path.read_bytes()
w, h = struct.unpack(">II", raw_png[16:24])
exp3 = {"failed_caught": True, "png_valid": True, "png_dims": [640, 480], "trace_zip_valid": True}
act3 = {
"failed_caught": failed_caught,
"png_valid": raw_png[:8] == b"\x89PNG\r\n\x1a\n",
"png_dims": [w, h],
"trace_zip_valid": zipfile.is_zipfile(trace_path) and trace_path.stat().st_size > 0,
}
cases.append(dict(name="failure_artifacts_screenshot_and_trace", expected=exp3, actual=act3, passed=act3 == exp3))
# Case 4: CI pipeline & Docker version pinning static contract verification
dockerfile = (
"FROM mcr.microsoft.com/playwright:v1.52.0-jammy\n"
"WORKDIR /app\n"
"COPY package.json package-lock.json ./\n"
"RUN npm ci\n"
"COPY . .\n"
'CMD ["npx", "playwright", "test"]\n'
)
gh_workflow = (
"run: npm ci\n"
"run: npx playwright install --with-deps\n"
"run: npx playwright test\n"
"if: always()\n"
"path: playwright-report/\n"
)
docker_tag = re.search(r"mcr\.microsoft\.com/playwright:(v\d+\.\d+\.\d+-\w+)", dockerfile)
exp4 = {
"docker_pinned_tag": "v1.52.0-jammy",
"uses_npm_ci": True,
"installs_with_deps": True,
"uploads_always": True,
}
act4 = {
"docker_pinned_tag": docker_tag.group(1) if docker_tag else None,
"uses_npm_ci": "npm ci" in dockerfile and "npm ci" in gh_workflow,
"installs_with_deps": "--with-deps" in gh_workflow,
"uploads_always": "if: always()" in gh_workflow and "playwright-report/" in gh_workflow,
}
cases.append(dict(name="ci_pipeline_and_docker_contract", expected=exp4, actual=act4, passed=act4 == exp4))
browser.close()
finally:
server.shutdown()
server.server_close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/playwright-ci-cd-lab/explore-ci-cd.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-ci-cd.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a602.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a605.zip