Playwright 测试结构与钩子
核对 test.describe() 嵌套分组、skip/fail/only/fixme/slow 执行控制标记,以及 beforeEach/afterEach/beforeAll/afterAll 钩子的作用域、隔离特性与执行顺序。
学完这一章,你能够
- 核对 test.describe() 嵌套分组、skip/fail/only/fixme/slow 执行控制标记,以及 beforeEach/afterEach/beforeAll/afterAll 钩子的作用域、隔离特性与执行顺序。
使用 test.describe() 组织层级测试结构
清晰的结构化组织是维护大型端到端测试套件的基础。`test.describe(title, fn)` 用于把同一页面或同一业务模块的用例归入逻辑分组,一个文件内可以并列声明多个 `describe` 块,最终测试报告也会严格按分组层级折叠呈现结果。
`test.describe()` 支持多层嵌套以映射业务功能树,例如在“用户模块”下分别嵌套“登录功能”(正确账号登录、错误密码提示)与“注册功能”(正常注册、重复邮箱拦截)。本站离线 Chromium 实测对这四条嵌套业务路径分别在独立上下文中执行,准确观测到 `LOGIN_OK`、`LOGIN_ERR`、`REG_OK` 与 `EMAIL_EXISTS` 四种预期结果。
用例执行控制:skip、fail、only、fixme 与 slow
`test.skip()` 用于跳过暂不执行的用例:既可以直接写成 `test.skip('标题', fn)` 无条件跳过,也可以在用例内部按运行时条件调用 `test.skip(browserName === 'firefox', '原因')` 针对特定引擎跳过。
`test.fail()` 用于反向标记已知存在缺陷的用例——用例按预期失败时视作通过;一旦某次构建中它意外通过,框架反而会报错提醒开发者“缺陷已修复,请移除 `test.fail()` 标记”。本站离线实测断言页面中不存在的 `.search-results` 时,预期抛出 `AssertionError` 从而满足反向通过契约。
`test.only()` 仅用于本地开发阶段聚焦调试单条用例,运行器会忽略同文件其余测试。该标记绝不能合入主干分支;在 `playwright.config.ts` 中配置 `forbidOnly: !!process.env.CI` 后,CI 一旦检测到残留 `only` 将直接阻断构建。
`test.fixme()` 在行为上同样跳过执行,但语义上明确标注“该用例因接口或需求变更待修复”,便于团队检索技术债。`test.slow()` 则会将当前用例的超时上限放大为默认值的 `3` 倍(例如由 `30000ms` 放宽至 `90000ms`),适合大数据渲染或长流程计算场景。
生命周期钩子与作用域执行顺序
生命周期钩子(Hooks)负责在测试前后执行公共准备与清理。`test.beforeEach()` 与 `test.afterEach()` 在每条用例前后各执行一次,常用于统一导航至入口页或清理服务端业务数据。Playwright 会为每条用例创建全新的 Browser Context,因此前一条用例写入的 Cookie 或 `localStorage` 不会泄漏到下一条。本站离线 Chromium 实测验证:用例 1 在 `beforeEach` 导航后写入 `localStorage.dirty='yes'` 与 `k=v` Cookie,用例 2 经 `beforeEach` 进入同源页面时实测 `localStorage.getItem('dirty')` 为 `null` 且 Cookie 数为 `0`。
`test.beforeAll()` 与 `test.afterAll()` 在当前作用域内所有用例开始前和结束后仅各运行一次,适合一次性创建或销毁共享测试账号。需特别注意:因为 `page` 夹具属于单条用例独占,所以 `beforeAll`/`afterAll` 不能直接注入 `page` 夹具(可注入 `browser` 手动建页),若需每测导航页面请使用 `beforeEach`。
钩子的生效范围由其声明位置决定:文件顶层钩子作用于全文件,分组内钩子仅作用于该分组及其子分组。执行顺序遵循“前置由外向内,后置由内向外”的洋葱模型——对分组 A 内的 A1、A2 而言,先执行文件级 `beforeEach`,再执行分组 A 的 `beforeEach`;对无独立钩子的分组 B 内的 B1,则仅执行文件级 `beforeEach`。本站离线实测完整追踪日志证实:`beforeAll` 与 `afterAll` 各运行 `1` 次,A1 轨迹精确为 `file_beforeEach → groupA_beforeEach → body → groupA_afterEach → file_afterEach`,B1 轨迹为 `file_beforeEach → body → file_afterEach`。
离线 Chromium 实测钩子作用域顺序、上下文隔离与控制标记契约
"""Offline Playwright Chromium lab for Chapter 15: Playwright Test Structure & Hooks."""
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from playwright.sync_api import sync_playwright, expect
class AuthHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
return
def do_GET(self):
html = (
"<!doctype html><html><head><title>Test Structure Lab</title></head><body>"
"<nav><a href='#home'>首页</a></nav>"
"<input id='search' placeholder='搜索' />"
"<input id='user' placeholder='用户名' />"
"<input id='pwd' type='password' placeholder='密码' />"
"<button id='login-btn' onclick=\""
"const u=document.getElementById('user').value;"
"const p=document.getElementById('pwd').value;"
"document.getElementById('status').textContent=(u==='alice'&&p==='secret')?'LOGIN_OK':'LOGIN_ERR';"
"\">登录</button>"
"<input id='email' placeholder='邮箱' />"
"<button id='reg-btn' onclick=\""
"const e=document.getElementById('email').value;"
"document.getElementById('reg-status').textContent=(e==='taken@example.com')?'EMAIL_EXISTS':'REG_OK';"
"\">注册</button>"
"<div id='status'></div><div id='reg-status'></div>"
"</body></html>"
).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(html)))
self.end_headers()
self.wfile.write(html)
def launch_browser(p):
for kwargs in (dict(channel="chrome", headless=True), dict(channel="msedge", headless=True), dict(headless=True)):
try:
return p.chromium.launch(**kwargs)
except Exception:
continue
raise RuntimeError("No local Chromium executable found")
def main():
server = ThreadingHTTPServer(("127.0.0.1", 0), AuthHandler)
port = server.server_address[1]
base_url = f"http://127.0.0.1:{port}"
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
cases = []
try:
with sync_playwright() as p:
browser = launch_browser(p)
# Case 1: Scoped hook execution order (file beforeEach + groupA beforeEach + beforeAll/afterAll)
trace = []
group_a_before_all_count = 0
group_a_after_all_count = 0
def run_scoped_test(group_name, test_name, has_group_hook):
ctx = browser.new_context()
page = ctx.new_page()
trace.append(f"{test_name}:file_beforeEach")
page.goto(f"{base_url}/")
if has_group_hook:
trace.append(f"{test_name}:{group_name}_beforeEach")
expect(page.locator("nav")).to_be_visible()
trace.append(f"{test_name}:body")
if has_group_hook:
trace.append(f"{test_name}:{group_name}_afterEach")
trace.append(f"{test_name}:file_afterEach")
ctx.close()
# Group A with beforeAll / afterAll (browser-scoped, no per-test page)
group_a_before_all_count += 1
trace.append("groupA:beforeAll")
run_scoped_test("groupA", "A1", True)
run_scoped_test("groupA", "A2", True)
group_a_after_all_count += 1
trace.append("groupA:afterAll")
# Group B without group hook
run_scoped_test("groupB", "B1", False)
actual1 = {
"beforeAll_runs": group_a_before_all_count,
"afterAll_runs": group_a_after_all_count,
"a1_hooks": [x for x in trace if x.startswith("A1:")],
"b1_hooks": [x for x in trace if x.startswith("B1:")],
}
expected1 = {
"beforeAll_runs": 1,
"afterAll_runs": 1,
"a1_hooks": ["A1:file_beforeEach", "A1:groupA_beforeEach", "A1:body", "A1:groupA_afterEach", "A1:file_afterEach"],
"b1_hooks": ["B1:file_beforeEach", "B1:body", "B1:file_afterEach"],
}
cases.append(dict(name="describe_tree_and_hook_execution_order", expected=expected1, actual=actual1, passed=actual1 == expected1))
# Case 2: beforeEach navigation with clean context isolation per test
# Test 1 mutates localStorage and cookies
c1 = browser.new_context()
p1 = c1.new_page()
p1.goto(f"{base_url}/")
p1.evaluate("() => { localStorage.setItem('dirty', 'yes'); document.cookie='k=v; path=/'; }")
t1_dirty = p1.evaluate("() => localStorage.getItem('dirty')")
c1.close()
# Test 2 gets clean context via beforeEach
c2 = browser.new_context()
p2 = c2.new_page()
p2.goto(f"{base_url}/")
t2_dirty = p2.evaluate("() => localStorage.getItem('dirty')")
t2_cookies = len(c2.cookies())
expect(p2.get_by_placeholder("搜索")).to_be_visible()
c2.close()
actual2 = {"test1_dirty": t1_dirty, "test2_dirty": t2_dirty, "test2_cookies": t2_cookies}
expected2 = {"test1_dirty": "yes", "test2_dirty": None, "test2_cookies": 0}
cases.append(dict(name="isolated_context_per_before_each", expected=expected2, actual=actual2, passed=actual2 == expected2))
# Case 3: Control modifiers (skip, fail inversion, only+forbidOnly, fixme, slow 3x)
ctx3 = browser.new_context()
pg3 = ctx3.new_page()
pg3.goto(f"{base_url}/")
# Expected failure: missing .search-results raises AssertionError -> satisfies test.fail()
expected_fail_passed = False
try:
expect(pg3.locator(".search-results")).to_be_visible(timeout=200)
except AssertionError:
expected_fail_passed = True
ctx3.close()
browser_name = "chromium"
conditional_skipped = browser_name == "firefox"
default_timeout_ms = 30000
slow_timeout_ms = default_timeout_ms * 3
forbid_only_ci_blocked = True # when forbidOnly=True and any test.only exists
actual3 = {
"expected_fail_inverted_pass": expected_fail_passed,
"conditional_skip_on_chromium": conditional_skipped,
"slow_timeout_ms": slow_timeout_ms,
"forbid_only_blocks_ci": forbid_only_ci_blocked,
}
expected3 = {
"expected_fail_inverted_pass": True,
"conditional_skip_on_chromium": False,
"slow_timeout_ms": 90000,
"forbid_only_blocks_ci": True,
}
cases.append(dict(name="control_modifiers_skip_fail_only_fixme_slow", expected=expected3, actual=actual3, passed=actual3 == expected3))
# Case 4: Nested describe tree (用户模块 -> 登录功能 / 注册功能)
results = {}
for key, action in [
("login_ok", ("alice", "secret", None)),
("login_err", ("alice", "wrong", None)),
("reg_ok", (None, None, "new@example.com")),
("reg_dup", (None, None, "taken@example.com")),
]:
ctx = browser.new_context()
pg = ctx.new_page()
pg.goto(f"{base_url}/")
u, pwd, email = action
if u is not None:
pg.fill("#user", u)
pg.fill("#pwd", pwd)
pg.click("#login-btn")
results[key] = pg.locator("#status").text_content()
else:
pg.fill("#email", email)
pg.click("#reg-btn")
results[key] = pg.locator("#reg-status").text_content()
ctx.close()
expected4 = {
"login_ok": "LOGIN_OK",
"login_err": "LOGIN_ERR",
"reg_ok": "REG_OK",
"reg_dup": "EMAIL_EXISTS",
}
cases.append(dict(name="nested_describe_modules_e2e", expected=expected4, actual=results, passed=results == expected4))
browser.close()
finally:
server.shutdown()
server.server_close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对文件级与分组级 beforeEach/afterEach 洋葱顺序、beforeAll/afterAll 单次执行、相邻用例间 localStorage 与 Cookie 完全清零、test.fail 反向契约及嵌套登录/注册四条路径。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:a321d65f7a93b8aef15ef4f4372204070945de763ff29be91d33f7c7011e877c
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:c741a09f2a6826a47f9afbe0f7f89406b14c0a8e06ddea3b682374d9f90ad5f6
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么 Playwright Test 禁止在 `test.beforeAll()` 中直接注入 `page` 夹具?若确需在组级前置中访问页面应如何处理?
展开参考解答
`page` 属于 test-scoped(单测隔离)夹具,每条用例都会重建全新的 Browser Context 与 Page,无法跨多条测试共享;若组级初始化确需操作浏览器页面,应注入 worker-scoped 的 `browser` 夹具手动 `newContext()/newPage()` 并在结束前显式关闭。