"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/playwright-running-tests-lab/explore-running-tests.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-running-tests.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a630.zip
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a602.zip