CodeSampleX

Пример

requests 2.34.2: models.Response

Проверенный пример — pypi requests 2.34.2: models.Response. Контракт выполнен на python 3.12 · linux debian/x64 · docker и пройден.

sha256:a322a2c8901f51a51334d14da7b213e47daea40b8ddf931ab82cbdf2d9eb055d

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 pip

Среды запусков проверки

Окружение Контракт Этапы Запуск
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-05

Кейс

HOW
Цель
verify requests.models.Response in pkg:pypi/requests@2.34.2
Пакеты
Символы
  • requests.models.Response
Создан
2026-09-05T19:48:21Z

Контракт

  1. assert Response stores status_code, evaluates ok boolean flag, and decodes content to text
  2. assert Response decodes JSON payload via json method and handles dictionary structures
  3. assert Response evaluates is_redirect and is_permanent_redirect flags based on status code and Location header
  4. assert Response raise_for_status succeeds for 2xx responses and raises HTTPError on 4xx and 5xx

Файлы

  • PROMPT.md
  • csx.json
  • pyproject.toml
  • requirements.txt
  • sample.py
  • 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 requests.models.Response 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.models.Response

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:8196740d233b2f9625b9abe4de7ed198072d25be02c50dd69740083ac280128d","contract":["assert Response stores status_code, evaluates ok boolean flag, and decodes content to text","assert Response decodes JSON payload via json method and handles dictionary structures","assert Response evaluates is_redirect and is_permanent_redirect flags based on status code and Location header","assert Response raise_for_status succeeds for 2xx responses and raises HTTPError on 4xx and 5xx"],"goal":"verify requests.models.Response in pkg:pypi/requests@2.34.2","kind":"HOW","packages":["pkg:pypi/requests@2.34.2"],"schemaVersion":1,"symbols":["requests.models.Response"]},"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.models.Response"],"verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "verify-requests-models-response"
version = "0.1.0"
dependencies = [
    "requests==2.34.2",
]
requirements.txt
requests==2.34.2
sample.py
"""Demonstration of requests.models.Response."""

from typing import Any, Dict, Optional, Tuple
from requests.models import Response


def create_response(
    status_code: int = 200,
    content: bytes = b"",
    headers: Optional[Dict[str, str]] = None,
    encoding: str = "utf-8",
    url: str = "http://localhost/test",
) -> Response:
    """Create and initialize a requests.models.Response instance."""
    response = Response()
    response.status_code = status_code
    response._content = content
    response.encoding = encoding
    response.url = url
    if headers:
        response.headers.update(headers)
    return response


def is_response_ok(response: Response) -> bool:
    """Check whether the response was successful (HTTP status < 400)."""
    return response.ok


def get_response_json(response: Response) -> Any:
    """Parse JSON body from response."""
    return response.json()


def get_redirect_status(response: Response) -> Tuple[bool, bool]:
    """Return tuple of (is_redirect, is_permanent_redirect)."""
    return response.is_redirect, response.is_permanent_redirect


def ensure_successful_status(response: Response) -> None:
    """Validate status code and raise HTTPError if request failed."""
    response.raise_for_status()
spec.json
{
  "schemaVersion": 1,
  "goal": "verify requests.models.Response in pkg:pypi/requests@2.34.2",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/requests@2.34.2"
  ],
  "symbols": [
    "requests.models.Response"
  ]
}
test/contract.py
"""Contract verification test for requests.models.Response in pkg:pypi/requests@2.34.2."""

import os
import sys

# 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 requests.models import Response
from sample import (
    create_response,
    ensure_successful_status,
    get_redirect_status,
    get_response_json,
    is_response_ok,
)


def test_response_status_and_text() -> None:
    """Assertion 1: assert Response stores status_code, evaluates ok boolean flag, and decodes content to text."""
    resp = create_response(status_code=200, content=b"Hello, Response!", encoding="utf-8")

    assert isinstance(resp, Response), f"Expected Response instance, got {type(resp)}"
    assert resp.status_code == 200, f"Expected 200, got {resp.status_code}"
    assert resp.ok is True, "Response with status 200 must have ok=True"
    assert is_response_ok(resp) is True
    assert resp.text == "Hello, Response!"
    assert resp.content == b"Hello, Response!"

    resp_bad = create_response(status_code=500, content=b"Server error")
    assert resp_bad.status_code == 500
    assert resp_bad.ok is False, "Response with status 500 must have ok=False"
    assert is_response_ok(resp_bad) is False


def test_response_json_decoding() -> None:
    """Assertion 2: assert Response decodes JSON payload via json method and handles dictionary structures."""
    payload = b'{"name": "requests-model", "count": 10, "active": true}'
    headers = {"Content-Type": "application/json"}
    resp = create_response(status_code=200, content=payload, headers=headers)

    parsed = resp.json()
    assert parsed == {"name": "requests-model", "count": 10, "active": True}

    sample_parsed = get_response_json(resp)
    assert sample_parsed == parsed


def test_response_redirect_flags() -> None:
    """Assertion 3: assert Response evaluates is_redirect and is_permanent_redirect flags based on status code and Location header."""
    # Permanent redirect (301) with Location header
    resp_301 = create_response(status_code=301, headers={"Location": "http://localhost/new-location"})
    assert resp_301.is_redirect is True
    assert resp_301.is_permanent_redirect is True
    assert get_redirect_status(resp_301) == (True, True)

    # Temporary redirect (302) with Location header
    resp_302 = create_response(status_code=302, headers={"Location": "http://localhost/temp-location"})
    assert resp_302.is_redirect is True
    assert resp_302.is_permanent_redirect is False
    assert get_redirect_status(resp_302) == (True, False)

    # Redirect status code without Location header is not considered redirect by requests
    resp_302_no_loc = create_response(status_code=302)
    assert resp_302_no_loc.is_redirect is False
    assert resp_302_no_loc.is_permanent_redirect is False

    # Non-redirect status (200)
    resp_200 = create_response(status_code=200)
    assert resp_200.is_redirect is False
    assert resp_200.is_permanent_redirect is False


def test_response_raise_for_status() -> None:
    """Assertion 4: assert Response raise_for_status succeeds for 2xx responses and raises HTTPError on 4xx and 5xx."""
    resp_200 = create_response(status_code=200)
    # Should not raise
    resp_200.raise_for_status()
    ensure_successful_status(resp_200)

    # Client error (404)
    resp_404 = create_response(status_code=404, url="http://localhost/missing")
    raised_404 = False
    try:
        resp_404.raise_for_status()
    except requests.exceptions.HTTPError as exc:
        raised_404 = True
        assert exc.response.status_code == 404
    assert raised_404, "raise_for_status() must raise HTTPError on 404"

    # Server error (503)
    resp_503 = create_response(status_code=503, url="http://localhost/error")
    raised_503 = False
    try:
        ensure_successful_status(resp_503)
    except requests.exceptions.HTTPError as exc:
        raised_503 = True
        assert exc.response.status_code == 503
    assert raised_503, "ensure_successful_status() must raise HTTPError on 503"


def main() -> None:
    test_response_status_and_text()
    test_response_json_decoding()
    test_response_redirect_flags()
    test_response_raise_for_status()
    print("All contract assertions passed.")


if __name__ == "__main__":
    main()

Исходный сидер

аноним