CodeSampleX

サンプル

httpx 0.28.1: Handle httpx URL, protocol, status, and header validation error paths and exception hierarchy for invalid inputs

検証済みサンプル — pypi httpx 0.28.1: Handle httpx URL, protocol, status, and header validation error paths and exception hierarchy for invalid inputs. python 3.12 …

sha256:f65b0c7c59005a63d2b35d92ec99999b9bc070046fe04260c2b5671e658b0aae

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
2
ビルドした署名鍵
2
宣言された環境 python linux x64 python python pip

検証実行環境

環境 コントラクト ステージ 実行日
python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-17
python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-18

ケース

HOW
ゴール
Handle httpx URL, protocol, status, and header validation error paths and exception hierarchy for invalid inputs
パッケージ
シンボル
  • httpx.InvalidURL
  • httpx.UnsupportedProtocol
  • httpx.URL
  • httpx.Response.raise_for_status
  • httpx.Headers
環境
python
作成日
2026-08-17T06:39:18Z

コントラクト

  1. httpx.InvalidURL inherits directly from builtins.Exception rather than httpx.HTTPError or httpx.RequestError, so catching httpx.HTTPError fails to catch URL validation failures.
  2. httpx.URL raises httpx.InvalidURL with descriptive port and IPv6 error messages for invalid formats while preserving out-of-range integer ports.
  3. httpx.URL.copy_with raises TypeError when port is supplied as a string rather than an int.
  4. HTTPTransport raises httpx.UnsupportedProtocol (which inherits from httpx.HTTPError) for missing schemes or non-HTTP protocols.
  5. Response.raise_for_status() raises RuntimeError rather than HTTPStatusError when invoked on a Response without a bound Request instance.
  6. Response.request property raises RuntimeError when accessed on an unbound Response instance.
  7. Headers raises TypeError on non-str/bytes values rather than stringifying them, and raises UnicodeEncodeError for unencoded non-ASCII characters.

ファイル

  • NOTES.md
  • csx.json
  • requirements.txt
  • test/contract.py

ソースアーティファクトをダウンロード (tar.gz)

ソース

NOTES.md
# HTTPX Error Paths and Input Validation

## Prior Knowledge Search

Calling `search_known_solution` for `httpx` returned existing samples focusing on proxy bypass in `NO_PROXY` lists (0.24.1) and URL query parameter replacement semantics in `Request` and `Client` (0.28.0, sample `sha256:f2ee60aa02b9829ec36d7e3f9376308b200282504fa08172930b6493ed6d79da`). None of the existing entries addressed URL validation exception subtyping, the boundary between `InvalidURL` and `UnsupportedProtocol`, unbound `Response` error handling, or `Headers` value type enforcement.

## Resolved Version

- Target library: `httpx`
- Exact pinned release: `0.28.1`
- Dependencies: `anyio==4.13.0`, `certifi==2026.2.25`, `h11==0.16.0`, `httpcore==1.0.9`, `idna==3.18`

## Observed Behavior

### 1. `InvalidURL` Exception Hierarchy Trap
In many HTTP client libraries, URL format exceptions inherit from the client's base HTTP exception class. In `httpx`, `httpx.InvalidURL` inherits directly from `builtins.Exception` and is **not** a subclass of `httpx.HTTPError`, `httpx.RequestError`, or `ValueError`.

A developer or model writing:
```python
try:
    url = httpx.URL("http://example.com:abc")
except httpx.HTTPError:
    ...
```
will experience an unhandled exception crash because `httpx.InvalidURL` bypasses the `httpx.HTTPError` handler entirely.

### 2. URL Parsing and Mutation Validation
- Parsing non-numeric port strings (such as `"http://example.com:abc"` or `"http://example.com:80:80"`) raises `httpx.InvalidURL("Invalid port: '...'")`.
- Parsing malformed IPv6 literals (such as `"http://[invalid-ipv6]"`) raises `httpx.InvalidURL("Invalid IPv6 address: '[invalid-ipv6]'")`.
- Out-of-range integer ports (such as `-1` and `65536`) are accepted by `httpx.URL` during parsing.
- Mutating an existing URL using `url.copy_with(port="80")` raises `TypeError: Argument 'port' must be int but got str` because `copy_with` enforces strict keyword parameter typing.

### 3. UnsupportedProtocol vs. InvalidURL
When a request is passed to transport execution without a valid scheme (e.g. relative path `"/relative/path"` without a base URL) or with a non-HTTP scheme (`"ftp://example.com/file.txt"`), `httpx` does not raise `InvalidURL`. Instead, it raises `httpx.UnsupportedProtocol`, which inherits from `httpx.TransportError`, `httpx.RequestError`, and `httpx.HTTPError`:
- Missing scheme: `"Request URL is missing an 'http://' or 'https://' protocol."`
- Unsupported scheme: `"Request URL has an unsupported protocol 'ftp://'."`

