CodeSampleX

샘플

httpx2 2.10.0: httpx2

검증된 샘플 — pypi httpx2 2.10.0: httpx2. python 3.12 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: assert httpx2.__version__ is 2.10.0 and exports core…

sha256:35d74d569599a297bafe36fef9c4efb5fd6fa045260b0aacb73e091339be468d

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 python linux 24 · ubuntu · glibc 2.39 x64 python python pip

검증 실행 환경

환경 컨트랙트 단계 실행일
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-28

케이스

HOW
목표
verify httpx2 in pkg:pypi/httpx2@2.10.0
패키지
심벌
  • httpx2
환경
python
생성일
2026-08-28T06:37:05Z

컨트랙트

  1. assert httpx2.__version__ is 2.10.0 and exports core client and transport interfaces
  2. assert Client with MockTransport dispatches requests, parses JSON, and passes custom headers offline
  3. assert response.raise_for_status() raises HTTPStatusError inheriting from HTTPError on 4xx status codes
  4. assert Headers and QueryParams provide case-insensitive access and URL-encoded query formatting
  5. assert ServerSentEvent parses event, data, id, and retry properties
  6. assert alias_httpx() aliases httpx and httpcore module imports process-wide to httpx2 and httpcore2

파일

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

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# httpx2 Core Client, MockTransport, and Alias Semantics

## 1. What `search_known_solution` Answered
- `search_known_solution` returned `NO_SAFE_MATCH` for the general `httpx2` root symbol verification.
- Existing samples focus on specific subsets (such as `sha256:632bd37aef7f7583aaef7866ba216cfa65df1a49a27b1214814cc48a92389c40` on `URL.params` merge semantics).

## 2. Pinned Release
- `httpx2` == 2.10.0 (PyPI)
- `httpcore2` == 2.10.0
- `idna` == 3.18
- `truststore` == 0.10.4
- `anyio` == 4.13.0
- `h11` == 0.16.0
- `typing-extensions` == 4.15.0

## 3. What a Naive Model Would Have Written Instead
- Naive code attempting to mock HTTP dispatch in tests attempts to mock `httpx2.Client.send` directly or monkeypatch socket calls instead of using `httpx2.MockTransport(handler)` with an offline request handler.
- Naive code expects `httpx2.HTTPStatusError` to be a standalone exception unrelated to `httpx2.HTTPError`, or catches generic `Exception` without verifying the underlying response.
- Naive code migrating from `httpx` to `httpx2` tries to manually re-export or rewrite all legacy third-party dependency imports instead of invoking `httpx2.alias_httpx()`.

## 4. How the Wrong Version Fails
- Mocking socket-level calls fails when transport-level connection pooling and HTTP/2 framing are enabled.
- Forgetting that `alias_httpx()` must be invoked before importing legacy modules leads to duplicate class definitions and broken `isinstance` checks across libraries.
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 httpx2 in pkg:pypi/httpx2@2.10.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/httpx2@2.10.0
Demonstrate these symbols/APIs:
  - httpx2

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:9e6a6179faebf2ae484df14828e6f7fe9e3792aac95254e770062eb73e5e574b","contract":["assert httpx2.__version__ is 2.10.0 and exports core client and transport interfaces","assert Client with MockTransport dispatches requests, parses JSON, and passes custom headers offline","assert response.raise_for_status() raises HTTPStatusError inheriting from HTTPError on 4xx status codes","assert Headers and QueryParams provide case-insensitive access and URL-encoded query formatting","assert ServerSentEvent parses event, data, id, and retry properties","assert alias_httpx() aliases httpx and httpcore module imports process-wide to httpx2 and httpcore2"],"goal":"verify httpx2 in pkg:pypi/httpx2@2.10.0","kind":"HOW","packages":["pkg:pypi/httpx2@2.10.0"],"schemaVersion":1,"symbols":["httpx2"]},"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/httpx2@2.10.0"],"schemaVersion":1,"subject":"pkg:pypi/httpx2@2.10.0","symbols":["httpx2"],"verifierAdapter":"python@1"}
requirements.txt
httpx2==2.10.0
httpcore2==2.10.0
idna==3.18
truststore==0.10.4
anyio==4.13.0
h11==0.16.0
typing-extensions==4.15.0
spec.json
{
  "schemaVersion": 1,
  "goal": "verify httpx2 in pkg:pypi/httpx2@2.10.0",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/httpx2@2.10.0"
  ],
  "symbols": [
    "httpx2"
  ]
}
src/__init__.py
"""httpx2 core demonstration module."""
src/client.py
"""Reference helper implementation demonstrating httpx2 usage."""

from __future__ import annotations

from typing import Any, Callable
import httpx2


def create_mock_client(
    handler: Callable[[httpx2.Request], httpx2.Response],
    base_url: str = "https://example.com",
) -> httpx2.Client:
    """Create an httpx2.Client configured with a MockTransport for offline testing."""
    transport = httpx2.MockTransport(handler)
    return httpx2.Client(transport=transport, base_url=base_url)


