CodeSampleX

Exemple

requests 2.34.2: get

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

sha256:fe7f5352c95af2c8f4b2d3f0630542890e466b3981d9a86b16f80a55b501f6ff

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é linux 24 · ubuntu · glibc 2.39 x64 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-02

Cas

HOW
Objectif
verify requests.get in pkg:pypi/requests@2.34.2
Paquets
Symboles
  • requests.get
Créé
2026-09-02T10:35:36Z

Contrat

  1. requests.get sends HTTP GET request with query params, custom headers and decodes JSON response with status code
  2. requests.get retrieves decoded text and raw byte content from response
  3. requests.get handles HTTP redirects with allow_redirects configuration and tracks redirect history
  4. requests.get response raise_for_status raises HTTPError on 4xx status codes

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 requests.get in pkg:pypi/requests@2.34.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/requests@2.34.2
Demonstrate these symbols/APIs:
  - requests.get

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:6724b0628a92284cd3470d92c6bb3b799f0c08e5b00a3584f1ffad80fe652755","contract":["requests.get sends HTTP GET request with query params, custom headers and decodes JSON response with status code","requests.get retrieves decoded text and raw byte content from response","requests.get handles HTTP redirects with allow_redirects configuration and tracks redirect history","requests.get response raise_for_status raises HTTPError on 4xx status codes"],"goal":"verify requests.get in pkg:pypi/requests@2.34.2","kind":"HOW","packages":["pkg:pypi/requests@2.34.2"],"schemaVersion":1,"symbols":["requests.get"]},"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/requests@2.34.2"],"schemaVersion":1,"subject":"pkg:pypi/requests@2.34.2","symbols":["requests.get"],"verifierAdapter":"python@1"}
requirements.txt
requests==2.34.2
sample.py
"""Demonstration of HTTP GET requests using requests.get."""

from typing import Any, Dict, Optional
import requests


def fetch_json(
    url: str,
    params: Optional[Dict[str, Any]] = None,
    headers: Optional[Dict[str, str]] = None,
    timeout: float = 10.0,
) -> requests.Response:
    """Send an HTTP GET request and return the response."""
    return requests.get(url, params=params, headers=headers, timeout=timeout)


def fetch_text_content(
    url: str,
    headers: Optional[Dict[str, str]] = None,
    timeout: float = 10.0,
) -> str:
    """Send an HTTP GET request and return the decoded text."""
    response = requests.get(url, headers=headers, timeout=timeout)
    return response.text


def fetch_with_redirect_policy(
    url: str,
    allow_redirects: bool = True,
    timeout: float = 10.0,
) -> requests.Response:
    """Send an HTTP GET request with explicit redirect handling configuration."""
    return requests.get(url, allow_redirects=allow_redirects, timeout=timeout)
spec.json
{
  "schemaVersion": 1,
  "goal": "verify requests.get in pkg:pypi/requests@2.34.2",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/requests@2.34.2"
  ],
  "symbols": [
    "requests.get"
  ]
}
test/contract.py
"""Contract verification test for requests.get."""

import http.server
import os
import sys
import threading

# 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__))))

import requests
from sample import fetch_json, fetch_text_content, fetch_with_redirect_policy


class MockHTTPHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/api/data?query=search&limit=10":
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("X-Response-Id", "res-12345")
            self.send_header("Set-Cookie", "session=abcde; Path=/")
            self.end_headers()
            self.wfile.write(b'{"status": "ok", "items": [1, 2, 3]}')
        elif self.path == "/text/document":
            self.send_response(200)
            self.send_header("Content-Type", "text/plain; charset=utf-8")
            self.end_headers()
            self.wfile.write("sample response payload".encode("utf-8"))
        elif self.path == "/redirect/source":
            self.send_response(302)
            self.send_header("Location", "/api/data?query=search&limit=10")
            self.end_headers()
        elif self.path == "/error/not-found":
            self.send_response(404)
            self.send_header("Content-Type", "text/plain")
            self.end_headers()
            self.wfile.write(b"Resource Not Found")
        else:
            self.send_response(400)
            self.end_headers()

    def log_message(self, format, *args):
        # Suppress server access logs during tests
        pass


def test_requests_get_json_params_headers(base_url: str) -> None:
    """Assertion 1: requests.get sends HTTP GET request with query params, custom headers and decodes JSON response with status code."""
    url = f"{base_url}/api/data"
    params = {"query": "search", "limit": 10}
    headers = {"X-Client-Version": "1.0.0"}

    # Direct requests.get call
    resp = requests.get(url, params=params, headers=headers, timeout=5.0)
    assert resp.status_code == 200, f"Expected 200, got {resp.status_code}"
    assert resp.headers.get("X-Response-Id") == "res-12345"
    assert resp.cookies.get("session") == "abcde"
    json_data = resp.json()
    assert json_data == {"status": "ok", "items": [1, 2, 3]}

    # Helper function check
    sample_resp = fetch_json(url, params=params, headers=headers)
    assert sample_resp.status_code == 200
    assert sample_resp.json() == json_data


def test_requests_get_text_content(base_url: str) -> None:
    """Assertion 2: requests.get retrieves decoded text and raw byte content from response."""
    url = f"{base_url}/text/document"
    resp = requests.get(url, timeout=5.0)

    assert resp.status_code == 200
    assert resp.text == "sample response payload"
    assert resp.content == b"sample response payload"

    # Helper function check
    text = fetch_text_content(url)
    assert text == "sample response payload"


def test_requests_get_redirects(base_url: str) -> None:
    """Assertion 3: requests.get handles HTTP redirects with allow_redirects configuration and tracks redirect history."""
    url = f"{base_url}/redirect/source"

    # Follow redirect (default)
    resp_followed = requests.get(url, allow_redirects=True, timeout=5.0)
    assert resp_followed.status_code == 200
    assert len(resp_followed.history) == 1
    assert resp_followed.history[0].status_code == 302

    # Do not follow redirect
    resp_no_follow = fetch_with_redirect_policy(url, allow_redirects=False)
    assert resp_no_follow.status_code == 302
    assert len(resp_no_follow.history) == 0


def test_requests_get_raise_for_status(base_url: str) -> None:
    """Assertion 4: requests.get response raise_for_status raises HTTPError on 4xx status codes."""
    url = f"{base_url}/error/not-found"
    resp = requests.get(url, timeout=5.0)
    assert resp.status_code == 404

    raised = False
    try:
        resp.raise_for_status()
    except requests.exceptions.HTTPError as exc:
        raised = True
        assert exc.response.status_code == 404

    assert raised, "raise_for_status() should raise HTTPError for 404 response"


def main() -> None:
    server = http.server.HTTPServer(("127.0.0.1", 0), MockHTTPHandler)
    port = server.server_address[1]
    server_thread = threading.Thread(target=server.serve_forever, daemon=True)
    server_thread.start()

    base_url = f"http://127.0.0.1:{port}"
    try:
        test_requests_get_json_params_headers(base_url)
        test_requests_get_text_content(base_url)
        test_requests_get_redirects(base_url)
        test_requests_get_raise_for_status(base_url)
        print("All contract assertions passed.")
    finally:
        server.shutdown()
        server.server_close()


if __name__ == "__main__":
    main()

Seeder d'origine

anonyme