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

模拟 baseURL、Desktop Chrome 设备配置、example.spec.ts 导航断言与 Todo 过滤实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-project-structure.py
explore-project-structure.py164 行
"""Offline Playwright lab for Chapter 04 (project-structure): baseURL, example spec flows, Todo demo, Desktop Chrome device."""
import http.server
import json
import os
import re
import threading
from playwright.sync_api import expect, sync_playwright

HOME_HTML = """<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Fast and reliable end-to-end testing for modern web apps | Playwright</title></head>
<body>
  <h1>Playwright</h1>
  <a href="/docs/intro">Get started</a>
</body>
</html>"""

INTRO_HTML = """<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Installation | Playwright</title></head>
<body><h1>Installation</h1><p>Install Playwright locally.</p></body>
</html>"""

TODO_HTML = """<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Demo Todo App</title></head>
<body>
  <input id="new-todo" placeholder="What needs to be done?" />
  <ul id="todo-list"></ul>
  <div class="filters">
    <button data-filter="all">All</button>
    <button data-filter="active">Active</button>
    <button data-filter="completed">Completed</button>
  </div>
  <script>
    const todos = [];
    let filter = 'all';
    const input = document.getElementById('new-todo');
    const ul = document.getElementById('todo-list');
    function render() {
      ul.innerHTML = '';
      todos.filter(t => filter === 'all' || (filter === 'active' ? !t.done : t.done)).forEach((t) => {
        const li = document.createElement('li');
        li.className = t.done ? 'todo completed' : 'todo';
        const cb = document.createElement('input');
        cb.type = 'checkbox';
        cb.checked = t.done;
        cb.addEventListener('change', () => { t.done = cb.checked; render(); });
        const span = document.createElement('span');
        span.textContent = t.text;
        li.appendChild(cb);
        li.appendChild(span);
        ul.appendChild(li);
      });
    }
    input.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' && input.value.trim()) {
        todos.push({ text: input.value.trim(), done: false });
        input.value = '';
        render();
      }
    });
    document.querySelectorAll('.filters button').forEach(btn => {
      btn.addEventListener('click', () => { filter = btn.dataset.filter; render(); });
    });
  </script>
</body>
</html>"""


class _Handler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        routes = {"/docs/intro": INTRO_HTML, "/todo": TODO_HTML}
        body = routes.get(self.path, HOME_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(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, format, *args):
        pass


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():
    server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
    port = server.server_address[1]
    threading.Thread(target=server.serve_forever, daemon=True).start()
    base_url = f"http://127.0.0.1:{port}"
    cases = []

    try:
        with sync_playwright() as p:
            browser = launch_browser(p)
            desktop_chrome = p.devices["Desktop Chrome"]
            ctx = browser.new_context(base_url=base_url, **desktop_chrome)
            page = ctx.new_page()

            # Case 1: baseURL relative goto + has title assertion
            page.goto("/")
            expect(page).to_have_title(re.compile("Playwright"))
            exp1 = {"relative_url_resolved": True, "title_contains_playwright": True}
            act1 = {
                "relative_url_resolved": page.url == f"{base_url}/",
                "title_contains_playwright": "Playwright" in page.title(),
            }
            cases.append(dict(name="base_url_and_title_check", expected=exp1, actual=act1, passed=act1 == exp1))

            # Case 2: example.spec.ts get started link + Installation heading
            page.get_by_role("link", name="Get started").click()
            heading = page.get_by_role("heading", name="Installation")
            expect(heading).to_be_visible()
            exp2 = {"path": "/docs/intro", "heading_visible": True}
            act2 = {"path": page.url.replace(base_url, ""), "heading_visible": heading.is_visible()}
            cases.append(dict(name="get_started_role_navigation", expected=exp2, actual=act2, passed=act2 == exp2))

            # Case 3: demo-todo-app add / toggle / filter flow
            page.goto("/todo")
            todo_input = page.get_by_placeholder("What needs to be done?")
            todo_input.fill("Buy milk")
            todo_input.press("Enter")
            todo_input.fill("Write Playwright tests")
            todo_input.press("Enter")
            all_count = page.locator("#todo-list li").count()
            page.locator("#todo-list li").first.locator("input[type=checkbox]").check()
            page.get_by_role("button", name="Active").click()
            active_items = page.locator("#todo-list li span").all_text_contents()
            page.get_by_role("button", name="Completed").click()
            completed_items = page.locator("#todo-list li span").all_text_contents()
            exp3 = {"all_count": 2, "active_items": ["Write Playwright tests"], "completed_items": ["Buy milk"]}
            act3 = {"all_count": all_count, "active_items": active_items, "completed_items": completed_items}
            cases.append(dict(name="todo_app_add_toggle_filter", expected=exp3, actual=act3, passed=act3 == exp3))

            # Case 4: Desktop Chrome device profile matching projects config
            vp = page.viewport_size
            ua = page.evaluate("() => navigator.userAgent")
            exp4 = {"viewport": {"width": 1280, "height": 720}, "ua_has_chrome": True}
            act4 = {"viewport": vp, "ua_has_chrome": "Chrome" in ua}
            cases.append(dict(name="desktop_viewport_device_profile", expected=exp4, actual=act4, passed=act4 == exp4))

            ctx.close()
            browser.close()
    finally:
        server.shutdown()
        server.server_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-project-structure-lab/explore-project-structure.py

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

下载课程关联工程包:Playwright

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

下载课程关联工程包:Playwright

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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