CodeSampleX

Exemple

starlette 1.4.1: exceptions.HTTPException

Échantillon vérifié pour pypi starlette 1.4.1: exceptions.HTTPException. Le contrat s'est exécuté sur python 3.12 · linux debian/x64 · docker et a réussi.

sha256:7ddd3a1b5abeb7221d1dc74d52d3e7524a2a7e96cb29aec3e235907d72b093f5

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré python linux 24 · ubuntu · glibc 2.39 x64 python python pip

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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-01

Cas

HOW
Objectif
verify starlette.exceptions.HTTPException in pkg:pypi/starlette@1.4.1
Paquets
Symboles
  • starlette.exceptions.HTTPException
Environnement
python
Créé
2026-09-01T22:00:55Z

Contrat

  1. HTTPException initializes with status_code, detail message, and optional custom headers
  2. Starlette exception handler catches HTTPException and returns configured response status and payload
  3. Default Starlette exception handling formats uncaught HTTPException into standard HTTP error responses

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

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 starlette.exceptions.HTTPException in pkg:pypi/starlette@1.4.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/starlette@1.4.1
Demonstrate these symbols/APIs:
  - starlette.exceptions.HTTPException

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:3d13568557ffbada1c88a07dafd1a2f07a84c9041f82349fc46418a96d87e822","contract":["HTTPException initializes with status_code, detail message, and optional custom headers","Starlette exception handler catches HTTPException and returns configured response status and payload","Default Starlette exception handling formats uncaught HTTPException into standard HTTP error responses"],"goal":"verify starlette.exceptions.HTTPException in pkg:pypi/starlette@1.4.1","kind":"HOW","packages":["pkg:pypi/starlette@1.4.1"],"schemaVersion":1,"symbols":["starlette.exceptions.HTTPException"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","language":"python","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/starlette@1.4.1"],"schemaVersion":1,"subject":"pkg:pypi/starlette@1.4.1","symbols":["starlette.exceptions.HTTPException"],"verifierAdapter":"python@1"}
requirements.txt
anyio==4.14.2
idna==3.19
starlette==1.4.1
typing-extensions==4.16.0
sample.py
"""Sample demonstrating HTTPException handling in Starlette."""

from typing import Any, Dict
from starlette.applications import Starlette
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route


async def get_item(request: Request) -> JSONResponse:
    """Return item details or raise HTTPException when not found."""
    item_id = request.path_params.get("item_id")
    if item_id == "missing":
        raise HTTPException(status_code=404, detail="Item not found")
    if item_id == "unauthorized":
        raise HTTPException(
            status_code=401,
            detail="Authentication required",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return JSONResponse({"item_id": item_id, "status": "available"})


async def custom_http_exception_handler(
    request: Request, exc: HTTPException
) -> JSONResponse:
    """Handle HTTPException by returning structured JSON error payload."""
    headers = dict(exc.headers) if exc.headers else {}
    return JSONResponse(
        {"error": exc.detail, "status_code": exc.status_code},
        status_code=exc.status_code,
        headers=headers,
    )


def create_app(with_custom_handler: bool = True) -> Starlette:
    """Create Starlette application with routes and optional custom exception handler."""
    routes = [
        Route("/items/{item_id}", get_item, methods=["GET"]),
    ]
    exception_handlers: Dict[Any, Any] = {}
    if with_custom_handler:
        exception_handlers[HTTPException] = custom_http_exception_handler

    return Starlette(routes=routes, exception_handlers=exception_handlers)


if __name__ == "__main__":
    app = create_app()
    print("Starlette application initialized with HTTPException handling.")
spec.json
{
  "schemaVersion": 1,
  "goal": "verify starlette.exceptions.HTTPException in pkg:pypi/starlette@1.4.1",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/starlette@1.4.1"
  ],
  "symbols": [
    "starlette.exceptions.HTTPException"
  ]
}
test/contract.py
"""Contract verification tests for starlette.exceptions.HTTPException."""

import asyncio
import json
import os
import sys
from typing import Any, Dict, List, Optional, Tuple

# 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 starlette.applications import Starlette
from starlette.exceptions import HTTPException
from sample import create_app


async def invoke_asgi(
    app: Starlette,
    method: str,
    path: str,
    body: bytes = b"",
    headers: Optional[List[Tuple[bytes, bytes]]] = None,
) -> Tuple[int, Dict[bytes, bytes], bytes]:
    """Helper to invoke ASGI application offline without network dependencies."""
    if headers is None:
        headers = [(b"content-type", b"application/json")]

    scope = {
        "type": "http",
        "http_version": "1.1",
        "method": method,
        "path": path,
        "raw_path": path.encode("latin-1"),
        "query_string": b"",
        "headers": headers,
    }

    sent_messages = []

    async def receive() -> Dict[str, Any]:
        return {"type": "http.request", "body": body, "more_body": False}

    async def send(message: Dict[str, Any]) -> None:
        sent_messages.append(message)

    await app(scope, receive, send)

    status_code = 0
    resp_headers = {}
    response_body = b""

    for msg in sent_messages:
        if msg["type"] == "http.response.start":
            status_code = msg["status"]
            resp_headers = dict(msg.get("headers", []))
        elif msg["type"] == "http.response.body":
            response_body += msg.get("body", b"")

    return status_code, resp_headers, response_body


def test_http_exception_attributes() -> None:
    """Assertion 1: HTTPException initializes with status_code, detail message, and optional custom headers."""
    exc = HTTPException(
        status_code=403,
        detail="Forbidden resource",
        headers={"X-Reason": "AccessDenied"},
    )
    assert exc.status_code == 403
    assert exc.detail == "Forbidden resource"
    assert exc.headers == {"X-Reason": "AccessDenied"}
    assert str(exc) == "403: Forbidden resource"


def test_custom_http_exception_handler() -> None:
    """Assertion 2: Starlette exception handler catches HTTPException and returns configured response status and payload."""
    app = create_app(with_custom_handler=True)

    async def run_test() -> None:
        # Test 404 response
        status, headers, body = await invoke_asgi(app, "GET", "/items/missing")
        assert status == 404, f"Expected 404, got {status}"
        assert b"application/json" in headers.get(b"content-type", b"")
        data = json.loads(body.decode("utf-8"))
        assert data == {"error": "Item not found", "status_code": 404}

        # Test 401 response with custom headers
        status, headers, body = await invoke_asgi(app, "GET", "/items/unauthorized")
        assert status == 401, f"Expected 401, got {status}"
        assert headers.get(b"www-authenticate") == b"Bearer"
        data = json.loads(body.decode("utf-8"))
        assert data == {"error": "Authentication required", "status_code": 401}

    asyncio.run(run_test())


def test_default_http_exception_handling() -> None:
    """Assertion 3: Default Starlette exception handling formats uncaught HTTPException into standard HTTP error responses."""
    app = create_app(with_custom_handler=False)

    async def run_test() -> None:
        status, headers, body = await invoke_asgi(app, "GET", "/items/missing")
        assert status == 404, f"Expected 404, got {status}"
        assert body.decode("utf-8") == "Item not found"

    asyncio.run(run_test())


def main() -> None:
    test_http_exception_attributes()
    test_custom_http_exception_handler()
    test_default_http_exception_handling()
    print("Starlette HTTPException contract verification passed.")


if __name__ == "__main__":
    main()

Seeder d'origine

anonyme