CodeSampleX

示例

urllib3 2.7.0: exceptions

已验证示例 — pypi urllib3 2.7.0: exceptions. contract 在 python 3.12 · linux debian/x64 · docker 上运行并通过: urllib3.exceptions.HTTPError is the base exception class…

sha256:c9efc9ce8125914dd0b21da72747e309b2f4d7a970da8af84bb86c8954f99ddd

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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 urllib3.exceptions in pkg:pypi/urllib3@2.7.0
包
符号
  • urllib3.exceptions
创建时间
2026-09-05T22:05:19Z

契约

  1. urllib3.exceptions.HTTPError is the base exception class for all urllib3 errors and inherits from Exception
  2. urllib3.exceptions.ClosedPoolError inherits from PoolError and captures the closed pool reference when dispatching requests
  3. urllib3.exceptions.MaxRetryError inherits from RequestError and preserves pool, url, and underlying reason
  4. urllib3.exceptions.LocationValueError and subclasses enforce URL parsing constraints and scheme validation
  5. urllib3.exceptions.ReadTimeoutError multiple inheritance combines TimeoutError and RequestError with pool and url attributes
  6. urllib3.exceptions.InsecureRequestWarning inherits from HTTPWarning for SSL and security diagnostics

文件

  • PROMPT.md
  • csx.json
  • 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 urllib3.exceptions 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

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:1cdde9feeea8c50a436fdce17e0c957ec5c6307677f64d52f21800523ac962b7","contract":["urllib3.exceptions.HTTPError is the base exception class for all urllib3 errors and inherits from Exception","urllib3.exceptions.ClosedPoolError inherits from PoolError and captures the closed pool reference when dispatching requests","urllib3.exceptions.MaxRetryError inherits from RequestError and preserves pool, url, and underlying reason","urllib3.exceptions.LocationValueError and subclasses enforce URL parsing constraints and scheme validation","urllib3.exceptions.ReadTimeoutError multiple inheritance combines TimeoutError and RequestError with pool and url attributes","urllib3.exceptions.InsecureRequestWarning inherits from HTTPWarning for SSL and security diagnostics"],"goal":"verify urllib3.exceptions in pkg:pypi/urllib3@2.7.0","kind":"HOW","packages":["pkg:pypi/urllib3@2.7.0"],"schemaVersion":1,"symbols":["urllib3.exceptions"]},"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"],"verifierAdapter":"python@1"}
requirements.txt
urllib3==2.7.0
sample.py
"""Demonstration of urllib3.exceptions usage and hierarchy."""

from __future__ import annotations

import warnings
import urllib3
import urllib3.exceptions as ue
import urllib3.util


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


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


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


def parse_url_location(url: str) -> urllib3.util.Url:
    """Parse a URL string, raising LocationParseError if invalid."""
    return urllib3.util.parse_url(url)


def emit_insecure_warning(message: str) -> None:
    """Emit an InsecureRequestWarning."""
    warnings.warn(message, ue.InsecureRequestWarning, stacklevel=2)
spec.json
{
  "schemaVersion": 1,
  "goal": "verify urllib3.exceptions in pkg:pypi/urllib3@2.7.0",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/urllib3@2.7.0"
  ],
  "symbols": [
    "urllib3.exceptions"
  ]
}
test/contract.py
"""Contract verification test for urllib3.exceptions in pkg:pypi/urllib3@2.7.0."""

from __future__ import annotations

import os
import sys
import warnings

# Ensure root directory is in 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 (
    check_is_http_error,
    emit_insecure_warning,
    parse_url_location,
    trigger_closed_pool_error,
    trigger_unknown_scheme_error,
)


def test_http_error_base_hierarchy() -> None:
    """Assertion 1: urllib3.exceptions.HTTPError is the base exception class for all urllib3 errors and inherits from Exception."""
    assert issubclass(ue.HTTPError, Exception), "HTTPError must inherit from Exception"
    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"

    base_err = ue.HTTPError("generic http error")
    assert check_is_http_error(base_err) is True
    assert check_is_http_error(ValueError("unrelated error")) is False


def test_pool_error_and_closed_pool() -> None:
    """Assertion 2: urllib3.exceptions.ClosedPoolError inherits from PoolError and captures the closed pool reference when dispatching requests."""
    assert issubclass(ue.ClosedPoolError, ue.PoolError), "ClosedPoolError must inherit from PoolError"
    assert issubclass(ue.EmptyPoolError, ue.PoolError), "EmptyPoolError must inherit from PoolError"

    pool = urllib3.HTTPConnectionPool("127.0.0.1", 80)
    try:
        trigger_closed_pool_error(pool)
        assert False, "Expected ClosedPoolError when requesting against a closed pool"
    except ue.ClosedPoolError as exc:
        assert exc.pool is pool, "ClosedPoolError.pool must reference the closed pool instance"
        assert issubclass(type(exc), ue.PoolError), "ClosedPoolError must be a subclass of PoolError"
        assert issubclass(type(exc), ue.HTTPError), "ClosedPoolError must be a subclass of HTTPError"
        assert "Pool is closed" in str(exc), "Error message must indicate pool is closed"
    finally:
        pool.close()


