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

实测语义化定位优先级、录制三类断言、Trace 追踪包导出与 launch.json 结构核验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-setup.py
explore-setup.py118 行
"""Offline Playwright lab for Chapter 05 (setup): semantic locator priority, recorded assertions, trace archive, launch.json validation."""
import json
import os
import tempfile
import zipfile
from pathlib import Path
from playwright.sync_api import expect, sync_playwright

DEMO_HTML = """<!doctype html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>VS Code 定位与录制演练</title></head>
<body>
  <input id="profile-name" aria-label="昵称" value="PlaywrightDev" />
  <button id="save-btn" data-testid="save-action">保存配置</button>
  <p id="toast" hidden>已保存</p>
  <div class="card">卡片 1</div>
  <div class="card">卡片 2</div>
  <div class="card">卡片 3</div>
  <script>
    document.getElementById('save-btn').addEventListener('click', () => {
      const name = document.getElementById('profile-name').value;
      const toast = document.getElementById('toast');
      toast.textContent = '已保存:' + name;
      toast.hidden = false;
    });
  </script>
</body>
</html>"""


def launch_browser(p):
    exe = p.chromium.executable_path
    if exe and os.path.exists(exe):
        return p.chromium.launch(headless=True)
    for ch in ("chrome", "msedge"):
        try:
            return p.chromium.launch(channel=ch, headless=True)
        except Exception:
            continue
    return p.chromium.launch(headless=True)


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        ctx = browser.new_context()
        page = ctx.new_page()
        page.set_content(DEMO_HTML)

        # Case 1: Semantic locator priority (role > text > testid) + multi-match count
        by_role_id = page.get_by_role("button", name="保存配置").get_attribute("id")
        by_text_id = page.get_by_text("保存配置").get_attribute("id")
        by_testid_id = page.get_by_test_id("save-action").get_attribute("id")
        card_count = page.locator(".card").count()
        exp1 = {"role_id": "save-btn", "text_id": "save-btn", "testid_id": "save-btn", "multi_match_count": 3}
        act1 = {"role_id": by_role_id, "text_id": by_text_id, "testid_id": by_testid_id, "multi_match_count": card_count}
        cases.append(dict(name="semantic_locator_priority", expected=exp1, actual=act1, passed=act1 == exp1))

        # Case 2: Recorded assertion triplet (visibility, text, value)
        name_input = page.get_by_label("昵称")
        name_input.fill("BlueSkyQA")
        page.get_by_role("button", name="保存配置").click()
        toast = page.locator("#toast")
        expect(toast).to_be_visible()
        expect(toast).to_contain_text("已保存:BlueSkyQA")
        expect(name_input).to_have_value("BlueSkyQA")
        exp2 = {"toast_visible": True, "toast_text": "已保存:BlueSkyQA", "input_value": "BlueSkyQA"}
        act2 = {"toast_visible": toast.is_visible(), "toast_text": toast.inner_text(), "input_value": name_input.input_value()}
        cases.append(dict(name="recorded_assertions_triplet", expected=exp2, actual=act2, passed=act2 == exp2))

        # Case 3: Trace archive generation (matching VS Code trace viewer workflow)
        with tempfile.TemporaryDirectory() as tmp:
            trace_zip = Path(tmp) / "trace.zip"
            ctx.tracing.start(screenshots=True, snapshots=True)
            page.get_by_label("昵称").fill("TraceUser")
            page.get_by_role("button", name="保存配置").click()
            ctx.tracing.stop(path=str(trace_zip))
            with zipfile.ZipFile(trace_zip, "r") as zf:
                names = set(zf.namelist())
            exp3 = {"zip_exists": True, "has_trace_file": True}
            act3 = {"zip_exists": trace_zip.exists(), "has_trace_file": "trace.trace" in names}
            cases.append(dict(name="tracing_capture_and_zip_export", expected=exp3, actual=act3, passed=act3 == exp3))

        # Case 4: VS Code launch.json structure verification
        launch_cfg = {
            "version": "0.2.0",
            "configurations": [
                {
                    "name": "Debug Playwright Test",
                    "type": "node",
                    "request": "launch",
                    "program": "${workspaceFolder}/node_modules/.bin/playwright",
                    "args": ["test", "--project=chromium", "--headed"],
                    "console": "integratedTerminal",
                    "internalConsoleOptions": "neverOpen",
                }
            ],
        }
        cfg = launch_cfg["configurations"][0]
        exp4 = {"type": "node", "request": "launch", "has_headed_flag": True, "has_chromium_project": True}
        act4 = {
            "type": cfg["type"],
            "request": cfg["request"],
            "has_headed_flag": "--headed" in cfg["args"],
            "has_chromium_project": "--project=chromium" in cfg["args"],
        }
        cases.append(dict(name="launch_config_json_validation", expected=exp4, actual=act4, passed=act4 == exp4))

        ctx.close()
        browser.close()

    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

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

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

下载课程关联工程包:Playwright

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

下载课程关联工程包:Playwright

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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