CodeSampleX

Ejemplo

httpx 0.28.1: httpx

Muestra verificada para pypi httpx 0.28.1: httpx. El contrato se ejecutó en python 3.12 · linux alpine/x64 · docker y pasó: httpx.Client with MockTransport…

sha256:4887eceffb9e0d1e1f527f92eec6a1b529d4e6a3a78ef6106531d285eefa918b

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado python linux 24 · ubuntu · glibc 2.39 x64 python python pip

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-alpine@sha256:d09d15e60962…
2026-08-26

Caso

HOW
Objetivo
verify httpx in pkg:pypi/httpx@0.28.1
Paquetes
Símbolos
  • httpx
Entorno
python
Creado
2026-08-26T07:29:12Z

Contrato

  1. httpx.Client with MockTransport executes synchronous HTTP requests, applies headers and query params, and decodes JSON responses offline.
  2. httpx.AsyncClient with MockTransport executes asynchronous HTTP requests, supports async context managers, and streams response content via aiter_bytes.
  3. httpx request and response event hooks execute synchronously during the request lifecycle to inspect or modify HTTP traffic.
  4. httpx.URL parses URIs, exposes path and query components, and performs RFC 3986 reference resolution via join.
  5. Response.raise_for_status raises httpx.HTTPStatusError on 4xx/5xx responses without consuming or invalidating response content.
  6. httpx.Headers maintains case-insensitive header lookup and preserves discrete header formatting.

Archivos

  • NOTES.md
  • PROMPT.md
  • csx.json
  • requirements.txt
  • spec.json
  • src/__init__.py
  • src/client.py
  • test/__init__.py
  • test/contract.py

Descargar el artefacto de código fuente (tar.gz)

Código fuente

NOTES.md
# Notes: httpx Core APIs and Async Client Verification

## 1. Network Search Result
`search_known_solution` returned `NO_SAFE_MATCH` for the general `httpx` symbol coverage verification.

## 2. Release Pinned
- **Package**: `httpx 0.28.1`
- **PURL**: `pkg:pypi/httpx@0.28.1`

