CodeSampleX

示例

playwright 1.58.0

已验证示例 — pypi playwright 1.58.0. contract 在 python 3.12 · linux debian/x64 · docker 上运行并通过: sync_playwright launches Playwright context manager and provides…

sha256:d8ee0c4f45fd409804f600f67058f7e892e209c1b7e879ebefc5df471b8b0b72

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux 24 · ubuntu · glibc 2.39 x64 pip

验证运行环境

环境 契约 阶段 运行日期
python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104…
2026-09-08

案例

HOW
目标
verify pkg:pypi/playwright@1.58.0
包
创建时间
2026-09-07T16:58:06Z

契约

  1. sync_playwright launches Playwright context manager and provides access to chromium, firefox, and webkit browser types
  2. sync_playwright devices dictionary provides predefined mobile and desktop device configurations with viewport, user_agent, and touch capabilities
  3. sync_playwright selectors API allows setting custom test id attribute
  4. sync_playwright request.new_context creates APIRequestContext capable of issuing HTTP GET and POST requests with JSON serialization

文件

  • PROMPT.md
  • csx.json
  • pyproject.toml
  • requirements.txt
  • sample.py
  • spec.json
  • test/contract.py

下载源代码构件 (tar.gz)

源代码

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify pkg:pypi/playwright@1.58.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/playwright@1.58.0

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:d447afd3b880aefdbb608a776509408b87687dfecce94b5070dac64b59084fe0","contract":["sync_playwright launches Playwright context manager and provides access to chromium, firefox, and webkit browser types","sync_playwright devices dictionary provides predefined mobile and desktop device configurations with viewport, user_agent, and touch capabilities","sync_playwright selectors API allows setting custom test id attribute","sync_playwright request.new_context creates APIRequestContext capable of issuing HTTP GET and POST requests with JSON serialization"],"goal":"verify pkg:pypi/playwright@1.58.0","kind":"HOW","packages":["pkg:pypi/playwright@1.58.0"],"schemaVersion":1},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/playwright@1.58.0"],"schemaVersion":1,"subject":"pkg:pypi/playwright@1.58.0","verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "verify-playwright"
version = "0.1.0"
dependencies = [
    "playwright==1.58.0",
]
requirements.txt
playwright==1.58.0
sample.py
"""Demonstration of Playwright sync API using sync_playwright."""

from typing import Any, Dict, Optional
from playwright.sync_api import Playwright, APIRequestContext, APIResponse


def get_browser_types(p: Playwright) -> Dict[str, str]:
    """Return dictionary of available browser type names."""
    return {
        "chromium": p.chromium.name,
        "firefox": p.firefox.name,
        "webkit": p.webkit.name,
    }


def get_device_config(p: Playwright, device_name: str) -> Dict[str, Any]:
    """Retrieve device configuration dictionary by name."""
    return p.devices.get(device_name, {})


def configure_test_id_attribute(p: Playwright, attribute_name: str) -> None:
    """Configure custom test id attribute on selectors."""
    p.selectors.set_test_id_attribute(attribute_name)


def create_api_request_context(
    p: Playwright,
    base_url: str,
    extra_http_headers: Optional[Dict[str, str]] = None,
) -> APIRequestContext:
    """Create and return an APIRequestContext with base URL and optional headers."""
    return p.request.new_context(base_url=base_url, extra_http_headers=extra_http_headers)


def send_get_request(context: APIRequestContext, endpoint: str) -> APIResponse:
    """Send an HTTP GET request via APIRequestContext."""
    return context.get(endpoint)


def send_post_request(context: APIRequestContext, endpoint: str, data: Any) -> APIResponse:
    """Send an HTTP POST request via APIRequestContext with JSON payload."""
    return context.post(endpoint, data=data)
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:pypi/playwright@1.58.0",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/playwright@1.58.0"
  ]
}
test/contract.py
"""Contract verification test for sync_playwright in playwright."""

import http.server
import json
import os
import sys
import threading

# Ensure project root is on sys.path for local module imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from playwright.sync_api import sync_playwright, Playwright, APIRequestContext
from sample import (
    get_browser_types,
    get_device_config,
    configure_test_id_attribute,
    create_api_request_context,
    send_get_request,
    send_post_request,
)


class MockServer(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/api/status":
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("X-Server-Name", "local-test")
            self.end_headers()
            self.wfile.write(json.dumps({"status": "ready", "version": "1.0"}).encode("utf-8"))
        else:
            self.send_response(404)
            self.end_headers()

    def do_POST(self):
        if self.path == "/api/data":
            content_length = int(self.headers.get("Content-Length", 0))
            payload = json.loads(self.rfile.read(content_length))
            self.send_response(201)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps({"received": payload, "success": True}).encode("utf-8"))
        else:
            self.send_response(404)
            self.end_headers()

    def log_message(self, format, *args):
        # Suppress server logging during contract tests
        pass


def test_browser_types_and_context_manager(p: Playwright) -> None:
    """Contract: sync_playwright launches Playwright context manager and provides access to chromium, firefox, and webkit browser types."""
    assert isinstance(p, Playwright)
    browsers = get_browser_types(p)
    assert browsers["chromium"] == "chromium"
    assert browsers["firefox"] == "firefox"
    assert browsers["webkit"] == "webkit"


def test_device_descriptors(p: Playwright) -> None:
    """Contract: sync_playwright devices dictionary provides predefined mobile and desktop device configurations with viewport, user_agent, and touch capabilities."""
    device_name = "iPhone 13"
    assert device_name in p.devices
    config = get_device_config(p, device_name)
    assert config["viewport"]["width"] == 390
    assert config["viewport"]["height"] == 664
    assert config["device_scale_factor"] == 3
    assert config["is_mobile"] is True
    assert config["has_touch"] is True
    assert "iPhone" in config["user_agent"]


def test_selectors_configuration(p: Playwright) -> None:
    """Contract: sync_playwright selectors API allows setting custom test id attribute."""
    configure_test_id_attribute(p, "data-testid")


def test_api_request_context(p: Playwright, base_url: str) -> None:
    """Contract: sync_playwright request.new_context creates APIRequestContext capable of issuing HTTP GET and POST requests with JSON serialization."""
    headers = {"X-Client-Id": "client-abc"}
    context = create_api_request_context(p, base_url=base_url, extra_http_headers=headers)
    try:
        assert isinstance(context, APIRequestContext)

        # GET request
        get_res = send_get_request(context, "/api/status")
        assert get_res.status == 200
        assert get_res.ok is True
        assert get_res.headers.get("x-server-name") == "local-test"
        json_data = get_res.json()
        assert json_data["status"] == "ready"
        assert json_data["version"] == "1.0"

        # POST request
        payload = {"metric": "latency", "value": 42}
        post_res = send_post_request(context, "/api/data", payload)
        assert post_res.status == 201
        assert post_res.ok is True
        post_json = post_res.json()
        assert post_json["success"] is True
        assert post_json["received"] == payload
    finally:
        context.dispose()


def main() -> None:
    server = http.server.HTTPServer(("127.0.0.1", 0), MockServer)
    port = server.server_address[1]
    server_thread = threading.Thread(target=server.serve_forever, daemon=True)
    server_thread.start()

    base_url = f"http://127.0.0.1:{port}"
    try:
        with sync_playwright() as p:
            test_browser_types_and_context_manager(p)
            test_device_descriptors(p)
            test_selectors_configuration(p)
            test_api_request_context(p, base_url)
        print("All contract assertions passed.")
    finally:
        server.shutdown()
        server.server_close()


if __name__ == "__main__":
    main()

原始种子者

匿名