CodeSampleX

Exemple

urllib3 2.7.0: exceptions.HTTPError

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

sha256:43e39704e0f6a84c334679d2b7eec93280fa2b24905d2b8d3b612c02a641ad4e

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-06

Cas

HOW
Objectif
verify urllib3.exceptions.HTTPError in pkg:pypi/urllib3@2.7.0
Paquets
Symboles
  • urllib3.exceptions.HTTPError
Créé
2026-09-06T01:12:31Z

Contrat

  1. urllib3.exceptions.HTTPError inherits from Exception and is the base class for urllib3 operational errors
  2. core exception categories including PoolError, RequestError, TimeoutError, and SSLError inherit from HTTPError
  3. catching urllib3.exceptions.HTTPError intercepts pool-level errors including ClosedPoolError
  4. catching urllib3.exceptions.HTTPError intercepts request-level errors including MaxRetryError
  5. catching urllib3.exceptions.HTTPError intercepts URL parsing errors including URLSchemeUnknown
  6. urllib3.exceptions.HTTPWarning inherits from Warning and does not inherit from HTTPError

Fichiers

  • PROMPT.md
  • csx.json
  • pyproject.toml
  • 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 urllib3.exceptions.HTTPError in pkg:pypi/urllib3@2.7.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/urllib3@2.7.0
Demonstrate these symbols/APIs:
  - urllib3.exceptions.HTTPError

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:a1e855b1eb1dc35613db87986564ee4fc5e11ad3f8631c976dd7ed3f7ed72565","contract":["urllib3.exceptions.HTTPError inherits from Exception and is the base class for urllib3 operational errors","core exception categories including PoolError, RequestError, TimeoutError, and SSLError inherit from HTTPError","catching urllib3.exceptions.HTTPError intercepts pool-level errors including ClosedPoolError","catching urllib3.exceptions.HTTPError intercepts request-level errors including MaxRetryError","catching urllib3.exceptions.HTTPError intercepts URL parsing errors including URLSchemeUnknown","urllib3.exceptions.HTTPWarning inherits from Warning and does not inherit from HTTPError"],"goal":"verify urllib3.exceptions.HTTPError in pkg:pypi/urllib3@2.7.0","kind":"HOW","packages":["pkg:pypi/urllib3@2.7.0"],"schemaVersion":1,"symbols":["urllib3.exceptions.HTTPError"]},"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/urllib3@2.7.0"],"schemaVersion":1,"subject":"pkg:pypi/urllib3@2.7.0","symbols":["urllib3.exceptions.HTTPError"],"verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "verify-urllib3-httperror"
version = "0.1.0"
dependencies = [
    "urllib3==2.7.0",
]
requirements.txt
urllib3==2.7.0
sample.py
"""Demonstration of urllib3.exceptions.HTTPError usage and exception handling."""

from __future__ import annotations

from typing import Any, Callable, Tuple
import urllib3
import urllib3.exceptions as ue


def is_http_error(exc: BaseException) -> bool:
    """Return True if the given exception is an instance of urllib3.exceptions.HTTPError."""
    return isinstance(exc, ue.HTTPError)


def catch_http_error(action: Callable[[], Any]) -> Tuple[bool, str]:
    """Execute action and catch urllib3.exceptions.HTTPError.

    Returns a tuple of (caught_flag, error_class_name).
    """
    try:
        action()
        return False, "None"
    except ue.HTTPError as exc:
        return True, type(exc).__name__


def trigger_closed_pool_error(pool: urllib3.HTTPConnectionPool) -> None:
    """Attempt a request on a closed connection pool, raising ClosedPoolError."""
    pool.close()
    pool.request("GET", "/")


def create_max_retry_error(pool: urllib3.HTTPConnectionPool, url: str) -> ue.MaxRetryError:
    """Construct a MaxRetryError instance with underlying cause."""
    cause = Exception("Connection refused")
    return ue.MaxRetryError(pool, url, reason=cause)


def trigger_unknown_scheme_error(url: str) -> None:
    """Attempt a request with an unsupported scheme, raising URLSchemeUnknown."""
    pm = urllib3.PoolManager()
    try:
        pm.request("GET", url)
    finally:
        pm.clear()


def is_warning_an_http_error() -> bool:
    """Check whether HTTPWarning is considered an HTTPError."""
    return issubclass(ue.HTTPWarning, ue.HTTPError)
spec.json
{
  "schemaVersion": 1,
  "goal": "verify urllib3.exceptions.HTTPError in pkg:pypi/urllib3@2.7.0",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/urllib3@2.7.0"
  ],
  "symbols": [
    "urllib3.exceptions.HTTPError"
  ]
}
test/contract.py
"""Contract verification test for urllib3.exceptions.HTTPError in pkg:pypi/urllib3@2.7.0."""

from __future__ import annotations

import os
import sys