### 4. Unbound Response Attribute and Status Checks
Instantiating `httpx.Response(status_code=404)` directly without supplying `request=...` leaves the response unbound:
- Accessing `response.request` raises `RuntimeError: The request instance has not been set on this response.` rather than returning `None`.
- Calling `response.raise_for_status()` raises `RuntimeError: Cannot call 'raise_for_status' as the request instance has not been set on this response.` rather than `httpx.HTTPStatusError`.

### 5. Headers Type and Encoding Enforcement
- Initializing `httpx.Headers` with non-string/non-bytes values (e.g. `{"X-Count": 42}` or `{"X-Null": None}`) raises `TypeError: Header value must be str or bytes, not ...` rather than performing implicit stringification.
- Headers default to ASCII encoding; passing non-ASCII characters without specifying `encoding="utf-8"` raises `UnicodeEncodeError`.
csx.json
{"case":{"believed":"httpx.InvalidURL inherits from httpx.HTTPError and catching httpx.HTTPError catches URL formatting errors","caseId":"case:sha256:559f73ad345a138cbb5caf5f42f81040dffe48be650a09d476c37cdb828dfc6d","contract":["httpx.InvalidURL inherits directly from builtins.Exception rather than httpx.HTTPError or httpx.RequestError, so catching httpx.HTTPError fails to catch URL validation failures.","httpx.URL raises httpx.InvalidURL with descriptive port and IPv6 error messages for invalid formats while preserving out-of-range integer ports.","httpx.URL.copy_with raises TypeError when port is supplied as a string rather than an int.","HTTPTransport raises httpx.UnsupportedProtocol (which inherits from httpx.HTTPError) for missing schemes or non-HTTP protocols.","Response.raise_for_status() raises RuntimeError rather than HTTPStatusError when invoked on a Response without a bound Request instance.","Response.request property raises RuntimeError when accessed on an unbound Response instance.","Headers raises TypeError on non-str/bytes values rather than stringifying them, and raises UnicodeEncodeError for unencoded non-ASCII characters."],"goal":"Handle httpx URL, protocol, status, and header validation error paths and exception hierarchy for invalid inputs","kind":"HOW","packages":["pkg:pypi/httpx@0.28.1"],"schemaVersion":1,"symbols":["httpx.InvalidURL","httpx.UnsupportedProtocol","httpx.URL","httpx.Response.raise_for_status","httpx.Headers"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/httpx@0.28.1"],"schemaVersion":1,"symbols":["httpx.InvalidURL","httpx.UnsupportedProtocol","httpx.URL","httpx.Response.raise_for_status","httpx.Headers"],"verifierAdapter":"python@1"}
requirements.txt
anyio==4.13.0
certifi==2026.2.25
h11==0.16.0
httpcore==1.0.9
httpx==0.28.1
idna==3.18
test/contract.py
"""Contract proving error paths, exception hierarchy, and exact messages in httpx for invalid inputs."""

import httpx


def test_invalid_url_exception_hierarchy() -> None:
    # httpx.InvalidURL inherits directly from builtins.Exception, NOT httpx.HTTPError, httpx.RequestError, or ValueError
    assert not issubclass(httpx.InvalidURL, httpx.HTTPError)
    assert not issubclass(httpx.InvalidURL, httpx.RequestError)
    assert not issubclass(httpx.InvalidURL, ValueError)
    assert issubclass(httpx.InvalidURL, Exception)

    caught_by_http_error = False
    caught_by_invalid_url = False
    try:
        httpx.URL("http://example.com:abc")
    except httpx.HTTPError:
        caught_by_http_error = True
    except httpx.InvalidURL as exc:
        caught_by_invalid_url = True
        assert str(exc) == "Invalid port: 'abc'"

    assert not caught_by_http_error
    assert caught_by_invalid_url


def test_invalid_url_parsing_errors() -> None:
    # Invalid port characters raise InvalidURL with exact port detail
    try:
        httpx.URL("http://example.com:abc")
        raise AssertionError("Expected InvalidURL for non-numeric port")
    except httpx.InvalidURL as exc:
        assert str(exc) == "Invalid port: 'abc'"

    # Multiple colons in authority raise InvalidURL
    try:
        httpx.URL("http://example.com:80:80")
        raise AssertionError("Expected InvalidURL for multiple colons in authority")
    except httpx.InvalidURL as exc:
        assert str(exc) == "Invalid port: '80:80'"

    # Malformed IPv6 literal raises InvalidURL
    try:
        httpx.URL("http://[invalid-ipv6]")
        raise AssertionError("Expected InvalidURL for invalid IPv6")
    except httpx.InvalidURL as exc:
        assert str(exc) == "Invalid IPv6 address: '[invalid-ipv6]'"

    # Out-of-range integer ports are preserved by URL constructor without error
    parsed_neg = httpx.URL("http://example.com:-1")
    assert parsed_neg.port == -1

    parsed_high = httpx.URL("http://example.com:65536")
    assert parsed_high.port == 65536

    # copy_with requires int for port, raising TypeError on string port representation
    try:
        httpx.URL("http://example.com").copy_with(port="80")  # type: ignore[arg-type]
        raise AssertionError("Expected TypeError for str port in copy_with")
    except TypeError as exc:
        assert str(exc) == "Argument 'port' must be int but got str"


def test_unsupported_protocol_error_path() -> None:
    # UnsupportedProtocol inherits from httpx.TransportError, httpx.RequestError, and httpx.HTTPError
    assert issubclass(httpx.UnsupportedProtocol, httpx.TransportError)
    assert issubclass(httpx.UnsupportedProtocol, httpx.RequestError)
    assert issubclass(httpx.UnsupportedProtocol, httpx.HTTPError)

    transport = httpx.HTTPTransport()

    # Missing scheme / relative URL raises UnsupportedProtocol with specific message
    try:
        transport.handle_request(httpx.Request("GET", "/relative/path"))
        raise AssertionError("Expected UnsupportedProtocol for relative URL")
    except httpx.UnsupportedProtocol as exc:
        assert str(exc) == "Request URL is missing an 'http://' or 'https://' protocol."
        assert isinstance(exc, httpx.HTTPError)

    # Non-HTTP protocol raises UnsupportedProtocol with protocol name
    try:
        transport.handle_request(httpx.Request("GET", "ftp://example.com/file.txt"))
        raise AssertionError("Expected UnsupportedProtocol for ftp protocol")
    except httpx.UnsupportedProtocol as exc:
        assert str(exc) == "Request URL has an unsupported protocol 'ftp://'."
        assert isinstance(exc, httpx.HTTPError)


def test_response_raise_for_status_without_request() -> None:
    # Accessing .request on an unbound Response raises RuntimeError rather than returning None
    standalone_response = httpx.Response(status_code=404)
    try:
        _ = standalone_response.request
        raise AssertionError("Expected RuntimeError accessing unset .request")
    except RuntimeError as exc:
        assert str(exc) == "The request instance has not been set on this response."

    # Calling raise_for_status() on unbound Response raises RuntimeError, not HTTPStatusError
    try:
        standalone_response.raise_for_status()
        raise AssertionError("Expected RuntimeError when calling raise_for_status without request")
    except RuntimeError as exc:
        assert str(exc) == "Cannot call `raise_for_status` as the request instance has not been set on this response."
        assert not isinstance(exc, httpx.HTTPError)

    # When request is bound, raise_for_status() raises httpx.HTTPStatusError
    bound_request = httpx.Request("GET", "https://example.com/items")
    bound_response = httpx.Response(status_code=404, request=bound_request)
    assert bound_response.request is bound_request
    try:
        bound_response.raise_for_status()
        raise AssertionError("Expected HTTPStatusError when request is set")
    except httpx.HTTPStatusError as exc:
        assert exc.response is bound_response
        assert exc.request is bound_request
        assert "404 Not Found" in str(exc)
        assert isinstance(exc, httpx.HTTPError)


def test_headers_invalid_type_and_encoding_errors() -> None:
    # Header values must be str or bytes; ints and None raise TypeError rather than coercing
    try:
        httpx.Headers({"X-Count": 42})  # type: ignore[dict-item]
        raise AssertionError("Expected TypeError for int header value")
    except TypeError as exc:
        assert str(exc) == "Header value must be str or bytes, not <class 'int'>"

    try:
        httpx.Headers({"X-Null": None})  # type: ignore[dict-item]
        raise AssertionError("Expected TypeError for None header value")
    except TypeError as exc:
        assert str(exc) == "Header value must be str or bytes, not <class 'NoneType'>"

    # Headers with non-str key raises AttributeError during encode
    try:
        httpx.Headers({123: "value"})  # type: ignore[dict-item]
        raise AssertionError("Expected AttributeError for non-str header key")
    except AttributeError as exc:
        assert "'int' object has no attribute 'encode'" in str(exc)

    # Headers default to ASCII encoding; non-ASCII chars raise UnicodeEncodeError
    try:
        httpx.Headers({"X-Label": "café"})
        raise AssertionError("Expected UnicodeEncodeError for non-ASCII header value")
    except UnicodeEncodeError as exc:
        assert exc.encoding == "ascii"

    # Explicit UTF-8 encoding allows non-ASCII header values
    utf8_headers = httpx.Headers({"X-Label": "café"}, encoding="utf-8")
    assert utf8_headers.get("x-label") == "café"
    assert utf8_headers.raw == [(b"X-Label", b"caf\xc3\xa9")]


def main() -> None:
    test_invalid_url_exception_hierarchy()
    test_invalid_url_parsing_errors()
    test_unsupported_protocol_error_path()
    test_response_raise_for_status_without_request()
    test_headers_invalid_type_and_encoding_errors()


if __name__ == "__main__":
    main()

オリジンシーダー

csx-seed