def test_request_error_and_max_retry() -> None:
    """Assertion 3: urllib3.exceptions.MaxRetryError inherits from RequestError and preserves pool, url, and underlying reason."""
    assert issubclass(ue.MaxRetryError, ue.RequestError), "MaxRetryError must inherit from RequestError"
    assert issubclass(ue.RequestError, ue.HTTPError), "RequestError must inherit from HTTPError"

    pool = urllib3.HTTPConnectionPool("example.com", 80)
    target_url = "http://example.com/api/v1/resource"
    underlying_cause = Exception("socket connection refused")

    try:
        retry_err = ue.MaxRetryError(pool, target_url, reason=underlying_cause)
        assert retry_err.pool is pool, "MaxRetryError.pool must reference the pool"
        assert retry_err.url == target_url, "MaxRetryError.url must match the target URL"
        assert retry_err.reason is underlying_cause, "MaxRetryError.reason must retain the root cause"
        assert target_url in str(retry_err), "String representation must include the target URL"
    finally:
        pool.close()


def test_location_value_error_and_subclasses() -> None:
    """Assertion 4: urllib3.exceptions.LocationValueError and subclasses enforce URL parsing constraints and scheme validation."""
    assert issubclass(ue.LocationValueError, (ValueError, ue.HTTPError)), (
        "LocationValueError must inherit from both ValueError and HTTPError"
    )
    assert issubclass(ue.LocationParseError, ue.LocationValueError), (
        "LocationParseError must inherit from LocationValueError"
    )
    assert issubclass(ue.URLSchemeUnknown, ue.LocationValueError), (
        "URLSchemeUnknown must inherit from LocationValueError"
    )

    # Validate LocationParseError on malformed port
    invalid_url = "http://example.com:99999999"
    try:
        parse_url_location(invalid_url)
        assert False, "Expected LocationParseError for out-of-range port"
    except ue.LocationParseError as exc:
        assert exc.location == invalid_url, "LocationParseError.location must match invalid URL"
        assert issubclass(type(exc), ue.LocationValueError)
        assert issubclass(type(exc), ValueError)

    # Validate URLSchemeUnknown via trigger_unknown_scheme_error
    unknown_scheme_url = "unknown://localhost/test"
    try:
        trigger_unknown_scheme_error(unknown_scheme_url)
        assert False, "Expected URLSchemeUnknown for unregistered scheme"
    except ue.URLSchemeUnknown as exc:
        assert exc.scheme == "unknown", "URLSchemeUnknown.scheme must record the scheme"
        assert issubclass(type(exc), ue.LocationValueError)


def test_read_timeout_error_multiple_inheritance() -> None:
    """Assertion 5: urllib3.exceptions.ReadTimeoutError multiple inheritance combines TimeoutError and RequestError with pool and url attributes."""
    assert issubclass(ue.ReadTimeoutError, ue.TimeoutError), "ReadTimeoutError must inherit from TimeoutError"
    assert issubclass(ue.ReadTimeoutError, ue.RequestError), "ReadTimeoutError must inherit from RequestError"
    assert issubclass(ue.ConnectTimeoutError, ue.TimeoutError), "ConnectTimeoutError must inherit from TimeoutError"

    pool = urllib3.HTTPConnectionPool("example.com", 80)
    target_url = "http://example.com/data"
    try:
        read_timeout = ue.ReadTimeoutError(pool, target_url, "Read timed out after 5.0 seconds")
        assert read_timeout.pool is pool, "ReadTimeoutError.pool must reference pool"
        assert read_timeout.url == target_url, "ReadTimeoutError.url must match target URL"
        assert "Read timed out" in str(read_timeout), "Message must appear in string representation"
    finally:
        pool.close()


def test_warnings_hierarchy() -> None:
    """Assertion 6: urllib3.exceptions.InsecureRequestWarning inherits from HTTPWarning for SSL and security diagnostics."""
    assert issubclass(ue.HTTPWarning, Warning), "HTTPWarning must inherit from Warning"
    assert issubclass(ue.SecurityWarning, ue.HTTPWarning), "SecurityWarning must inherit from HTTPWarning"
    assert issubclass(ue.InsecureRequestWarning, ue.HTTPWarning), "InsecureRequestWarning must inherit from HTTPWarning"

    with warnings.catch_warnings(record=True) as captured:
        warnings.simplefilter("always")
        emit_insecure_warning("Unverified HTTPS request is being made.")
        assert len(captured) == 1, "Expected exactly one warning to be emitted"
        warning_item = captured[0]
        assert issubclass(warning_item.category, ue.InsecureRequestWarning), (
            "Warning category must be InsecureRequestWarning"
        )
        assert issubclass(warning_item.category, ue.HTTPWarning), (
            "Warning category must inherit from HTTPWarning"
        )
        assert "Unverified HTTPS request" in str(warning_item.message)


def main() -> None:
    test_http_error_base_hierarchy()
    test_pool_error_and_closed_pool()
    test_request_error_and_max_retry()
    test_location_value_error_and_subclasses()
    test_read_timeout_error_multiple_inheritance()
    test_warnings_hierarchy()
    print("All contract assertions passed.")


if __name__ == "__main__":
    main()

原始种子者

匿名