蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线 Chromium 实测钩子作用域顺序、上下文隔离与控制标记契约

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-test-structure.py
explore-test-structure.py198 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/playwright-test-structure-lab/explore-test-structure.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-test-structure.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Playwright

课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a602.zip

下载课程关联工程包:Playwright

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a634.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习