# Ensure root directory is on sys.path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import urllib3
import urllib3.exceptions as ue
from sample import (
    catch_http_error,
    create_max_retry_error,
    is_http_error,
    is_warning_an_http_error,
    trigger_closed_pool_error,
    trigger_unknown_scheme_error,
)


def test_base_inheritance_and_classification() -> None:
    """Assertion 1: urllib3.exceptions.HTTPError inherits from Exception and is the base class for urllib3 operational errors."""
    assert issubclass(ue.HTTPError, Exception), "HTTPError must inherit from Exception"
    assert issubclass(ue.HTTPError, BaseException), "HTTPError must inherit from BaseException"

    base_instance = ue.HTTPError("custom error message")
    assert str(base_instance) == "custom error message", "HTTPError str representation should match message"
    assert is_http_error(base_instance) is True, "HTTPError instance must be recognized as HTTPError"
    assert is_http_error(ValueError("unrelated")) is False, "ValueError must not be recognized as HTTPError"


def test_core_exception_categories() -> None:
    """Assertion 2: core exception categories including PoolError, RequestError, TimeoutError, and SSLError inherit from HTTPError."""
    assert issubclass(ue.PoolError, ue.HTTPError), "PoolError must inherit from HTTPError"
    assert issubclass(ue.RequestError, ue.HTTPError), "RequestError must inherit from HTTPError"
    assert issubclass(ue.TimeoutError, ue.HTTPError), "TimeoutError must inherit from HTTPError"
    assert issubclass(ue.SSLError, ue.HTTPError), "SSLError must inherit from HTTPError"
    assert issubclass(ue.ProxyError, ue.HTTPError), "ProxyError must inherit from HTTPError"
    assert issubclass(ue.DecodeError, ue.HTTPError), "DecodeError must inherit from HTTPError"


def test_closed_pool_error_handling() -> None:
    """Assertion 3: catching urllib3.exceptions.HTTPError intercepts pool-level errors including ClosedPoolError."""
    pool = urllib3.HTTPConnectionPool("127.0.0.1", 80)
    try:
        caught, err_name = catch_http_error(lambda: trigger_closed_pool_error(pool))
        assert caught is True, "ClosedPoolError must be caught by except HTTPError"
        assert err_name == "ClosedPoolError", f"Expected ClosedPoolError, got {err_name}"
        assert issubclass(ue.ClosedPoolError, ue.HTTPError), "ClosedPoolError must be subclass of HTTPError"
    finally:
        pool.close()


def test_max_retry_error_handling() -> None:
    """Assertion 4: catching urllib3.exceptions.HTTPError intercepts request-level errors including MaxRetryError."""
    pool = urllib3.HTTPConnectionPool("example.com", 80)
    target_url = "http://example.com/api/test"
    try:
        def raise_retry() -> None:
            raise create_max_retry_error(pool, target_url)

        caught, err_name = catch_http_error(raise_retry)
        assert caught is True, "MaxRetryError must be caught by except HTTPError"
        assert err_name == "MaxRetryError", f"Expected MaxRetryError, got {err_name}"
        assert issubclass(ue.MaxRetryError, ue.HTTPError), "MaxRetryError must be subclass of HTTPError"
    finally:
        pool.close()


def test_unknown_scheme_error_handling() -> None:
    """Assertion 5: catching urllib3.exceptions.HTTPError intercepts URL parsing errors including URLSchemeUnknown."""
    unsupported_url = "unsupported-scheme://localhost/api"
    caught, err_name = catch_http_error(lambda: trigger_unknown_scheme_error(unsupported_url))
    assert caught is True, "URLSchemeUnknown must be caught by except HTTPError"
    assert err_name == "URLSchemeUnknown", f"Expected URLSchemeUnknown, got {err_name}"
    assert issubclass(ue.URLSchemeUnknown, ue.HTTPError), "URLSchemeUnknown must be subclass of HTTPError"


def test_warning_hierarchy_distinction() -> None:
    """Assertion 6: urllib3.exceptions.HTTPWarning inherits from Warning and does not inherit from HTTPError."""
    assert issubclass(ue.HTTPWarning, Warning), "HTTPWarning must inherit from Warning"
    assert not issubclass(ue.HTTPWarning, ue.HTTPError), "HTTPWarning must not inherit from HTTPError"
    assert not issubclass(ue.InsecureRequestWarning, ue.HTTPError), "InsecureRequestWarning must not inherit from HTTPError"
    assert is_warning_an_http_error() is False, "is_warning_an_http_error must return False"


def main() -> None:
    test_base_inheritance_and_classification()
    test_core_exception_categories()
    test_closed_pool_error_handling()
    test_max_retry_error_handling()
    test_unknown_scheme_error_handling()
    test_warning_hierarchy_distinction()
    print("All contract assertions passed.")


if __name__ == "__main__":
    main()

Seeder d'origine

anonyme