## 3. What This Sample Proves
This sample provides clean-room verification for the core components of `httpx` (version 0.28.1) running completely offline using `httpx.MockTransport`:
1. **Synchronous Client Execution**: `httpx.Client` correctly binds `MockTransport`, handles parameters, builds headers, and serializes/deserializes JSON payloads.
2. **Asynchronous Client Execution**: `httpx.AsyncClient` handles async request calls, manages async context lifecycle (`async with`), and streams response bytes through `aiter_bytes()`.
3. **Event Hooks**: `httpx.Client` invokes `request` and `response` event hooks synchronously in order during the request pipeline.
4. **URL Operations**: `httpx.URL` accurately parses URI structures, supports component extraction, and executes standard RFC 3986 relative path resolution through `.join()`.
5. **Error Hierarchy & Status Handling**: `Response.raise_for_status()` raises `httpx.HTTPStatusError` (inheriting from `httpx.HTTPError`, not `httpx.RequestError`), while keeping the payload accessible.
6. **Header Data Structures**: `httpx.Headers` provides case-insensitive access and multi-value header list support.
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 httpx in pkg:pypi/httpx@0.28.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/httpx@0.28.1
Demonstrate these symbols/APIs:
  - httpx
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:e422edbe98d8a166d393156f2e71c76242e51dc7b00cae95f6326353656e1716","constraints":{"executionContext":"python"},"contract":["httpx.Client with MockTransport executes synchronous HTTP requests, applies headers and query params, and decodes JSON responses offline.","httpx.AsyncClient with MockTransport executes asynchronous HTTP requests, supports async context managers, and streams response content via aiter_bytes.","httpx request and response event hooks execute synchronously during the request lifecycle to inspect or modify HTTP traffic.","httpx.URL parses URIs, exposes path and query components, and performs RFC 3986 reference resolution via join.","Response.raise_for_status raises httpx.HTTPStatusError on 4xx/5xx responses without consuming or invalidating response content.","httpx.Headers maintains case-insensitive header lookup and preserves discrete header formatting."],"goal":"verify httpx in pkg:pypi/httpx@0.28.1","kind":"HOW","packages":["pkg:pypi/httpx@0.28.1"],"schemaVersion":1,"symbols":["httpx"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","executionContext":"python","language":"python","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/httpx@0.28.1"],"schemaVersion":1,"subject":"pkg:pypi/httpx@0.28.1","symbols":["httpx"],"verifierAdapter":"python@1"}
requirements.txt
httpx==0.28.1
httpcore==1.0.9
h11==0.16.0
certifi==2026.7.22
idna==3.19
anyio==4.14.2
typing-extensions==4.16.0
spec.json
{
  "schemaVersion": 1,
  "goal": "verify httpx in pkg:pypi/httpx@0.28.1",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/httpx@0.28.1"
  ],
  "symbols": [
    "httpx"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/__init__.py
"""httpx verification package."""
src/client.py
"""Helper module demonstrating httpx Client, AsyncClient, and URL operations."""

from typing import Any, Callable, Dict, List, Optional
import httpx


def create_sync_client(handler: Callable[[httpx.Request], httpx.Response], base_url: str = "https://api.example.com") -> httpx.Client:
    """Create a synchronous httpx.Client configured with MockTransport."""
    return httpx.Client(
        transport=httpx.MockTransport(handler),
        base_url=base_url,
    )


def create_async_client(handler: Callable[[httpx.Request], httpx.Response], base_url: str = "https://api.example.com") -> httpx.AsyncClient:
    """Create an asynchronous httpx.AsyncClient configured with MockTransport."""
    return httpx.AsyncClient(
        transport=httpx.MockTransport(handler),
        base_url=base_url,
    )
test/__init__.py
"""Contract tests for httpx verification."""
test/contract.py
"""Contract tests proving httpx 0.28.1 core functionality."""

import asyncio
import json
from pathlib import Path
import sys

# Ensure project root is on sys.path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

import httpx
from src.client import create_async_client, create_sync_client


def test_sync_client_mock_transport() -> None:
    """httpx.Client with MockTransport executes synchronous HTTP requests, applies headers and query params, and decodes JSON responses offline."""
    def handler(request: httpx.Request) -> httpx.Response:
        assert request.headers["custom-header"] == "test-value"
        assert request.url.params["query_key"] == "query_val"
        body = json.loads(request.content.decode("utf-8"))
        assert body["hello"] == "world"
        return httpx.Response(
            200,
            json={"status": "ok", "received": body},
            headers={"resp-header": "received"},
        )

    with create_sync_client(handler) as client:
        response = client.post(
            "/test",
            params={"query_key": "query_val"},
            headers={"custom-header": "test-value"},
            json={"hello": "world"},
        )
        assert response.status_code == 200
        assert response.headers["resp-header"] == "received"
        data = response.json()
        assert data["status"] == "ok"
        assert data["received"] == {"hello": "world"}


def test_async_client_mock_transport() -> None:
    """httpx.AsyncClient with MockTransport executes asynchronous HTTP requests, supports async context managers, and streams response content via aiter_bytes."""
    async def run_async() -> None:
        def handler(request: httpx.Request) -> httpx.Response:
            if request.url.path == "/stream":
                return httpx.Response(
                    200,
                    stream=httpx.ByteStream(b"chunk1\nchunk2\nchunk3\n"),
                )
            return httpx.Response(200, json={"async": "success"})

        async with create_async_client(handler) as client:
            resp = await client.get("/async-test")
            assert resp.status_code == 200
            assert resp.json() == {"async": "success"}

            stream_resp = await client.get("/stream")
            chunks = []
            async for chunk in stream_resp.aiter_bytes():
                chunks.append(chunk)
            assert b"".join(chunks) == b"chunk1\nchunk2\nchunk3\n"

    asyncio.run(run_async())


def test_event_hooks() -> None:
    """httpx request and response event hooks execute synchronously during the request lifecycle to inspect or modify HTTP traffic."""
    hook_called = {"req": False, "resp": False}

    def on_request(request: httpx.Request) -> None:
        hook_called["req"] = True
        request.headers["x-hook-injected"] = "true"

    def on_response(response: httpx.Response) -> None:
        hook_called["resp"] = True
        assert response.status_code == 200

    def handler(request: httpx.Request) -> httpx.Response:
        assert request.headers["x-hook-injected"] == "true"
        return httpx.Response(200, text="hooked")

    client = httpx.Client(
        transport=httpx.MockTransport(handler),
        event_hooks={"request": [on_request], "response": [on_response]},
    )
    with client:
        resp = client.get("https://example.com/hook")
        assert resp.text == "hooked"
        assert hook_called["req"] is True
        assert hook_called["resp"] is True


def test_url_manipulation_and_rfc3986_join() -> None:
    """httpx.URL parses URIs, exposes path and query components, and performs RFC 3986 reference resolution via join."""
    url = httpx.URL("https://example.com:8080/path/to/resource?query=1#section")
    assert url.scheme == "https"
    assert url.host == "example.com"
    assert url.port == 8080
    assert url.path == "/path/to/resource"
    assert url.query == b"query=1"

    base = httpx.URL("https://example.com/api/v1/")
    joined = base.join("items")
    assert str(joined) == "https://example.com/api/v1/items"

    modified = url.copy_with(scheme="http", port=80)
    assert str(modified) == "http://example.com/path/to/resource?query=1#section"


def test_response_raise_for_status_and_content_preservation() -> None:
    """Response.raise_for_status raises httpx.HTTPStatusError on 4xx/5xx responses without consuming or invalidating response content."""
    def handler(request: httpx.Request) -> httpx.Response:
        return httpx.Response(
            404,
            json={"error": "resource not found", "code": 40401},
            headers={"content-type": "application/json"},
        )

    client = httpx.Client(transport=httpx.MockTransport(handler))
    with client:
        resp = client.get("https://example.com/missing")
        assert resp.status_code == 404

        try:
            resp.raise_for_status()
            assert False, "Expected HTTPStatusError"
        except httpx.HTTPStatusError as exc:
            assert exc.response.status_code == 404
            assert isinstance(exc, httpx.HTTPError)
            assert not isinstance(exc, httpx.RequestError)

        body = resp.json()
        assert body["error"] == "resource not found"
        assert body["code"] == 40401


def test_headers_case_insensitivity_and_structure() -> None:
    """httpx.Headers maintains case-insensitive header lookup and preserves discrete header formatting."""
    headers = httpx.Headers({"Content-Type": "application/json", "X-Custom-Header": "Value1"})
    assert headers["content-type"] == "application/json"
    assert headers["Content-Type"] == "application/json"
    assert headers["x-custom-header"] == "Value1"
    assert "x-custom-header" in headers
    assert "Content-Length" not in headers

    headers_multi = httpx.Headers([("Set-Cookie", "a=1"), ("Set-Cookie", "b=2")])
    cookie_list = headers_multi.get_list("Set-Cookie")
    assert cookie_list == ["a=1", "b=2"]


def main() -> None:
    test_sync_client_mock_transport()
    test_async_client_mock_transport()
    test_event_hooks()
    test_url_manipulation_and_rfc3986_join()
    test_response_raise_for_status_and_content_preservation()
    test_headers_case_insensitivity_and_structure()
    print("Contract pass: httpx 0.28.1 verification successful")


if __name__ == "__main__":
    main()

Seeder de origen

anónimo