def execute_json_request(
    client: httpx2.Client,
    method: str,
    path: str,
    json_data: dict[str, Any] | None = None,
    headers: dict[str, str] | None = None,
) -> httpx2.Response:
    """Send a request and validate response status."""
    response = client.request(method=method, url=path, json=json_data, headers=headers)
    return response
test/__init__.py
"""Test package."""
test/contract.py
import sys
from pathlib import Path

# Ensure src is importable
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

import httpx2
from src.client import create_mock_client, execute_json_request

# ---------------------------------------------------------------------------
# 1. Package metadata and core export verification
# ---------------------------------------------------------------------------
assert httpx2.__version__ == "2.10.0", f"Expected version 2.10.0, got {httpx2.__version__}"
assert hasattr(httpx2, "Client"), "httpx2 must export Client"
assert hasattr(httpx2, "AsyncClient"), "httpx2 must export AsyncClient"
assert hasattr(httpx2, "Request"), "httpx2 must export Request"
assert hasattr(httpx2, "Response"), "httpx2 must export Response"
assert hasattr(httpx2, "MockTransport"), "httpx2 must export MockTransport"
assert hasattr(httpx2, "Headers"), "httpx2 must export Headers"
assert hasattr(httpx2, "QueryParams"), "httpx2 must export QueryParams"
assert hasattr(httpx2, "ServerSentEvent"), "httpx2 must export ServerSentEvent"
assert hasattr(httpx2, "alias_httpx"), "httpx2 must export alias_httpx"

# ---------------------------------------------------------------------------
# 2. MockTransport request dispatch and JSON handling
# ---------------------------------------------------------------------------
dispatched_requests = []


def mock_handler(request: httpx2.Request) -> httpx2.Response:
    dispatched_requests.append(request)
    if request.url.path == "/api/items":
        return httpx2.Response(
            200,
            json={"items": ["alpha", "beta"], "received_header": request.headers.get("x-request-id")},
            headers={"Content-Type": "application/json", "X-Custom-Server": "mock-v2"},
        )
    elif request.url.path == "/api/error":
        return httpx2.Response(404, json={"detail": "Item not found"})
    return httpx2.Response(200, text="fallback")


client = create_mock_client(mock_handler, base_url="https://example.com")

response = execute_json_request(
    client,
    method="POST",
    path="/api/items",
    json_data={"query": "test"},
    headers={"X-Request-ID": "req-999"},
)

assert response.status_code == 200
assert response.is_success is True
assert response.headers.get("x-custom-server") == "mock-v2"
data = response.json()
assert data["items"] == ["alpha", "beta"]
assert data["received_header"] == "req-999"

# ---------------------------------------------------------------------------
# 3. HTTPStatusError and HTTPError exception hierarchy
# ---------------------------------------------------------------------------
error_resp = execute_json_request(client, method="GET", path="/api/error")
assert error_resp.status_code == 404
assert error_resp.is_error is True

try:
    error_resp.raise_for_status()
    raise AssertionError("Expected HTTPStatusError on 404 response")
except httpx2.HTTPStatusError as exc:
    assert exc.response.status_code == 404
    assert isinstance(exc, httpx2.HTTPError), "HTTPStatusError must inherit from HTTPError"
    assert isinstance(exc, httpx2.RequestError) is False

# ---------------------------------------------------------------------------
# 4. Headers and QueryParams immutability and formatting
# ---------------------------------------------------------------------------
headers = httpx2.Headers({"Authorization": "Bearer token-xyz", "content-type": "application/json"})
assert headers["authorization"] == "Bearer token-xyz"
assert headers.get("AUTHORIZATION") == "Bearer token-xyz"
assert "Content-Type" in headers

params = httpx2.QueryParams({"search": "python", "page": "1", "tags": "web"})
assert str(params) == "search=python&page=1&tags=web"
assert params["search"] == "python"
assert params.get("page") == "1"

# ---------------------------------------------------------------------------
# 5. ServerSentEvent field parsing
# ---------------------------------------------------------------------------
sse_event = httpx2.ServerSentEvent(
    event="message",
    data="payload-data-line",
    id="event-idx-1",
    retry=3000,
)
assert sse_event.event == "message"
assert sse_event.data == "payload-data-line"
assert sse_event.id == "event-idx-1"
assert sse_event.retry == 3000

# ---------------------------------------------------------------------------
# 6. Process-wide alias_httpx() verification
# ---------------------------------------------------------------------------
assert callable(httpx2.alias_httpx)
httpx2.alias_httpx()

# Now importing httpx should resolve to httpx2 classes
import httpx  # noqa: E402

assert httpx.Client is httpx2.Client, "httpx.Client should alias to httpx2.Client"
assert httpx.Response is httpx2.Response, "httpx.Response should alias to httpx2.Response"
assert httpx.__version__ == "2.10.0"

print("CONTRACT PASS: httpx2 2.10.0 contracts verified offline successfully.")

오리진 시더

익명