CodeSampleX

Exemple

urllib3 2.7.0: exceptions.LocationValueError

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

sha256:f39ec98252bfe1589dac71b7108007002271ed48b46419c659a77fc3c22fcf9b

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

Cas

HOW
Objectif
verify urllib3.exceptions.LocationValueError in pkg:pypi/urllib3@2.7.0
Paquets
Symboles
  • urllib3.exceptions.LocationValueError
Créé
2026-09-05T23:23:47Z

Contrat

  1. LocationValueError is a subclass of both ValueError and urllib3.exceptions.HTTPError
  2. LocationParseError and URLSchemeUnknown inherit from LocationValueError
  3. urllib3.util.parse_url raises LocationParseError on invalid port or invalid IPv6 format
  4. urllib3.connectionpool.connection_from_url raises LocationValueError when host is omitted
  5. urllib3.poolmanager.PoolManager.connection_from_url raises LocationValueError for missing host and URLSchemeUnknown for unsupported scheme

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 urllib3.exceptions.LocationValueError 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.LocationValueError

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:cf4dc82ea3937dc359bb21f37fb77767e98e6ed4ddb5f8343b9fd76c41edd678","contract":["LocationValueError is a subclass of both ValueError and urllib3.exceptions.HTTPError","LocationParseError and URLSchemeUnknown inherit from LocationValueError","urllib3.util.parse_url raises LocationParseError on invalid port or invalid IPv6 format","urllib3.connectionpool.connection_from_url raises LocationValueError when host is omitted","urllib3.poolmanager.PoolManager.connection_from_url raises LocationValueError for missing host and URLSchemeUnknown for unsupported scheme"],"goal":"verify urllib3.exceptions.LocationValueError in pkg:pypi/urllib3@2.7.0","kind":"HOW","packages":["pkg:pypi/urllib3@2.7.0"],"schemaVersion":1,"symbols":["urllib3.exceptions.LocationValueError"]},"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.LocationValueError"],"verifierAdapter":"python@1"}
requirements.txt
urllib3==2.7.0
sample.py
"""Demonstration of urllib3 URL validation and LocationValueError handling."""

from typing import Optional
import urllib3
from urllib3.exceptions import LocationValueError, LocationParseError, URLSchemeUnknown
from urllib3.util import parse_url, Url


def parse_target_url(url: str) -> Url:
    """Parse a URL string into a Url namedtuple.

    Raises LocationValueError (or its subclass LocationParseError) if the URL is malformed.
    """
    return parse_url(url)


def is_valid_url(url: str) -> bool:
    """Check if a URL string can be parsed without raising LocationValueError."""
    try:
        parse_url(url)
        return True
    except LocationValueError:
        return False


def get_connection_pool_for_url(
    url: str,
) -> urllib3.connectionpool.HTTPConnectionPool:
    """Create a connection pool for a specific URL.

    Raises LocationValueError if the host component is missing.
    """
    return urllib3.connectionpool.connection_from_url(url)


def get_managed_pool_for_url(
    pool_manager: urllib3.PoolManager,
    url: str,
) -> urllib3.connectionpool.HTTPConnectionPool:
    """Acquire a connection from PoolManager for the specified URL.

    Raises LocationValueError if the host is missing or URLSchemeUnknown for unsupported schemes.
    """
    return pool_manager.connection_from_url(url)
spec.json
{
  "schemaVersion": 1,
  "goal": "verify urllib3.exceptions.LocationValueError in pkg:pypi/urllib3@2.7.0",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/urllib3@2.7.0"
  ],
  "symbols": [
    "urllib3.exceptions.LocationValueError"
  ]
}
test/contract.py
"""Contract verification test for urllib3.exceptions.LocationValueError."""

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 urllib3
from urllib3.exceptions import (
    HTTPError,
    LocationParseError,
    LocationValueError,
    URLSchemeUnknown,
)
from sample import (
    get_connection_pool_for_url,
    get_managed_pool_for_url,
    is_valid_url,
    parse_target_url,
)


def test_inheritance_hierarchy() -> None:
    """Assertion 1: LocationValueError is a subclass of both ValueError and urllib3.exceptions.HTTPError."""
    assert issubclass(LocationValueError, ValueError), (
        "LocationValueError must inherit from ValueError"
    )
    assert issubclass(LocationValueError, HTTPError), (
        "LocationValueError must inherit from HTTPError"
    )

    err = LocationValueError("Test location value error")
    assert isinstance(err, ValueError)
    assert isinstance(err, HTTPError)


def test_subclass_relationships() -> None:
    """Assertion 2: LocationParseError and URLSchemeUnknown inherit from LocationValueError."""
    assert issubclass(LocationParseError, LocationValueError), (
        "LocationParseError must inherit from LocationValueError"
    )
    assert issubclass(URLSchemeUnknown, LocationValueError), (
        "URLSchemeUnknown must inherit from LocationValueError"
    )


def test_parse_url_invalid_components() -> None:
    """Assertion 3: urllib3.util.parse_url raises LocationParseError on invalid port or invalid IPv6 format."""
    # Invalid port: non-numeric or out-of-range integer
    invalid_port_url = "http://example.com:99999999999999999999"
    try:
        parse_target_url(invalid_port_url)
        assert False, "Expected LocationParseError for out-of-range port"
    except LocationValueError as exc:
        assert isinstance(exc, LocationParseError)

    # Invalid IPv6 address bracket syntax
    invalid_ipv6_url = "http://[::1:invalid]/"
    try:
        parse_target_url(invalid_ipv6_url)
        assert False, "Expected LocationParseError for invalid IPv6 format"
    except LocationValueError as exc:
        assert isinstance(exc, LocationParseError)

    assert not is_valid_url(invalid_port_url)
    assert not is_valid_url(invalid_ipv6_url)
    assert is_valid_url("http://example.com:8080/path")


def test_connection_from_url_missing_host() -> None:
    """Assertion 4: urllib3.connectionpool.connection_from_url raises LocationValueError when host is omitted."""
    empty_host_urls = ["", "http://", "https://"]
    for url in empty_host_urls:
        try:
            get_connection_pool_for_url(url)
            assert False, f"Expected LocationValueError for url {url!r}"
        except LocationValueError as exc:
            assert "No host specified" in str(exc)


def test_pool_manager_connection_from_url() -> None:
    """Assertion 5: urllib3.poolmanager.PoolManager.connection_from_url raises LocationValueError for missing host and URLSchemeUnknown for unsupported scheme."""
    pm = urllib3.PoolManager()

    # Missing host raises LocationValueError with "No host specified"
    try:
        get_managed_pool_for_url(pm, "http://")
        assert False, "Expected LocationValueError when host is missing in PoolManager.connection_from_url"
    except LocationValueError as exc:
        assert "No host specified" in str(exc)

    # Unsupported scheme raises URLSchemeUnknown (subclass of LocationValueError)
    try:
        get_managed_pool_for_url(pm, "ftp://example.com")
        assert False, "Expected URLSchemeUnknown for unsupported scheme"
    except LocationValueError as exc:
        assert isinstance(exc, URLSchemeUnknown)
        assert exc.scheme == "ftp"


def main() -> None:
    test_inheritance_hierarchy()
    test_subclass_relationships()
    test_parse_url_invalid_components()
    test_connection_from_url_missing_host()
    test_pool_manager_connection_from_url()
    print("All contract assertions passed.")


if __name__ == "__main__":
    main()

Seeder d'origine

anonyme