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

运行五类录制动作回放、八级定位优先级、断言验证与仿真选项实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-codegen.py
explore-codegen.py199 行
"""Offline Playwright Chromium lab for Chapter 26: Codegen."""
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from http.cookies import SimpleCookie
import json
import os
from pathlib import Path
import tempfile
import threading
from playwright.sync_api import sync_playwright, expect


CODEGEN_HTML = """<!doctype html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>Codegen Target</title></head>
<body>
  <h1 id="heading">测试录制页</h1>
  <p>欢迎使用录制功能</p>
  <form id="demo-form">
    <label for="user-input">用户名</label>
    <input id="user-input" placeholder="请输入用户名" />
    <input id="note-input" placeholder="请输入备注" />
    <label for="role-select">角色</label>
    <select id="role-select">
      <option value="viewer">访客</option>
      <option value="editor">编辑</option>
    </select>
    <label><input id="agree-box" type="checkbox" /> 同意协议</label>
    <button type="button" id="submit-btn">提交</button>
  </form>
  <img alt="产品图标" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=" />
  <div data-testid="status-badge" title="状态提示">未提交</div>
  <span class="css-fallback">尾部节点</span>
  <script>
    document.getElementById('submit-btn').addEventListener('click', () => {
      const u = document.getElementById('user-input').value;
      const r = document.getElementById('role-select').value;
      document.querySelector('[data-testid="status-badge"]').textContent = u + ':' + r;
    });
  </script>
</body>
</html>"""


class CodegenHandler(BaseHTTPRequestHandler):
    def log_message(self, fmt, *args):
        pass

    def _send(self, code, body, extra_headers=None):
        data = body.encode("utf-8")
        self.send_response(code)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.send_header("Content-Length", str(len(data)))
        for k, v in (extra_headers or []):
            self.send_header(k, v)
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        if self.path == "/":
            self._send(200, CODEGEN_HTML, [("Set-Cookie", "rec_session=saved42; Path=/")])
        elif self.path == "/whoami":
            ck = SimpleCookie()
            ck.load(self.headers.get("Cookie", ""))
            val = ck["rec_session"].value if "rec_session" in ck else "none"
            self._send(200, f"<span id='sess'>{val}</span>")
        else:
            self._send(404, "not found")


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}


def main():
    server = ThreadingHTTPServer(("127.0.0.1", 0), CodegenHandler)
    port = server.server_address[1]
    base = f"http://127.0.0.1:{port}"
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()

    cases = []
    try:
        with tempfile.TemporaryDirectory() as tmpdir:
            auth_file = Path(tmpdir) / "auth.json"
            with sync_playwright() as p:
                browser = launch_chromium(p)
                try:
                    # Case 1: Replay canonical Codegen recorded actions (goto, fill, selectOption, check/uncheck, click)
                    ctx = browser.new_context(base_url=base)
                    pg = ctx.new_page()
                    pg.goto("/")
                    pg.get_by_label("用户名").fill("alice")
                    pg.get_by_placeholder("请输入备注").fill("note-1")
                    pg.get_by_label("角色").select_option("editor")
                    pg.get_by_label("同意协议").check()
                    checked_after_check = pg.get_by_label("同意协议").is_checked()
                    pg.get_by_label("同意协议").uncheck()
                    checked_after_uncheck = pg.get_by_label("同意协议").is_checked()
                    pg.get_by_role("button", name="提交").click()
                    badge_text = pg.get_by_test_id("status-badge").text_content()
                    ctx.storage_state(path=str(auth_file))

                    cases.append(make_case(
                        "recorded_user_actions_replay",
                        {
                            "checked_after_check": True,
                            "checked_after_uncheck": False,
                            "note_value": "note-1",
                            "badge_text": "alice:editor",
                        },
                        {
                            "checked_after_check": checked_after_check,
                            "checked_after_uncheck": checked_after_uncheck,
                            "note_value": pg.get_by_placeholder("请输入备注").input_value(),
                            "badge_text": badge_text,
                        },
                    ))

                    # Case 2: All 8 locator priority strategies uniquely resolve target elements
                    counts = {
                        "role": pg.get_by_role("button", name="提交").count(),
                        "text": pg.get_by_text("欢迎使用录制功能").count(),
                        "label": pg.get_by_label("用户名").count(),
                        "placeholder": pg.get_by_placeholder("请输入备注").count(),
                        "alt_text": pg.get_by_alt_text("产品图标").count(),
                        "test_id": pg.get_by_test_id("status-badge").count(),
                        "title": pg.get_by_title("状态提示").count(),
                        "css": pg.locator(".css-fallback").count(),
                    }
                    cases.append(make_case(
                        "locator_priority_resolution",
                        {k: 1 for k in counts},
                        counts,
                    ))

                    # Case 3: Codegen assertion actions (Visibility, Text, Value, Snapshot)
                    expect(pg.get_by_test_id("status-badge")).to_be_visible()
                    expect(pg.get_by_test_id("status-badge")).to_have_text("alice:editor")
                    expect(pg.get_by_label("用户名")).to_have_value("alice")
                    snap_bytes = pg.get_by_test_id("status-badge").screenshot()
                    cases.append(make_case(
                        "assertion_types_verification",
                        {"assertions_passed": True, "snapshot_is_png": True},
                        {"assertions_passed": True, "snapshot_is_png": snap_bytes[:8] == b"\x89PNG\r\n\x1a\n"},
                    ))
                    ctx.close()

                    # Case 4: Codegen CLI emulation & storage options (--viewport-size, --device, --color-scheme, --load-storage)
                    ctx_vp = browser.new_context(
                        base_url=base,
                        viewport={"width": 375, "height": 812},
                        color_scheme="dark",
                        storage_state=str(auth_file),
                    )
                    pg_vp = ctx_vp.new_page()
                    pg_vp.goto("/whoami")
                    vp_state = pg_vp.evaluate("() => ({w: window.innerWidth, h: window.innerHeight, dark: matchMedia('(prefers-color-scheme: dark)').matches})")
                    sess_val = pg_vp.locator("#sess").text_content()
                    ctx_vp.close()

                    iphone_vp = p.devices["iPhone 15"]["viewport"]
                    cases.append(make_case(
                        "codegen_emulation_and_storage_options",
                        {
                            "custom_viewport": [375, 812],
                            "dark_mode": True,
                            "restored_session": "saved42",
                            "iphone15_viewport": [393, 659],
                        },
                        {
                            "custom_viewport": [vp_state["w"], vp_state["h"]],
                            "dark_mode": vp_state["dark"],
                            "restored_session": sess_val,
                            "iphone15_viewport": [iphone_vp["width"], iphone_vp["height"]],
                        },
                    ))
                finally:
                    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-codegen-lab/explore-codegen.py

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

下载课程关联工程包:Playwright

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

下载课程关联工程包:Playwright

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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