Ejemplo
httpx 0.28.1: Test code that calls an HTTP API with httpx, with no network and no monkeypatching
Muestra verificada para pypi httpx 0.28.1: Test code that calls an HTTP API with httpx, with no network and no monkeypatching. El contrato se ejecutó en…
sha256:cb3957bd87d8069f1852e993cc872f799d4655060485fae85a1bb8bde180b5ce
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
- 3
- Claves de firma que lo compilaron
- 2
Entorno declarado
python 3.12 linux x64 python 3.12 python pip
Entornos de las ejecuciones de verificación
| Entorno | Contrato | Etapas | Ejecución |
|---|---|---|---|
| python 3.12 · linux alpine/x64 · docker ed25519:a2ec939a4c60e243 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · pypi@1 |
2026-08-14 |
| python 3.12 · linux alpine/x64 · docker ed25519:a2ec939a4c60e243 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · pypi@1 |
2026-08-14 |
| python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · pypi@1 |
2026-08-17 |
Caso
HOW- Objetivo
- Test code that calls an HTTP API with httpx, with no network and no monkeypatching
- Paquetes
- Símbolos
-
- httpx.MockTransport
- httpx.Client
- Response.raise_for_status
- httpx.WSGITransport
- Entorno
- python 3.12
- Creado
- 2026-08-14T06:15:10Z
Contrato
- assert MockTransport serves a real Client so base_url and params still apply
- assert raise_for_status raises HTTPStatusError and leaves the body readable
- assert the app= shortcut was removed in favour of WSGITransport and ASGITransport
- assert httpx defaults to a 5 second timeout and does not follow redirects
Archivos
- csx.json
- requirements.txt
- src/__init__.py
- src/api.py
- test/contract.py
Código fuente
{"case":{"caseId":"case:sha256:317fbbbe12d23cde30b2894d9f3c22b676bef4e12dad547b7f0cb8b398318a2c","constraints":{"runtime":"python"},"contract":["assert MockTransport serves a real Client so base_url and params still apply","assert raise_for_status raises HTTPStatusError and leaves the body readable","assert the app= shortcut was removed in favour of WSGITransport and ASGITransport","assert httpx defaults to a 5 second timeout and does not follow redirects"],"goal":"Test code that calls an HTTP API with httpx, with no network and no monkeypatching","kind":"HOW","packages":["pkg:pypi/httpx@0.28.1"],"schemaVersion":1,"symbols":["httpx.MockTransport","httpx.Client","Response.raise_for_status","httpx.WSGITransport"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","runtimeVersion":"3.12","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/httpx@0.28.1"],"schemaVersion":1,"symbols":["httpx.MockTransport","httpx.Client","Response.raise_for_status","httpx.WSGITransport"],"verifierAdapter":"pypi@1"}
httpx==0.28.1
httpcore==1.0.9
h11==0.16.0
certifi==2025.10.5
idna==3.11
anyio==4.11.0
sniffio==1.3.1
"""Testing HTTP code with httpx without touching the network, and the two
defaults that differ from requests.
MockTransport takes a plain function from Request to Response, so the whole
client — base_url, params, headers, raise_for_status — is exercised for
real and nothing is monkeypatched. That is the part worth copying.
The `app=` shortcut people reach for first was removed in httpx 0.28;
WSGITransport and ASGITransport are the replacements, and they are what
MockTransport sits beside.
Two defaults that silently change behaviour when porting from requests:
httpx applies a 5 second timeout where requests waits forever, and httpx
does NOT follow redirects where requests does.
"""
import httpx
def build_client(handler) -> httpx.Client:
"""A client that never opens a socket, with everything else intact."""
return httpx.Client(
transport=httpx.MockTransport(handler),
base_url="https://api.example.com",
)
def fetch_items(client: httpx.Client, page: int) -> dict:
response = client.get("/items", params={"page": str(page)})
response.raise_for_status()
return response.json()
import inspect
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import httpx
from src.api import build_client, fetch_items
def handler(request: httpx.Request) -> httpx.Response:
if request.url.path == "/boom":
return httpx.Response(500, json={"error": "nope"})
return httpx.Response(200, json={"path": request.url.path,
"q": dict(request.url.params)})
client = build_client(handler)
# The client is real: base_url, params and json decoding all run.
assert fetch_items(client, 2) == {"path": "/items", "q": {"page": "2"}}
# raise_for_status raises HTTPStatusError, and the body is still readable
# afterwards — the response is not consumed by the check.
failed = client.get("/boom")
try:
failed.raise_for_status()
raise AssertionError("500 should raise")
except httpx.HTTPStatusError as exc:
assert exc.response.status_code == 500
assert failed.json() == {"error": "nope"}
# On success it returns the response, so it chains.
assert isinstance(client.get("/items").raise_for_status(), httpx.Response)
# The app= shortcut is gone as of 0.28. Passing it now is a TypeError, not
# a deprecation, and the transports are the replacement.
assert "app" not in inspect.signature(httpx.Client.__init__).parameters
assert hasattr(httpx, "WSGITransport") and hasattr(httpx, "ASGITransport")
# The two defaults that differ from requests, stated as assertions because
# both change behaviour without changing any of your code.
assert httpx.Client().timeout == httpx.Timeout(5.0)
assert httpx.Client().follow_redirects is False
print("contract ok:", httpx.__version__)