Playwright 运行测试
核对 Playwright CLI 测试执行命令、按路径/关键词/正则/Tag 筛选、浏览器与有头模式控制、并行重复分片及 Trace/快照控制参数。
学完这一章,你能够
- 核对 Playwright CLI 测试执行命令、按路径/关键词/正则/Tag 筛选、浏览器与有头模式控制、并行重复分片及 Trace/快照控制参数。
基本运行与多维测试筛选
Playwright 测试运行器通过 `npx playwright test` 执行全部用例(也可映射到 `package.json` 的 `npm test` 脚本),并支持丰富的命令行参数以精准控制运行范围与调试行为。
筛选特定测试有四类常用方式:按文件路径或目录运行(支持空格分隔多个文件);按文件名关键词模糊匹配(如 `npx playwright test login user`);按测试标题正则筛选(`-g` / `--grep` 支持如 `"登录|注册"`);以及在测试标题中添加 `@smoke`、`@slow` 等标签,配合 `--grep "@smoke"` 仅运行冒烟集或 `--grep-invert "@slow"` 排除慢速用例。本站离线对 8 条示例规格验证四类筛选逻辑:精确路径命中 1 条、关键词 `login`/`user` 命中 3 条、正则 `登录|注册` 命中 3 条、`@smoke` 命中 3 条且全部在无头 Chromium 中执行通过,排除 `@slow` 保留 6 条。
浏览器控制与交互执行模式
命令行可随时覆盖目标浏览器与窗口模式:`--project=chromium` 限定运行单个或多个项目;`--headed` 关闭默认无头模式以直观观察浏览器窗口操作;`--channel=chrome` 则直接调用本机安装的稳定版 Chrome 渠道(本站离线环境即通过本机 Chrome 渠道驱动真实 Chromium 内核)。
排查问题时可切换两种交互模式:`--ui` 启动带时间轴与实时监听的图形化 UI Mode;`--debug` 以单步调试模式启动并自动弹出 Playwright Inspector 窗口。
并行、重复、分片与 Trace/快照控制
针对大规模套件与稳定性排查,Playwright 提供三组执行调度参数:`--workers=4` 或 `--workers=1` 控制并行进程数;`--repeat-each=3` 将每条用例连续跑多遍以暴露偶发脆弱性(本站实测独立上下文重复执行 3 次点击计数均稳定返回 `['1', '1', '1']`);`--shard=1/4` 将套件切分为多片分发到 CI 多台机器并行执行再汇总报告(本站实测将 8 条规格均分为 4 片 `[2, 2, 2, 2]` 且覆盖去重总数 8 条,并在 Chromium 中完成第 1 片 2 条用例运行)。
调试与视觉回归常用辅助参数包括 `--update-snapshots` 刷新基准截图、`--trace on` 强制记录执行轨迹,以及事后用 `npx playwright show-trace` 查看压缩包。本站离线开启 `tracing.start(screenshots=True, snapshots=True)` 执行交互并保存 `trace.zip`,核实压缩包内完整包含 `trace.trace`、`trace.network` 与截图帧。常用 CLI 命令速查见下表。
Playwright 常用运行与诊断命令速查
| 命令 | 作用 |
|---|---|
| `npx playwright test` | 运行配置范围内的全部测试用例 |
| `npx playwright test file.spec.ts` | 仅运行指定的单个测试文件 |
| `npx playwright test -g "关键词"` | 按测试标题关键词或正则表达式筛选执行 |
| `npx playwright test --project=chromium` | 仅在指定的项目/浏览器配置下运行 |
| `npx playwright test --headed` | 以有头模式显示真实浏览器窗口运行 |
| `npx playwright test --ui` | 打开图形化 UI Mode 交互式浏览和调试测试 |
| `npx playwright test --debug` | 启动 Inspector 单步调试模式 |
| `npx playwright test --workers=4` | 显式指定并发运行的 worker 数量 |
| `npx playwright test --shard=1/4` | 按 4 分片切分套件并仅运行第 1 片(适合 CI 分布式并行) |
| `npx playwright test --repeat-each=3` | 每条测试连续重复执行 3 次以检验稳定性 |
| `npx playwright test --update-snapshots` | 重新生成并更新视觉回归基准截图 |
| `npx playwright show-report` | 在本地浏览器打开最近一次 HTML 测试报告 |
| `npx playwright show-trace trace.zip` | 加载并回放指定 Trace 压缩包中的完整轨迹 |
| `npx playwright codegen url` | 针对目标地址启动交互式代码录制生成器 |
运行多维用例筛选、三次隔离重复执行、四分片切分与 Trace 生成实测
"""Offline Playwright Chromium lab for Chapter 24: Running Tests."""
import json
import os
from pathlib import Path
import re
import tempfile
import zipfile
from playwright.sync_api import sync_playwright
def launch_chromium(p):
if os.path.exists(p.chromium.executable_path):
return p.chromium.launch(headless=True)
for ch in ("chrome", "msedge"):
try:
return p.chromium.launch(channel=ch, headless=True)
except Exception:
continue
raise RuntimeError("No Chromium/Chrome/Edge browser executable available")
def make_case(name, expected, actual):
return {"name": name, "expected": expected, "actual": actual, "passed": actual == expected}
SUITE = [
{"file": "tests/login.spec.ts", "title": "用户登录校验 @smoke"},
{"file": "tests/register.spec.ts", "title": "新用户注册流程 @smoke"},
{"file": "tests/user/profile.spec.ts", "title": "资料页加载 @slow"},
{"file": "tests/user/settings.spec.ts", "title": "隐私设置更新"},
{"file": "tests/cart.spec.ts", "title": "购物车结算 @smoke"},
{"file": "tests/search.spec.ts", "title": "搜索结果分页"},
{"file": "tests/export.spec.ts", "title": "大表导出 @slow"},
{"file": "tests/logout.spec.ts", "title": "退出登录清理"},
]
def main():
cases = []
with tempfile.TemporaryDirectory() as tmpdir:
with sync_playwright() as p:
browser = launch_chromium(p)
try:
# Case 1: Test selection rules (file path, keyword, grep regex, tag include/invert) + live run
by_file = [t["title"] for t in SUITE if t["file"] == "tests/login.spec.ts"]
by_kw = [t["file"] for t in SUITE if any(k in t["file"] for k in ("login", "user"))]
by_grep = [t["title"] for t in SUITE if re.search(r"登录|注册", t["title"])]
by_smoke = [t["title"] for t in SUITE if "@smoke" in t["title"]]
by_invert_slow = [t["title"] for t in SUITE if "@slow" not in t["title"]]
# Execute the matched @smoke tests in headless Chromium
smoke_passed = 0
for title in by_smoke:
ctx = browser.new_context()
pg = ctx.new_page()
pg.set_content(f"<main><h1 id='t'>{title}</h1><button id='go'>Run</button></main>")
pg.locator("#go").click()
if pg.locator("#t").text_content() == title:
smoke_passed += 1
ctx.close()
cases.append(make_case(
"filter_by_file_grep_and_tags",
{
"by_file_count": 1,
"by_kw_count": 3,
"by_grep_count": 3,
"smoke_count": 3,
"invert_slow_count": 6,
"smoke_passed": 3,
},
{
"by_file_count": len(by_file),
"by_kw_count": len(by_kw),
"by_grep_count": len(by_grep),
"smoke_count": len(by_smoke),
"invert_slow_count": len(by_invert_slow),
"smoke_passed": smoke_passed,
},
))
# Case 2: --repeat-each=3 deterministic stability check in isolated Chromium contexts
repeat_results = []
for run_idx in range(3):
ctx = browser.new_context()
pg = ctx.new_page()
pg.set_content("<button id='inc'>0</button><script>let n=0;inc.onclick=()=>{n++;inc.textContent=String(n);};</script>")
pg.locator("#inc").click()
repeat_results.append(pg.locator("#inc").text_content())
ctx.close()
cases.append(make_case(
"repeat_each_stability_in_chromium",
["1", "1", "1"],
repeat_results,
))
# Case 3: --shard=1/4..4/4 balanced partitioning and execution of shard 1
total_shards = 4
shards = [SUITE[i::total_shards] for i in range(total_shards)]
shard1_titles = []
for item in shards[0]:
ctx = browser.new_context()
pg = ctx.new_page()
pg.set_content(f"<p id='s'>{item['file']}</p>")
shard1_titles.append(pg.locator("#s").text_content())
ctx.close()
cases.append(make_case(
"shard_partition_distribution",
{
"shard_sizes": [2, 2, 2, 2],
"total_covered": 8,
"shard1_files": ["tests/login.spec.ts", "tests/cart.spec.ts"],
},
{
"shard_sizes": [len(s) for s in shards],
"total_covered": len({t["file"] for s in shards for t in s}),
"shard1_files": shard1_titles,
},
))
# Case 4: --trace on capture producing valid trace.zip archive
trace_zip = Path(tmpdir) / "trace.zip"
ctx = browser.new_context()
ctx.tracing.start(screenshots=True, snapshots=True, sources=False)
pg = ctx.new_page()
pg.set_content("<button id='btn'>Go</button><span id='out'>idle</span><script>btn.onclick=()=>out.textContent='done';</script>")
pg.locator("#btn").click()
out_text = pg.locator("#out").text_content()
ctx.tracing.stop(path=str(trace_zip))
ctx.close()
with zipfile.ZipFile(trace_zip) as zf:
names = zf.namelist()
cases.append(make_case(
"trace_on_capture_during_run",
{"out_text": "done", "has_trace": True, "has_network": True, "has_screenshots": True},
{
"out_text": out_text,
"has_trace": "trace.trace" in names,
"has_network": "trace.network" in names,
"has_screenshots": any(n.endswith(".jpeg") or n.endswith(".png") for n in names),
},
))
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对文件/关键词/正则/Tag 筛选命中计数与无头运行通过、repeat-each 3 次隔离稳定、4 分片均衡切分及 trace.zip 结构完整性。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:0c9af56bf061711fb2911db6ceba42a2c23a3a6ef025675d9ef56b5975b4f4d7
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:8ef4d50add4be43b7936244cb7f64a4b2d8c34c6edf6db30b485e7c28c9a46ed
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 CI 流水线中发现某条测试偶发失败,应组合使用哪些命令行参数在本地快速定位并复现?
展开参考解答
可用 --grep 精确锁定该用例,叠加 --repeat-each=5 或 --repeat-each=10 提高复现概率,同时加上 --trace on(或 --workers=1 排除并发干扰)保存失败轨迹以便离线回放排查。