蓝色天空网mbsky.com · 知识 · 实践 · 创造Playwright · 本地阅读预览
教程 / AI / 智能开发 / Playwright

Playwright CI/CD 集成

核对 GitHub Actions、Jenkins、GitLab CI 与官方 Docker 镜像的 Playwright 流水线集成,以及无头配置、JUnit/HTML 报告与失败产物归档的离线实测。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

GitHub Actions 流水线与 CI 测试结果查看

使用 `npm init playwright@latest` 初始化项目时可自动生成 `.github/workflows/playwright.yml`,核心步骤依次为:检出代码、安装 Node.js、`npm ci` 锁定安装依赖、`npx playwright install --with-deps` 安装浏览器及 Linux 系统依赖、运行 `npx playwright test`,以及借助 `if: always()` 上传 `playwright-report/` 产物确保失败时同样留档。本站实测 CI 配置解析逻辑在 `CI=true` 下自动切换 `workers=1`、`retries=2`、报告器 `['html', 'junit']`,并在无头 Chromium 核验通过。

在 CI 平台运行后,可通过运行日志分 Worker 定位失败用例,或从构建产物(Artifacts)下载 `playwright-report/` 在本地打开交互式 HTML 报告,也可将其发布到静态站点或 GitHub Pages 供团队在线查阅。本站离线实测执行 2 条真实 Chromium 用例并同步生成符合规范的 `test-results/junit.xml`(`tests=2, failures=0`)与 `playwright-report/index.html`;同时制造可控断言失败,验证在异常分支依然成功落盘 `640×480` 失败截图 PNG 与有效 Trace ZIP。

Jenkins、GitLab CI 与官方 Docker 镜像集成

除 GitHub Actions 外,其他主流 CI 平台同样易于接入:Jenkins 声明式 Pipeline 可分 `Install` 与 `Test` 阶段执行并在 `post { always }` 中同时归档 `playwright-report/**` 与 `test-results/junit.xml`;GitLab CI 则可直接声明微软官方镜像 `mcr.microsoft.com/playwright:v1.52.0-jammy`,配合 `artifacts.when: always` 保留 30 天测试报告。

官方 Docker 镜像已预装 Chromium/Firefox/WebKit 及其底层 Linux 共享库,既可用 `docker run --rm -v $(pwd):/work -w /work ...` 临时运行,也可在 `Dockerfile` 中基于锁定标签构建标准化测试镜像(需确保镜像版本与 `package.json` 中的 `@playwright/test` 版本严格一致)。本站实测静态契约校验核验了镜像版本标签 `v1.52.0-jammy`、`npm ci`、`--with-deps` 及 `if: always()` 产物留存规则。

CI 环境运行 Playwright 最佳实践

实践说明
使用 --with-deps在 Linux CI 节点执行 npx playwright install --with-deps 一并安装缺失系统共享库
锁定 Playwright 版本在 package.json / lockfile 与 Docker 镜像标签中锁定一致版本,防止 CI 意外升级破坏兼容
缓存浏览器按版本号缓存 ms-playwright 浏览器目录,减少重复下载耗时(需与版本锁配合)
控制 workers 数量使用 workers: process.env.CI ? 1 : undefined 按 CI 容器 CPU/内存合理限制并发
设置超时CI 虚拟化资源通常弱于开发机,适当放宽 timeout 并开启适量 retries
保留测试产物通过 if: always() / when: always 上传 Trace、失败截图、视频与 HTML/JUnit 报告

运行 CI 无头配置解析、JUnit XML/HTML 报告生成、失败截图与 Trace 留档及流水线契约校验

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 核对 CI 模式 workers=1/retries=2、JUnit XML tests=2/failures=0 与 HTML 报告产物、可控失败仍产出 640x480 PNG 与有效 Trace ZIP,以及 Docker 标签锁定规则。
运行 CI 无头配置解析、JUnit XML/HTML 报告生成、失败截图与 Trace 留档及流水线契约校验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:0a29bf510caa95d4a8147e40063709aa12d11c6adae2fd76f9950e7201152524

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Playwright CI/CD 集成实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:4d89aec14cd9ec0e6c3b23c33558d622d61c00edeb1df1571b24f1c2fca66882

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在 CI 流水线中为何要将上传 playwright-report 的条件设为 if: always(),且使用官方 Docker 镜像时为何必须锁定与 package.json 一致的版本?

展开参考解答

测试失败时默认会中断后续步骤,设置 if: always() 才能保证失败截图、Trace 与报告被归档供排查;Playwright 客户端与预装浏览器二进制按版本绑定,镜像与依赖版本不一致会导致找不到对应浏览器可执行文件。

规范与官方依据