CodeSampleX

샘플

httpcore2 2.10.0: ConnectionPool, request

검증된 샘플 — pypi httpcore2 2.10.0: ConnectionPool, request. python 3.12 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: httpcore2.URL parses scheme, host…

sha256:1a86f9b9ba15e46ff1492eb476e081754e4385e019ee44e16c109d5f43af947b

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

실행 증거

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

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 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 pkg:pypi/httpcore2@2.10.0
패키지
심벌
  • httpcore2.ConnectionPool
  • httpcore2.request
생성일
2026-08-28T08:48:04Z

컨트랙트

  1. httpcore2.URL parses scheme, host, port and target path
  2. httpcore2.ConnectionPool sends HTTP requests via network backend and returns Response with status and body
  3. httpcore2.ConnectionPool.request sends request and automatically closes response after reading content
  4. httpcore2.request sends synchronous HTTP GET and POST requests and returns Response
  5. httpcore2.request raises ConnectError or NetworkError when connecting to an unreachable port

파일

  • PROMPT.md
  • csx.json
  • pyproject.toml
  • requirements.txt
  • 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/httpcore2@2.10.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/httpcore2@2.10.0
Demonstrate these symbols/APIs:
  - httpcore2.ConnectionPool
  - httpcore2.request

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:e1186ded2041ab7a87d8b1f940f0e6485628b6695fdcf52da031b63a59872a91","contract":["httpcore2.URL parses scheme, host, port and target path","httpcore2.ConnectionPool sends HTTP requests via network backend and returns Response with status and body","httpcore2.ConnectionPool.request sends request and automatically closes response after reading content","httpcore2.request sends synchronous HTTP GET and POST requests and returns Response","httpcore2.request raises ConnectError or NetworkError when connecting to an unreachable port"],"goal":"verify pkg:pypi/httpcore2@2.10.0","kind":"HOW","packages":["pkg:pypi/httpcore2@2.10.0"],"schemaVersion":1,"symbols":["httpcore2.ConnectionPool","httpcore2.request"]},"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/httpcore2@2.10.0"],"schemaVersion":1,"subject":"pkg:pypi/httpcore2@2.10.0","symbols":["httpcore2.ConnectionPool","httpcore2.request"],"verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "verify-httpcore2"
version = "0.1.0"
dependencies = [
    "h11==0.16.0",
    "httpcore2==2.10.0",
    "truststore==0.10.4",
]
requirements.txt
h11==0.16.0
httpcore2==2.10.0
truststore==0.10.4
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:pypi/httpcore2@2.10.0",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/httpcore2@2.10.0"
  ],
  "symbols": [
    "httpcore2.ConnectionPool",
    "httpcore2.request"
  ]
}
test/contract.py
import httpcore2
import http.server
import threading


def test_url_parsing():
    url = httpcore2.URL("http://example.com:8080/path?query=1")
    assert url.scheme == b"http"
    assert url.host == b"example.com"
    assert url.port == 8080
    assert url.target == b"/path?query=1"


def test_connection_pool_mock_backend():
    body = b"Hello Pool Response"
    headers = [
        (b"Content-Type", b"text/plain"),
        (b"Content-Length", str(len(body)).encode("ascii")),
    ]
    header_block = b"".join(k + b": " + v + b"\r\n" for k, v in headers)
    raw_response = b"HTTP/1.1 200 OK\r\n" + header_block + b"\r\n" + body

    backend = httpcore2.MockBackend(buffer=[raw_response])
    pool = httpcore2.ConnectionPool(network_backend=backend)
    request = httpcore2.Request(
        "GET",
        "http://example.com/mock-endpoint",
        headers=[(b"host", b"example.com")],
    )

    response = pool.handle_request(request)
    assert response.status == 200
    headers_dict = dict(response.headers)
    assert headers_dict[b"Content-Type"] == b"text/plain"
    assert response.read() == body
    pool.close()


def test_connection_pool_request_helper():
    json_body = b'{"status": "success", "code": 201}'
    headers = [
        (b"Content-Type", b"application/json"),
        (b"Content-Length", str(len(json_body)).encode("ascii")),
    ]
    header_block = b"".join(k + b": " + v + b"\r\n" for k, v in headers)
    raw_response = b"HTTP/1.1 201 Created\r\n" + header_block + b"\r\n" + json_body

    backend = httpcore2.MockBackend(buffer=[raw_response])
    with httpcore2.ConnectionPool(network_backend=backend) as pool:
        response = pool.request("POST", "http://example.com/api/items", content=b"item-data")
        assert response.status == 201
        assert response.content == json_body


def test_httpcore_request_with_local_server():
    class TestHandler(http.server.BaseHTTPRequestHandler):
        def do_GET(self):
            self.send_response(200)
            self.send_header("Content-Type", "text/plain")
            content = b"local-get-ok"
            self.send_header("Content-Length", str(len(content)))
            self.end_headers()
            self.wfile.write(content)

        def do_POST(self):
            length = int(self.headers.get("Content-Length", 0))
            payload = self.rfile.read(length) if length > 0 else b""
            self.send_response(200)
            self.send_header("Content-Type", "application/octet-stream")
            self.send_header("Content-Length", str(len(payload)))
            self.end_headers()
            self.wfile.write(payload)

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

    server = http.server.HTTPServer(("127.0.0.1", 0), TestHandler)
    port = server.server_port
    thread = threading.Thread(target=server.serve_forever)
    thread.daemon = True
    thread.start()

    try:
        # GET request
        resp_get = httpcore2.request("GET", f"http://127.0.0.1:{port}/ping")
        assert resp_get.status == 200
        assert resp_get.content == b"local-get-ok"

        # POST request
        resp_post = httpcore2.request("POST", f"http://127.0.0.1:{port}/echo", content=b"echo-payload-bytes")
        assert resp_post.status == 200
        assert resp_post.content == b"echo-payload-bytes"
    finally:
        server.shutdown()


def test_error_handling_unreachable_port():
    try:
        httpcore2.request("GET", "http://127.0.0.1:1")
        assert False, "Expected ConnectError or NetworkError on unreachable port"
    except (httpcore2.ConnectError, httpcore2.NetworkError) as exc:
        assert isinstance(exc, (httpcore2.ConnectError, httpcore2.NetworkError))


def main():
    test_url_parsing()
    test_connection_pool_mock_backend()
    test_connection_pool_request_helper()
    test_httpcore_request_with_local_server()
    test_error_handling_unreachable_port()
    print("All contract assertions passed successfully.")


if __name__ == "__main__":
    main()

오리진 시더

익명