diff --git a/.skills/python-bindings.md b/.skills/python-bindings.md index abcab4ed..1ffea66d 100644 --- a/.skills/python-bindings.md +++ b/.skills/python-bindings.md @@ -49,6 +49,42 @@ EggfetchError └── HTTPStatusError ``` +## HTTPX Compatibility Layer + +The `eggfetch.compat.httpx` module provides an HTTPX 0.28.1 drop-in facade over the eggfetch Rust engine. Import path: + +```python +from eggfetch.compat.httpx import Client, AsyncClient, Request, Response +``` + +**Phase 2 implements:** +- Value objects: `URL`, `QueryParams`, `Headers`, `Cookies`, `Timeout`, `Limits`, `Proxy` +- Status code helpers (`codes`) +- Request and Response objects with full HTTPX-compatible metadata +- `Client` and `AsyncClient` with constructor signatures, merge semantics, `build_request()`, `send()` +- Top-level helpers: `get`, `post`, `put`, `patch`, `delete`, `head`, `options`, `request`, `stream` +- Complete exception hierarchy matching HTTPX MRO +- Stubs for auth flows, transports, and stream classes (Phase 3+) + +**Testing the compat layer:** + +```sh +cd crates/eggfetch-python && maturin develop +EGGFETCH_COMPAT_REQUIRED=1 pytest crates/eggfetch-python/tests/compat/ -v --strict-markers +``` + +Validate profiles and manifests: + +```sh +python scripts/validate_httpx_compat_profile.py compat/httpx/0.28.1 +python scripts/generate_httpx_api_manifest.py --package httpx --output /tmp/httpx.json +python scripts/generate_httpx_api_manifest.py --package eggfetch --output /tmp/eggfetch.json +python scripts/compare_httpx_api_manifest.py \ + --reference /tmp/httpx.json \ + --candidate /tmp/eggfetch.json \ + --allowed compat/httpx/0.28.1/allowed-differences.toml +``` + ## Architecture Reference - Python bindings: `docs/architecture/python-bindings.md` diff --git a/AGENTS.md b/AGENTS.md index 367fa29b..0098151c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -83,6 +83,23 @@ Key flags: `http2`, `http3`, `json`, `compression-{gzip,brotli,zstd,deflate}`, ` The CLI enables: cookies, multipart, proxy. The Python binding enables all features including http3. `test-util` enables `tokio/test-util` for deterministic time testing. +## HTTPX Compatibility Layer + +The `eggfetch.compat.httpx` module provides an HTTPX 0.28.1 drop-in facade. Import it as: + +```python +from eggfetch.compat.httpx import Client, AsyncClient, Request, Response, URL, Headers, Cookies +``` + +Phase 2 is complete — value objects, request/response, exception hierarchy, client constructors, and merge semantics are implemented. See `plans/httpx-drop-in-phase-2-status.md` for status. + +Run compat tests: + +```sh +cd crates/eggfetch-python && maturin develop +EGGFETCH_COMPAT_REQUIRED=1 pytest crates/eggfetch-python/tests/compat/ -v --strict-markers +``` + ## Tests Colocated `#[cfg(test)] mod tests` blocks. ~750+ Rust, ~463+ Python, ~40+ FFI tests. diff --git a/README.md b/README.md index 646c9f87..fb1b8614 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,20 @@ Phase 1 (production semantics) closes these gaps: See [`compat/httpx/0.28.1/`](compat/httpx/0.28.1/) for the full profile and [`docs/reference/compatibility.md`](docs/reference/compatibility.md) for the feature matrix. +## HTTPX Drop-In Compatibility + +eggfetch provides a drop-in HTTPX 0.28.1 compatibility facade: + +```python +from eggfetch.compat.httpx import Client, AsyncClient, Request, Response, URL, Headers + +# Drop-in replacement for httpx +client = Client() +response = client.get("https://example.com") +``` + +Phase 2 (object model and core API parity) is complete. See [`plans/httpx-drop-in-phase-2-status.md`](plans/httpx-drop-in-phase-2-status.md) for details, [`compat/httpx/0.28.1/`](compat/httpx/0.28.1/) for the pinned profile, and [`docs/reference/compatibility.md`](docs/reference/compatibility.md) for the feature matrix. + ## Target API Shapes The Python API targets familiar requests/httpx patterns: diff --git a/crates/eggfetch-python/python/eggfetch/compat/__init__.py b/crates/eggfetch-python/python/eggfetch/compat/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/crates/eggfetch-python/python/eggfetch/compat/httpx/__init__.py b/crates/eggfetch-python/python/eggfetch/compat/httpx/__init__.py new file mode 100644 index 00000000..fe33557e --- /dev/null +++ b/crates/eggfetch-python/python/eggfetch/compat/httpx/__init__.py @@ -0,0 +1,293 @@ +"""HTTPX 0.28.1-compatible facade for eggfetch. + +This package provides a drop-in compatibility layer so that existing +HTTPX code can run against the eggfetch Rust engine with minimal changes. +""" + +from __future__ import annotations + +__description__ = "A HTTPX-compatible facade for eggfetch." +__title__ = "eggfetch[httpx-compat]" +__version__ = "0.28.1" + +# ── Phase 2: pure-Python value objects ────────────────────────────────── +from eggfetch.compat.httpx._urls import URL, QueryParams +from eggfetch.compat.httpx._headers import Headers +from eggfetch.compat.httpx._cookies import Cookies +from eggfetch.compat.httpx._timeout import Timeout +from eggfetch.compat.httpx._limits import Limits +from eggfetch.compat.httpx._proxy import Proxy +from eggfetch.compat.httpx._status_codes import codes +from eggfetch.compat.httpx._exceptions import ( + CloseError, + ConnectError, + ConnectTimeout, + CookieConflict, + DecodingError, + HTTPError, + HTTPStatusError, + InvalidURL, + LocalProtocolError, + NetworkError, + PoolTimeout, + ProtocolError, + ProxyError, + ReadError, + ReadTimeout, + RemoteProtocolError, + RequestError, + RequestNotRead, + ResponseNotRead, + StreamClosed, + StreamConsumed, + StreamError, + TimeoutException, + TooManyRedirects, + TransportError, + UnsupportedProtocol, + WriteError, + WriteTimeout, +) + +# ── Phase 3+ / 4+: stubs for transports, auth, streams, client ──────── +# These exist so the import line ``from eggfetch.compat.httpx import …`` +# works. Real implementations arrive in later phases. + +_USE_CLIENT_DEFAULT = object() + + +def _stub_factory(name: str, msg: str | None = None): + """Return a class that raises NotImplementedError on instantiation.""" + _msg = msg or f"eggfetch does not support {name}" + + class _Stub: + def __init_subclass__(cls, **kwargs): + super().__init_subclass__(**kwargs) + + def __init__(self, *args, **kwargs): + raise NotImplementedError(_msg) + + _Stub.__name__ = name + _Stub.__qualname__ = name + return _Stub + + +# Auth base class (Phase 3+) +class Auth: + """Base class for authentication.""" + + def auth_flow(self, request): + raise NotImplementedError("eggfetch auth flows not yet implemented") + + +class _NetRCAuth(Auth): + """Stub for NetRCAuth.""" + + def __init__(self, *args, **kwargs): + raise NotImplementedError("eggfetch does not support NetRCAuth") + + +NetRCAuth = _NetRCAuth + + +class _BasicAuth(Auth): + """HTTPX-compatible BasicAuth (Phase 2 stub).""" + + def __init__(self, username: str = "", password: str = "", *, encoding="latin-1"): + self._username = username + self._password = password + self._encoding = encoding + + def auth_flow(self, request): + raise NotImplementedError("eggfetch BasicAuth flow not yet implemented") + + def __repr__(self): + return f"BasicAuth(username={self._username!r})" + + +BasicAuth = _BasicAuth + + +class _DigestAuth(Auth): + """HTTPX-compatible DigestAuth (Phase 2 stub).""" + + def __init__(self, username: str, password: str): + self._username = username + self._password = password + + def auth_flow(self, request): + raise NotImplementedError("eggfetch DigestAuth flow not yet implemented") + + def __repr__(self): + return f"DigestAuth(username={self._username!r})" + + +DigestAuth = _DigestAuth + +# Transport stubs (Phase 4+) +class _BaseTransport: + def handle_request(self, request): + raise NotImplementedError("eggfetch does not support custom transports") + + def close(self): + pass + + +class _AsyncBaseTransport: + async def handle_async_request(self, request): + raise NotImplementedError("eggfetch does not support custom transports") + + async def aclose(self): + pass + + +BaseTransport = _BaseTransport +AsyncBaseTransport = _AsyncBaseTransport + +HTTPTransport = _stub_factory("HTTPTransport") +AsyncHTTPTransport = _stub_factory("AsyncHTTPTransport") +MockTransport = _stub_factory("MockTransport") +ASGITransport = _stub_factory("ASGITransport") +WSGITransport = _stub_factory("WSGITransport") + +# Stream stubs +class ByteStream: + def __init__(self, *args, **kwargs): + raise NotImplementedError("eggfetch does not support custom byte streams") + + +class SyncByteStream(ByteStream): + pass + + +class AsyncByteStream: + def __init__(self, *args, **kwargs): + raise NotImplementedError("eggfetch does not support custom byte streams") + + +# Phase 2: Request / Response +from eggfetch.compat.httpx._request import Request +from eggfetch.compat.httpx._response import Response + +# Client / AsyncClient +from eggfetch.compat.httpx._client import Client, AsyncClient + + +# Top-level convenience functions +def request(*args, **kwargs): + with Client() as client: + return client.request(*args, **kwargs) + + +def get(*args, **kwargs): + with Client() as client: + return client.get(*args, **kwargs) + + +def post(*args, **kwargs): + with Client() as client: + return client.post(*args, **kwargs) + + +def put(*args, **kwargs): + with Client() as client: + return client.put(*args, **kwargs) + + +def patch(*args, **kwargs): + with Client() as client: + return client.patch(*args, **kwargs) + + +def delete(*args, **kwargs): + with Client() as client: + return client.delete(*args, **kwargs) + + +def head(*args, **kwargs): + with Client() as client: + return client.head(*args, **kwargs) + + +def options(*args, **kwargs): + with Client() as client: + return client.options(*args, **kwargs) + + +def stream(*args, **kwargs): + with Client() as client: + with client.stream(*args, **kwargs) as response: + return response + + +USE_CLIENT_DEFAULT = _USE_CLIENT_DEFAULT + +__all__ = [ + "__description__", + "__title__", + "__version__", + "ASGITransport", + "AsyncBaseTransport", + "AsyncByteStream", + "AsyncClient", + "AsyncHTTPTransport", + "Auth", + "BaseTransport", + "BasicAuth", + "ByteStream", + "Client", + "CloseError", + "codes", + "ConnectError", + "ConnectTimeout", + "CookieConflict", + "Cookies", + "DecodingError", + "delete", + "DigestAuth", + "get", + "head", + "Headers", + "HTTPError", + "HTTPStatusError", + "HTTPTransport", + "InvalidURL", + "Limits", + "LocalProtocolError", + "MockTransport", + "NetRCAuth", + "NetworkError", + "options", + "patch", + "PoolTimeout", + "post", + "ProtocolError", + "Proxy", + "ProxyError", + "put", + "QueryParams", + "ReadError", + "ReadTimeout", + "RemoteProtocolError", + "request", + "Request", + "RequestError", + "RequestNotRead", + "Response", + "ResponseNotRead", + "stream", + "StreamClosed", + "StreamConsumed", + "StreamError", + "SyncByteStream", + "Timeout", + "TimeoutException", + "TooManyRedirects", + "TransportError", + "UnsupportedProtocol", + "URL", + "USE_CLIENT_DEFAULT", + "WriteError", + "WriteTimeout", + "WSGITransport", +] diff --git a/crates/eggfetch-python/python/eggfetch/compat/httpx/_client.py b/crates/eggfetch-python/python/eggfetch/compat/httpx/_client.py new file mode 100644 index 00000000..626769dc --- /dev/null +++ b/crates/eggfetch-python/python/eggfetch/compat/httpx/_client.py @@ -0,0 +1,713 @@ +"""HTTPX-compatible Client and AsyncClient for eggfetch.""" + +from __future__ import annotations + +import asyncio +import typing +from contextlib import contextmanager, asynccontextmanager + +import eggfetch + +from eggfetch.compat.httpx._urls import URL, QueryParams +from eggfetch.compat.httpx._headers import Headers +from eggfetch.compat.httpx._cookies import Cookies +from eggfetch.compat.httpx._timeout import Timeout +from eggfetch.compat.httpx._limits import Limits +from eggfetch.compat.httpx._proxy import Proxy +from eggfetch.compat.httpx._request import Request +from eggfetch.compat.httpx._response import Response +from eggfetch.compat.httpx._exceptions import ( + ConnectTimeout, + ConnectError, + CookieConflict, + HTTPStatusError, + InvalidURL, + NetworkError, + PoolTimeout, + ProtocolError, + ProxyError, + ReadTimeout, + RequestError, + TimeoutException, + TooManyRedirects, + TransportError, + UnsupportedProtocol, + WriteTimeout, +) + +if typing.TYPE_CHECKING: + from typing import Any, AsyncIterator, Iterator + +_USE_CLIENT_DEFAULT = object() + + +def _convert_timeout(timeout): + if isinstance(timeout, Timeout): + return eggfetch.Timeout( + seconds=timeout.total, + connect=timeout.connect, + read=timeout.read, + write=timeout.write, + pool=timeout.pool, + ) + if isinstance(timeout, (int, float)): + return eggfetch.Timeout(seconds=timeout) + return None + + +def _convert_limits(limits): + if isinstance(limits, Limits): + return eggfetch.Limits( + max_connections=limits.max_connections, + max_keepalive_connections=limits.max_keepalive_connections, + keepalive_expiry=limits.keepalive_expiry, + ) + return None + + +def _convert_headers(headers): + if isinstance(headers, Headers): + return dict(headers.items()) + if isinstance(headers, dict): + return headers + return None + + +def _convert_cookies(cookies): + if isinstance(cookies, Cookies): + return dict(cookies.items()) + if isinstance(cookies, dict): + return cookies + return None + + +def _convert_params(params): + if isinstance(params, QueryParams): + return dict(params.items()) + if isinstance(params, dict): + return params + return None + + +def _convert_proxy(proxy): + if isinstance(proxy, Proxy): + return str(proxy.url) + if isinstance(proxy, str): + return proxy + return None + + +def _map_exception(native_exc, compat_request=None): + exc_type = type(native_exc) + exc_name = exc_type.__name__ + msg = str(native_exc) + + if exc_name == "TimeoutException" or isinstance(native_exc, eggfetch.TimeoutException): + detail = getattr(native_exc, "detail", None) + if detail: + if "connect" in str(detail).lower(): + return ConnectTimeout(msg, request=compat_request) + if "read" in str(detail).lower(): + return ReadTimeout(msg, request=compat_request) + if "write" in str(detail).lower(): + return WriteTimeout(msg, request=compat_request) + if "pool" in str(detail).lower(): + return PoolTimeout(msg, request=compat_request) + return TimeoutException(msg, request=compat_request) + + if exc_name == "ConnectError" or exc_name == "NetworkError": + return ConnectError(msg, request=compat_request) + + if exc_name == "ProtocolError": + return ProtocolError(msg, request=compat_request) + + if exc_name == "TooManyRedirects": + return TooManyRedirects(msg, request=compat_request) + + if exc_name == "InvalidUrl": + return InvalidURL(msg) + + if exc_name == "ProxyError": + return ProxyError(msg, request=compat_request) + + return RequestError(msg, request=compat_request) + + +def _wrap_response(native_resp, compat_request=None, default_encoding="utf-8"): + status_code = native_resp.status_code + native_headers = native_resp.headers + + header_list = [] + if hasattr(native_headers, "multi_items"): + header_list = native_headers.multi_items() + elif hasattr(native_headers, "items"): + header_list = native_headers.items() + + content = native_resp.content + + history = [] + if hasattr(native_resp, "history") and native_resp.history: + for h in native_resp.history: + history.append(_wrap_response(h, default_encoding=default_encoding)) + + return Response( + status_code, + headers=header_list, + content=content, + request=compat_request, + history=history, + default_encoding=default_encoding, + ) + + +class Client: + def __init__( + self, + *, + auth=None, + params=None, + headers=None, + cookies=None, + verify=True, + cert=None, + trust_env=True, + http1=True, + http2=False, + proxy=None, + mounts=None, + timeout=Timeout(5.0), + follow_redirects=False, + limits=Limits(100, 20, 5.0), + max_redirects=20, + event_hooks=None, + base_url="", + transport=None, + default_encoding="utf-8", + ): + self._auth = auth + self._params = params if isinstance(params, QueryParams) else QueryParams(params) + self._headers = headers if isinstance(headers, Headers) else Headers(headers) + self._cookies = cookies if isinstance(cookies, Cookies) else Cookies(cookies) + self._verify = verify + self._cert = cert + self._trust_env = trust_env + self._http1 = http1 + self._http2 = http2 + self._proxy = proxy + self._mounts = mounts + self._timeout = timeout if isinstance(timeout, Timeout) else Timeout(timeout) + self._follow_redirects = follow_redirects + self._limits = limits if isinstance(limits, Limits) else Limits(limits) + self._max_redirects = max_redirects + self._event_hooks = event_hooks or {"request": [], "response": []} + self._base_url = URL(base_url) if not isinstance(base_url, URL) else base_url + self._transport = transport + self._default_encoding = default_encoding + self._native_client = None + self._is_closed = False + + def _ensure_client(self): + if self._native_client is None or self._is_closed: + kwargs = {} + if self._headers: + kwargs["headers"] = _convert_headers(self._headers) + if self._cookies: + kwargs["cookies"] = _convert_cookies(self._cookies) + if self._timeout: + kwargs["timeout"] = _convert_timeout(self._timeout) + if self._follow_redirects: + kwargs["follow_redirects"] = self._follow_redirects + if self._max_redirects is not None: + kwargs["max_redirects"] = self._max_redirects + if self._verify is not True: + kwargs["verify"] = self._verify + if self._cert is not None: + kwargs["cert"] = self._cert + if self._trust_env is not True: + kwargs["trust_env"] = self._trust_env + if self._limits: + kwargs["limits"] = _convert_limits(self._limits) + if self._proxy is not None: + kwargs["proxy"] = _convert_proxy(self._proxy) + if self._http2: + kwargs["http2"] = self._http2 + self._native_client = eggfetch.Client(**kwargs) + self._is_closed = False + + @property + def auth(self): + return self._auth + + @property + def base_url(self) -> URL: + return self._base_url + + @property + def cookies(self) -> Cookies: + return self._cookies + + @property + def event_hooks(self) -> dict: + return self._event_hooks + + @property + def headers(self) -> Headers: + return self._headers + + @property + def is_closed(self) -> bool: + return self._is_closed + + @property + def params(self) -> QueryParams: + return self._params + + @property + def timeout(self) -> Timeout: + return self._timeout + + @property + def trust_env(self) -> bool: + return self._trust_env + + def build_request(self, method, url, **kwargs): + merged_url = self._merge_url(url) + merged_params = self._merge_params(kwargs.get("params")) + merged_headers = self._merge_headers(kwargs.get("headers")) + merged_cookies = self._merge_cookies(kwargs.get("cookies")) + merged_extensions = self._merge_extensions(kwargs.get("extensions")) + + return Request( + method, + merged_url, + params=merged_params, + headers=merged_headers, + cookies=merged_cookies, + content=kwargs.get("content"), + data=kwargs.get("data"), + files=kwargs.get("files"), + json=kwargs.get("json"), + stream=kwargs.get("stream"), + extensions=merged_extensions if merged_extensions else None, + ) + + def send(self, request, *, stream=False, auth=_USE_CLIENT_DEFAULT, + follow_redirects=None, timeout=None): + self._ensure_client() + + kwargs = {} + if isinstance(request, Request): + kwargs["method"] = request.method + kwargs["url"] = str(request.url) + if request.headers: + kwargs["headers"] = _convert_headers(request.headers) + if request.params: + kwargs["params"] = _convert_params(request.params) + if request.content is not None: + kwargs["content"] = request.content + if request.cookies: + kwargs["cookies"] = _convert_cookies(request.cookies) + else: + raise TypeError(f"send() requires a Request object, got {type(request).__name__}") + + if follow_redirects is not None: + kwargs["follow_redirects"] = follow_redirects + if timeout is not None: + kwargs["timeout"] = _convert_timeout(timeout) + + for hook in self._event_hooks.get("request", []): + hook(request) + + try: + native_resp = self._native_client.request(**kwargs) + except Exception as exc: + raise _map_exception(exc, request) from exc + + response = _wrap_response(native_resp, request, self._default_encoding) + + for hook in self._event_hooks.get("response", []): + hook(response) + + return response + + def request(self, method, url, *, params=None, headers=None, cookies=None, + content=None, data=None, files=None, json=None, + follow_redirects=None, timeout=None, extensions=None): + req = self.build_request( + method, url, + params=params, headers=headers, cookies=cookies, + content=content, data=data, files=files, json=json, + extensions=extensions, + ) + return self.send( + req, + follow_redirects=follow_redirects, + timeout=timeout, + ) + + def get(self, url, **kwargs): + return self.request("GET", url, **kwargs) + + def post(self, url, **kwargs): + return self.request("POST", url, **kwargs) + + def put(self, url, **kwargs): + return self.request("PUT", url, **kwargs) + + def patch(self, url, **kwargs): + return self.request("PATCH", url, **kwargs) + + def delete(self, url, **kwargs): + return self.request("DELETE", url, **kwargs) + + def head(self, url, **kwargs): + return self.request("HEAD", url, **kwargs) + + def options(self, url, **kwargs): + return self.request("OPTIONS", url, **kwargs) + + @contextmanager + def stream(self, method, url, **kwargs): + self._ensure_client() + req = self.build_request(method, url, **kwargs) + try: + yield self.send(req, stream=True) + finally: + pass + + def close(self) -> None: + if self._native_client is not None: + try: + self._native_client.close() + except Exception: + pass + self._is_closed = True + + def __enter__(self) -> Client: + self._ensure_client() + return self + + def __exit__(self, *exc) -> None: + self.close() + + def _merge_url(self, url): + if self._base_url and self._base_url._raw: + return URL(url, base_url=self._base_url) + return URL(url) if not isinstance(url, URL) else url + + def _merge_params(self, request_params): + if request_params is None: + return self._params + if isinstance(request_params, QueryParams): + req = request_params + else: + req = QueryParams(request_params) + merged = QueryParams(self._params) + for key in req.keys(): + merged.set(key, req[key]) + return merged + + def _merge_headers(self, request_headers): + merged = self._headers.copy() + if request_headers is not None: + if isinstance(request_headers, Headers): + merged.update(request_headers) + elif isinstance(request_headers, dict): + merged.update(request_headers) + return merged + + def _merge_cookies(self, request_cookies): + if request_cookies is None: + return self._cookies + merged = Cookies(self._cookies) + if isinstance(request_cookies, Cookies): + merged.update(request_cookies) + elif isinstance(request_cookies, dict): + merged.update(request_cookies) + return merged + + def _merge_extensions(self, request_extensions): + if request_extensions is None: + return None + return request_extensions + + +class AsyncClient: + def __init__( + self, + *, + auth=None, + params=None, + headers=None, + cookies=None, + verify=True, + cert=None, + trust_env=True, + http1=True, + http2=False, + proxy=None, + mounts=None, + timeout=Timeout(5.0), + follow_redirects=False, + limits=Limits(100, 20, 5.0), + max_redirects=20, + event_hooks=None, + base_url="", + transport=None, + default_encoding="utf-8", + ): + self._auth = auth + self._params = params if isinstance(params, QueryParams) else QueryParams(params) + self._headers = headers if isinstance(headers, Headers) else Headers(headers) + self._cookies = cookies if isinstance(cookies, Cookies) else Cookies(cookies) + self._verify = verify + self._cert = cert + self._trust_env = trust_env + self._http1 = http1 + self._http2 = http2 + self._proxy = proxy + self._mounts = mounts + self._timeout = timeout if isinstance(timeout, Timeout) else Timeout(timeout) + self._follow_redirects = follow_redirects + self._limits = limits if isinstance(limits, Limits) else Limits(limits) + self._max_redirects = max_redirects + self._event_hooks = event_hooks or {"request": [], "response": []} + self._base_url = URL(base_url) if not isinstance(base_url, URL) else base_url + self._transport = transport + self._default_encoding = default_encoding + self._native_client = None + self._is_closed = False + + def _ensure_client(self): + if self._native_client is None or self._is_closed: + kwargs = {} + if self._headers: + kwargs["headers"] = _convert_headers(self._headers) + if self._cookies: + kwargs["cookies"] = _convert_cookies(self._cookies) + if self._timeout: + kwargs["timeout"] = _convert_timeout(self._timeout) + if self._follow_redirects: + kwargs["follow_redirects"] = self._follow_redirects + if self._max_redirects is not None: + kwargs["max_redirects"] = self._max_redirects + if self._verify is not True: + kwargs["verify"] = self._verify + if self._cert is not None: + kwargs["cert"] = self._cert + if self._trust_env is not True: + kwargs["trust_env"] = self._trust_env + if self._limits: + kwargs["limits"] = _convert_limits(self._limits) + if self._proxy is not None: + kwargs["proxy"] = _convert_proxy(self._proxy) + if self._http2: + kwargs["http2"] = self._http2 + self._native_client = eggfetch.AsyncClient(**kwargs) + self._is_closed = False + + @property + def auth(self): + return self._auth + + @property + def base_url(self) -> URL: + return self._base_url + + @property + def cookies(self) -> Cookies: + return self._cookies + + @property + def event_hooks(self) -> dict: + return self._event_hooks + + @property + def headers(self) -> Headers: + return self._headers + + @property + def is_closed(self) -> bool: + return self._is_closed + + @property + def params(self) -> QueryParams: + return self._params + + @property + def timeout(self) -> Timeout: + return self._timeout + + @property + def trust_env(self) -> bool: + return self._trust_env + + def build_request(self, method, url, **kwargs): + merged_url = self._merge_url(url) + merged_params = self._merge_params(kwargs.get("params")) + merged_headers = self._merge_headers(kwargs.get("headers")) + merged_cookies = self._merge_cookies(kwargs.get("cookies")) + merged_extensions = self._merge_extensions(kwargs.get("extensions")) + + return Request( + method, + merged_url, + params=merged_params, + headers=merged_headers, + cookies=merged_cookies, + content=kwargs.get("content"), + data=kwargs.get("data"), + files=kwargs.get("files"), + json=kwargs.get("json"), + stream=kwargs.get("stream"), + extensions=merged_extensions if merged_extensions else None, + ) + + async def send(self, request, *, stream=False, auth=_USE_CLIENT_DEFAULT, + follow_redirects=None, timeout=None): + self._ensure_client() + + kwargs = {} + if isinstance(request, Request): + kwargs["method"] = request.method + kwargs["url"] = str(request.url) + if request.headers: + kwargs["headers"] = _convert_headers(request.headers) + if request.params: + kwargs["params"] = _convert_params(request.params) + if request.content is not None: + kwargs["content"] = request.content + if request.cookies: + kwargs["cookies"] = _convert_cookies(request.cookies) + else: + raise TypeError(f"send() requires a Request object, got {type(request).__name__}") + + if follow_redirects is not None: + kwargs["follow_redirects"] = follow_redirects + if timeout is not None: + kwargs["timeout"] = _convert_timeout(timeout) + + for hook in self._event_hooks.get("request", []): + if asyncio.iscoroutinefunction(hook): + await hook(request) + else: + hook(request) + + try: + native_resp = await self._native_client.request(**kwargs) + except Exception as exc: + raise _map_exception(exc, request) from exc + + response = _wrap_response(native_resp, request, self._default_encoding) + + for hook in self._event_hooks.get("response", []): + if asyncio.iscoroutinefunction(hook): + await hook(response) + else: + hook(response) + + return response + + async def request(self, method, url, *, params=None, headers=None, cookies=None, + content=None, data=None, files=None, json=None, + follow_redirects=None, timeout=None, extensions=None): + req = self.build_request( + method, url, + params=params, headers=headers, cookies=cookies, + content=content, data=data, files=files, json=json, + extensions=extensions, + ) + return await self.send( + req, + follow_redirects=follow_redirects, + timeout=timeout, + ) + + async def get(self, url, **kwargs): + return await self.request("GET", url, **kwargs) + + async def post(self, url, **kwargs): + return await self.request("POST", url, **kwargs) + + async def put(self, url, **kwargs): + return await self.request("PUT", url, **kwargs) + + async def patch(self, url, **kwargs): + return await self.request("PATCH", url, **kwargs) + + async def delete(self, url, **kwargs): + return await self.request("DELETE", url, **kwargs) + + async def head(self, url, **kwargs): + return await self.request("HEAD", url, **kwargs) + + async def options(self, url, **kwargs): + return await self.request("OPTIONS", url, **kwargs) + + @asynccontextmanager + async def stream(self, method, url, **kwargs): + self._ensure_client() + req = self.build_request(method, url, **kwargs) + try: + yield await self.send(req, stream=True) + finally: + pass + + async def close(self) -> None: + if self._native_client is not None: + try: + await self._native_client.aclose() + except Exception: + pass + self._is_closed = True + + async def aclose(self) -> None: + await self.close() + + async def __aenter__(self) -> AsyncClient: + self._ensure_client() + return self + + async def __aexit__(self, *exc) -> None: + await self.close() + + def _merge_url(self, url): + if self._base_url and self._base_url._raw: + return URL(url, base_url=self._base_url) + return URL(url) if not isinstance(url, URL) else url + + def _merge_params(self, request_params): + if request_params is None: + return self._params + if isinstance(request_params, QueryParams): + req = request_params + else: + req = QueryParams(request_params) + merged = QueryParams(self._params) + for key in req.keys(): + merged.set(key, req[key]) + return merged + + def _merge_headers(self, request_headers): + merged = self._headers.copy() + if request_headers is not None: + if isinstance(request_headers, Headers): + merged.update(request_headers) + elif isinstance(request_headers, dict): + merged.update(request_headers) + return merged + + def _merge_cookies(self, request_cookies): + if request_cookies is None: + return self._cookies + merged = Cookies(self._cookies) + if isinstance(request_cookies, Cookies): + merged.update(request_cookies) + elif isinstance(request_cookies, dict): + merged.update(request_cookies) + return merged + + def _merge_extensions(self, request_extensions): + if request_extensions is None: + return None + return request_extensions diff --git a/crates/eggfetch-python/python/eggfetch/compat/httpx/_cookies.py b/crates/eggfetch-python/python/eggfetch/compat/httpx/_cookies.py new file mode 100644 index 00000000..f60f7158 --- /dev/null +++ b/crates/eggfetch-python/python/eggfetch/compat/httpx/_cookies.py @@ -0,0 +1,121 @@ +"""HTTPX-compatible Cookies class for eggfetch.""" + +from __future__ import annotations + + +class Cookies: + """HTTPX-compatible Cookies class. + + Simplified dict-based approach matching HTTPX behavior. + """ + + __slots__ = ("_cookies",) + + def __init__(self, cookies=None): + self._cookies: dict[str, str] = {} + if cookies is not None: + if isinstance(cookies, Cookies): + self._cookies = dict(cookies._cookies) + elif isinstance(cookies, dict): + self._cookies = {k: str(v) for k, v in cookies.items()} + elif isinstance(cookies, (list, tuple)): + for k, v in cookies: + self._cookies[str(k)] = str(v) + else: + raise TypeError( + f"Cookies() argument must be dict, list, or Cookies, " + f"not {type(cookies).__name__}" + ) + + def set( + self, + name: str, + value, + *, + domain=None, + path=None, + secure=None, + expires=None, + samesite=None, + ) -> None: + self._cookies[name] = str(value) + + def get(self, name: str, default=None) -> str | None: + return self._cookies.get(name, default) + + def delete(self, name: str, *, domain=None, path=None) -> None: + self._cookies.pop(name, None) + + def clear(self) -> None: + self._cookies.clear() + + def update(self, cookies=None) -> None: + if isinstance(cookies, Cookies): + self._cookies.update(cookies._cookies) + elif isinstance(cookies, dict): + self._cookies.update({k: str(v) for k, v in cookies.items()}) + elif isinstance(cookies, (list, tuple)): + for k, v in cookies: + self._cookies[str(k)] = str(v) + + def setdefault(self, name: str, default=None) -> str: + if name not in self._cookies: + self._cookies[name] = str(default) if default is not None else "" + return self._cookies[name] + + def items(self): + return self._cookies.items() + + def keys(self): + return self._cookies.keys() + + def values(self): + return self._cookies.values() + + def extract_cookies(self, request) -> None: + """Populate cookies from a request's Cookie header.""" + cookie_header = None + if hasattr(request, "headers"): + cookie_header = request.headers.get("Cookie") or request.headers.get("cookie") + if cookie_header: + for item in cookie_header.split(";"): + item = item.strip() + if "=" in item: + name, _, value = item.partition("=") + self._cookies[name.strip()] = value.strip() + + def set_cookie_header(self, response) -> None: + """Process Set-Cookie headers from a response.""" + if hasattr(response, "headers"): + set_cookie = response.headers.get("set-cookie") or response.headers.get("Set-Cookie") + if set_cookie: + parts = set_cookie.split(";") + cookie_part = parts[0].strip() + if "=" in cookie_part: + name, _, value = cookie_part.partition("=") + self._cookies[name.strip()] = value.strip() + + def __setitem__(self, name: str, value) -> None: + self._cookies[name] = str(value) + + def __getitem__(self, name: str) -> str: + return self._cookies[name] + + def __delitem__(self, name: str) -> None: + del self._cookies[name] + + def __contains__(self, key: object) -> bool: + return key in self._cookies + + def __len__(self) -> int: + return len(self._cookies) + + def __iter__(self): + return iter(self._cookies) + + def __bool__(self) -> bool: + return bool(self._cookies) + + def __repr__(self) -> str: + items = ", ".join(f"{k!r}: {v!r}" for k, v in self._cookies.items()) + return f"Cookies({{{items}}})" diff --git a/crates/eggfetch-python/python/eggfetch/compat/httpx/_exceptions.py b/crates/eggfetch-python/python/eggfetch/compat/httpx/_exceptions.py new file mode 100644 index 00000000..2b717f03 --- /dev/null +++ b/crates/eggfetch-python/python/eggfetch/compat/httpx/_exceptions.py @@ -0,0 +1,145 @@ +"""HTTPX-compatible exception hierarchy for eggfetch.""" + + +class HTTPError(Exception): + """Base exception for HTTPX-compatible errors.""" + + def __init__(self, request=None, *, message=""): + self._request = request + self._message = message + super().__init__(message if message else str(self)) + + @property + def request(self): + return self._request + + def __repr__(self): + return f"{type(self).__name__}({self._message!r})" + + +class HTTPStatusError(HTTPError): + """Exception raised when an HTTP response indicates an error status.""" + + def __init__(self, message, request, response): + super().__init__(request=request, message=message) + self._response = response + + @property + def response(self): + return self._response + + def __repr__(self): + return ( + f"{type(self).__name__}({self._message!r}, " + f"request={self._request!r}, response={self._response!r})" + ) + + +class RequestError(HTTPError): + """Base exception for request-related errors.""" + + +class TransportError(RequestError): + """Base exception for transport-related errors.""" + + +class TimeoutException(TransportError): + """Exception raised when a request times out.""" + + +class ConnectTimeout(TimeoutException): + """Exception raised when a connection attempt times out.""" + + +class ReadTimeout(TimeoutException): + """Exception raised when reading from the network times out.""" + + +class WriteTimeout(TimeoutException): + """Exception raised when writing to the network times out.""" + + +class PoolTimeout(TimeoutException): + """Exception raised when waiting for a connection from the pool times out.""" + + +class NetworkError(TransportError): + """Base exception for network-related errors.""" + + +class CloseError(NetworkError): + """Exception raised when closing a connection fails.""" + + +class ConnectError(NetworkError): + """Exception raised when establishing a connection fails.""" + + +class ReadError(NetworkError): + """Exception raised when reading from the network fails.""" + + +class WriteError(NetworkError): + """Exception raised when writing to the network fails.""" + + +class ProtocolError(TransportError): + """Base exception for protocol-related errors.""" + + +class LocalProtocolError(ProtocolError): + """Exception raised when a local protocol error occurs.""" + + +class RemoteProtocolError(ProtocolError): + """Exception raised when a remote protocol error occurs.""" + + +class ProxyError(TransportError): + """Exception raised when a proxy error occurs.""" + + +class UnsupportedProtocol(TransportError): + """Exception raised when an unsupported protocol is used.""" + + +class DecodingError(RequestError): + """Exception raised when response decoding fails.""" + + +class TooManyRedirects(RequestError): + """Exception raised when too many redirects are followed.""" + + +class StreamError(Exception): + """Base exception for stream-related errors.""" + + +class RequestNotRead(StreamError): + """Exception raised when attempting to read a request that hasn't been read.""" + + +class ResponseNotRead(StreamError): + """Exception raised when attempting to read a response that hasn't been read.""" + + +class StreamClosed(StreamError): + """Exception raised when attempting to read from a closed stream.""" + + +class StreamConsumed(StreamError): + """Exception raised when attempting to read from a consumed stream.""" + + +class InvalidURL(Exception): + """Exception raised when an invalid URL is provided.""" + + def __init__(self, message): + super().__init__(message) + + +class CookieConflict(Exception): + """Exception raised when a cookie conflict occurs.""" + + def __init__(self, message): + super().__init__(message) diff --git a/crates/eggfetch-python/python/eggfetch/compat/httpx/_headers.py b/crates/eggfetch-python/python/eggfetch/compat/httpx/_headers.py new file mode 100644 index 00000000..b6f3e1b6 --- /dev/null +++ b/crates/eggfetch-python/python/eggfetch/compat/httpx/_headers.py @@ -0,0 +1,180 @@ +"""HTTPX-compatible Headers class for eggfetch.""" + +from __future__ import annotations + + +class Headers: + """HTTPX-compatible Headers class. + + Internal storage: list of (name, value) tuples. + Names are stored in lowercase for case-insensitive lookup. + """ + + __slots__ = ("_items", "_encoding") + + def __init__(self, headers=None, encoding: str = "utf-8"): + self._items: list[tuple[str, str]] = [] + self._encoding = encoding + if headers is not None: + self._init_from(headers) + + def _init_from(self, headers) -> None: + if isinstance(headers, Headers): + self._items = list(headers._items) + self._encoding = headers._encoding + return + if isinstance(headers, dict): + items = headers.items() + elif isinstance(headers, (list, tuple)): + items = headers + else: + raise TypeError( + f"Headers() argument must be dict, list, or Headers, " + f"not {type(headers).__name__}" + ) + for name, value in items: + if isinstance(name, bytes): + name = name.decode("ascii") + if isinstance(value, bytes): + value = value.decode("ascii") + self._validate(name, value) + self._items.append((name.lower(), value)) + + @staticmethod + def _validate(name: str, value: str) -> None: + if "\r" in name or "\n" in name: + raise ValueError(f"Header name {name!r} contains invalid character CR/LF") + if "\r" in value or "\n" in value: + raise ValueError(f"Header value for {name!r} contains invalid character CR/LF") + + def _normalize_name(self, name) -> str: + if isinstance(name, bytes): + return name.decode("ascii").lower() + return name.lower() + + def get(self, name: str, default=None): + norm = self._normalize_name(name) + result = None + for k, v in self._items: + if k == norm: + result = v + return result if result is not None else default + + def get_list(self, name: str) -> list[str]: + norm = self._normalize_name(name) + return [v for k, v in self._items if k == norm] + + def multi_items(self) -> list[tuple[str, str]]: + return list(self._items) + + def keys(self) -> list[str]: + return list(dict.fromkeys(k for k, _ in self._items)) + + def values(self) -> list[str]: + seen = set() + result = [] + for k, v in self._items: + if k not in seen: + seen.add(k) + result.append(v) + return result + + def items(self) -> list[tuple[str, str]]: + seen = set() + result = [] + for k, v in self._items: + if k not in seen: + seen.add(k) + result.append((k, v)) + return result + + def __iter__(self): + return iter(self.keys()) + + def __len__(self) -> int: + return len(self._items) + + def __contains__(self, key: object) -> bool: + norm = self._normalize_name(key) + return any(k == norm for k, _ in self._items) + + def __setitem__(self, name: str, value: str) -> None: + self._validate(name, value) + norm = name.lower() + self._items = [(k, v) for k, v in self._items if k != norm] + self._items.append((norm, value)) + + def __delitem__(self, name: str) -> None: + norm = self._normalize_name(name) + before = len(self._items) + self._items = [(k, v) for k, v in self._items if k != norm] + if len(self._items) == before: + raise KeyError(name) + + def __getitem__(self, name: str) -> str: + norm = self._normalize_name(name) + result = None + for k, v in self._items: + if k == norm: + result = v + if result is None: + raise KeyError(name) + return result + + def update(self, headers) -> None: + if isinstance(headers, Headers): + items = headers._items + elif isinstance(headers, dict): + items = [(k.lower(), v) for k, v in headers.items()] + elif isinstance(headers, (list, tuple)): + items = [ + (self._normalize_name(k), v) if isinstance(k, str) else (k.decode("ascii").lower(), v) + for k, v in headers + ] + else: + raise TypeError( + f"update() argument must be Headers, dict, or list of tuples, " + f"not {type(headers).__name__}" + ) + for k, v in items: + self._items = [(ek, ev) for ek, ev in self._items if ek != k] + self._items.append((k, v)) + + def pop(self, name: str, default=None): + norm = self._normalize_name(name) + found = False + new_items = [] + result = default + for k, v in self._items: + if k == norm and not found: + found = True + result = v + else: + new_items.append((k, v)) + self._items = new_items + return result + + def clear(self) -> None: + self._items.clear() + + def copy(self) -> "Headers": + new = Headers(encoding=self._encoding) + new._items = list(self._items) + return new + + @property + def raw(self) -> list[tuple[bytes, bytes]]: + return [(k.encode("ascii"), v.encode("ascii")) for k, v in self._items] + + @property + def encoding(self) -> str: + return self._encoding + + def __eq__(self, other): + if isinstance(other, Headers): + return self._items == other._items + return NotImplemented + + def __repr__(self) -> str: + items_str = ", ".join(f"{k!r}: {v!r}" for k, v in self._items) + return f"Headers({items_str})" diff --git a/crates/eggfetch-python/python/eggfetch/compat/httpx/_limits.py b/crates/eggfetch-python/python/eggfetch/compat/httpx/_limits.py new file mode 100644 index 00000000..3370abbf --- /dev/null +++ b/crates/eggfetch-python/python/eggfetch/compat/httpx/_limits.py @@ -0,0 +1,53 @@ +"""HTTPX-compatible Limits class for eggfetch.""" + +from __future__ import annotations + + +class Limits: + """HTTPX-compatible Limits class. + + Limits(max_connections=None, max_keepalive_connections=None, keepalive_expiry=5.0) + """ + + __slots__ = ("_max_connections", "_max_keepalive_connections", "_keepalive_expiry") + + def __init__( + self, + max_connections=None, + max_keepalive_connections=None, + keepalive_expiry=5.0, + ): + self._max_connections = max_connections + self._max_keepalive_connections = max_keepalive_connections + self._keepalive_expiry = keepalive_expiry + + @property + def max_connections(self) -> int | None: + return self._max_connections + + @property + def max_keepalive_connections(self) -> int | None: + return self._max_keepalive_connections + + @property + def keepalive_expiry(self) -> float | None: + return self._keepalive_expiry + + def __eq__(self, other): + if isinstance(other, Limits): + return ( + self._max_connections == other._max_connections + and self._max_keepalive_connections == other._max_keepalive_connections + and self._keepalive_expiry == other._keepalive_expiry + ) + return NotImplemented + + def __repr__(self) -> str: + parts = [] + if self._max_connections is not None: + parts.append(f"max_connections={self._max_connections!r}") + if self._max_keepalive_connections is not None: + parts.append(f"max_keepalive_connections={self._max_keepalive_connections!r}") + if self._keepalive_expiry is not None: + parts.append(f"keepalive_expiry={self._keepalive_expiry!r}") + return f"Limits({', '.join(parts)})" diff --git a/crates/eggfetch-python/python/eggfetch/compat/httpx/_proxy.py b/crates/eggfetch-python/python/eggfetch/compat/httpx/_proxy.py new file mode 100644 index 00000000..df8a812b --- /dev/null +++ b/crates/eggfetch-python/python/eggfetch/compat/httpx/_proxy.py @@ -0,0 +1,70 @@ +"""HTTPX-compatible Proxy class for eggfetch.""" + +from __future__ import annotations + + +class Proxy: + """HTTPX-compatible Proxy class. + + Phase 2: accept and store; Phase 4 executes. + """ + + __slots__ = ("_url", "_headers", "_auth") + + def __init__(self, url, *, headers=None, auth=None): + from ._urls import URL + + if isinstance(url, URL): + self._url = url + elif isinstance(url, str): + self._url = URL(url) + else: + raise TypeError( + f"Proxy() url must be str or URL, got {type(url).__name__}" + ) + + self._headers = {} + if headers is not None: + if isinstance(headers, dict): + self._headers = dict(headers) + else: + raise TypeError( + f"Proxy() headers must be dict or None, got {type(headers).__name__}" + ) + + self._auth = auth + + @property + def url(self): + return self._url + + @property + def headers(self) -> dict: + return self._headers + + @property + def auth(self): + return self._auth + + @property + def raw_auth(self): + if self._auth is None: + return None + if isinstance(self._auth, (list, tuple)): + return tuple(self._auth) + return None + + @property + def ssl_context(self): + return None + + def __repr__(self) -> str: + url_str = str(self._url) + if self._url.password: + url_str = url_str.replace(f":{self._url.password}@", ":***@") + parts = [f"url={url_str!r}"] + if self._headers: + parts.append(f"headers={self._headers!r}") + if self._auth is not None: + parts.append("auth=***") + return f"Proxy({', '.join(parts)})" diff --git a/crates/eggfetch-python/python/eggfetch/compat/httpx/_request.py b/crates/eggfetch-python/python/eggfetch/compat/httpx/_request.py new file mode 100644 index 00000000..31c9abfa --- /dev/null +++ b/crates/eggfetch-python/python/eggfetch/compat/httpx/_request.py @@ -0,0 +1,272 @@ +"""HTTPX-compatible Request class for eggfetch.""" + +from __future__ import annotations + +import typing +from urllib.parse import urlparse, urlencode + +from eggfetch.compat.httpx._urls import URL, QueryParams +from eggfetch.compat.httpx._headers import Headers +from eggfetch.compat.httpx._cookies import Cookies + +if typing.TYPE_CHECKING: + from typing import AsyncIterator, Iterator + + +class Request: + """HTTPX-compatible Request object.""" + + __slots__ = ( + "_method", + "_url", + "_headers", + "_cookies", + "_params", + "_content", + "_stream", + "_extensions", + "_http_version", + "_is_stream_consumed", + "_stream_consumed", + ) + + def __init__( + self, + method: str, + url: URL | str, + *, + params=None, + headers=None, + cookies=None, + content: bytes | None = None, + data=None, + files=None, + json=None, + stream=None, + extensions: dict | None = None, + ) -> None: + # Validate mutual exclusion of body sources + body_sources = [ + name + for name, val in [ + ("content", content), + ("data", data), + ("files", files), + ("json", json), + ("stream", stream), + ] + if val is not None + ] + if len(body_sources) > 1: + raise ValueError( + f"Conflicting body sources: {', '.join(body_sources)}. " + "Only one of content, data, files, json, or stream may be provided." + ) + + self._method = method.upper() + self._url = URL(url) if not isinstance(url, URL) else url + self._http_version = "HTTP/1.1" + self._is_stream_consumed = False + self._stream_consumed = False + self._stream = stream + + # Build headers from user-provided value + if isinstance(headers, Headers): + self._headers = headers + else: + self._headers = Headers(headers) + + # Build params + if isinstance(params, QueryParams): + self._params = params + else: + self._params = QueryParams(params) + + # Build cookies + if isinstance(cookies, Cookies): + self._cookies = cookies + else: + self._cookies = Cookies(cookies) + + # Handle body content + self._content: bytes | None = None + + if content is not None: + self._content = content if isinstance(content, bytes) else content.encode("utf-8") + elif json is not None: + import json as _json + + self._content = _json.dumps(json).encode("utf-8") + if "content-type" not in self._headers: + self._headers["content-type"] = "application/json" + elif data is not None: + if isinstance(data, dict): + encoded = urlencode(data) + elif isinstance(data, (list, tuple)): + encoded = urlencode(data) + elif isinstance(data, str): + encoded = data + elif isinstance(data, bytes): + self._content = data + encoded = None + else: + encoded = str(data) + if self._content is None and encoded is not None: + self._content = encoded.encode("utf-8") + if "content-type" not in self._headers: + self._headers["content-type"] = "application/x-www-form-urlencoded" + elif files is not None: + # Simplified: serialize files as multipart-like placeholder + self._content = self._encode_files(files) + if "content-type" not in self._headers: + self._headers["content-type"] = "multipart/form-data" + + # Auto-headers + host = self._url.host + if host is not None: + port = self._url.port + scheme = self._url.scheme + if port and ( + (scheme == "http" and port != 80) or (scheme == "https" and port != 443) + ): + host = f"{host}:{port}" + if "host" not in self._headers: + self._headers["host"] = host + + if stream is not None: + if "transfer-encoding" not in self._headers: + self._headers["transfer-encoding"] = "chunked" + elif self._content is not None: + if "content-length" not in self._headers: + self._headers["content-length"] = str(len(self._content)) + + # Extensions + self._extensions: dict = extensions if extensions is not None else {} + + @staticmethod + def _encode_files(files) -> bytes: + """Minimal multipart encoding for files parameter.""" + boundary = "----eggfetchboundary" + parts: list[bytes] = [] + + if isinstance(files, dict): + file_items = files.items() + elif isinstance(files, (list, tuple)): + file_items = files + else: + file_items = [("file", files)] + + for field_name, file_tuple in file_items: + if isinstance(file_tuple, tuple): + if len(file_tuple) == 3: + filename, fileobj, content_type = file_tuple + elif len(file_tuple) == 2: + filename, fileobj = file_tuple + content_type = "application/octet-stream" + else: + filename = file_tuple[0] + fileobj = file_tuple[1] if len(file_tuple) > 1 else b"" + content_type = "application/octet-stream" + else: + filename = str(field_name) + fileobj = file_tuple + content_type = "application/octet-stream" + + if isinstance(fileobj, (bytes, bytearray)): + body = bytes(fileobj) + elif isinstance(fileobj, str): + body = fileobj.encode("utf-8") + elif hasattr(fileobj, "read"): + body = fileobj.read() + if isinstance(body, str): + body = body.encode("utf-8") + else: + body = str(fileobj).encode("utf-8") + + part = ( + f"--{boundary}\r\n" + f'Content-Disposition: form-data; name="{field_name}"; filename="{filename}"\r\n' + f"Content-Type: {content_type}\r\n\r\n" + ).encode("utf-8") + part += body + b"\r\n" + parts.append(part) + + parts.append(f"--{boundary}--\r\n".encode("utf-8")) + return b"".join(parts) + + @property + def method(self) -> str: + return self._method + + @property + def url(self) -> URL: + return self._url + + @property + def headers(self) -> Headers: + return self._headers + + @property + def cookies(self) -> Cookies: + return self._cookies + + @property + def params(self) -> QueryParams: + return self._params + + @property + def content(self) -> bytes | None: + return self._content + + @property + def stream(self): + return self._stream + + @property + def extensions(self) -> dict: + return self._extensions + + @property + def is_stream_consumed(self) -> bool: + return self._is_stream_consumed + + @property + def http_version(self) -> str: + return self._http_version + + def read(self) -> bytes: + if self._stream is not None and self._content is None: + chunks: list[bytes] = [] + for chunk in self._stream: + if isinstance(chunk, bytes): + chunks.append(chunk) + elif isinstance(chunk, str): + chunks.append(chunk.encode("utf-8")) + else: + chunks.append(str(chunk).encode("utf-8")) + self._content = b"".join(chunks) + self._is_stream_consumed = True + self._stream_consumed = True + if self._content is None: + return b"" + return self._content + + async def aread(self) -> bytes: + if self._stream is not None and self._content is None: + chunks: list[bytes] = [] + async for chunk in self._stream: # type: ignore[union-attr] + if isinstance(chunk, bytes): + chunks.append(chunk) + elif isinstance(chunk, str): + chunks.append(chunk.encode("utf-8")) + else: + chunks.append(str(chunk).encode("utf-8")) + self._content = b"".join(chunks) + self._is_stream_consumed = True + self._stream_consumed = True + if self._content is None: + return b"" + return self._content + + def __repr__(self) -> str: + return f"" diff --git a/crates/eggfetch-python/python/eggfetch/compat/httpx/_response.py b/crates/eggfetch-python/python/eggfetch/compat/httpx/_response.py new file mode 100644 index 00000000..6efc9b57 --- /dev/null +++ b/crates/eggfetch-python/python/eggfetch/compat/httpx/_response.py @@ -0,0 +1,445 @@ +"""HTTPX-compatible Response class for eggfetch.""" + +from __future__ import annotations + +import json as _json +import typing +from datetime import timedelta + +from eggfetch.compat.httpx._urls import URL +from eggfetch.compat.httpx._headers import Headers +from eggfetch.compat.httpx._cookies import Cookies +from eggfetch.compat.httpx._exceptions import HTTPStatusError + +if typing.TYPE_CHECKING: + from typing import Any, AsyncIterator, Iterator + + +class Response: + """HTTPX-compatible Response object.""" + + __slots__ = ( + "_status_code", + "_headers", + "_url", + "_reason_phrase", + "_http_version", + "_encoding", + "_default_encoding", + "_content", + "_text", + "_json", + "_cookies", + "_request", + "_extensions", + "_history", + "_elapsed", + "_num_bytes_downloaded", + "_stream", + "_is_closed", + "_stream_consumed", + ) + + _REASON_PHRASES: dict[int, str] = { + 100: "Continue", + 101: "Switching Protocols", + 102: "Processing", + 103: "Early Hints", + 200: "OK", + 201: "Created", + 202: "Accepted", + 203: "Non-Authoritative Information", + 204: "No Content", + 205: "Reset Content", + 206: "Partial Content", + 207: "Multi-Status", + 208: "Already Reported", + 226: "IM Used", + 300: "Multiple Choices", + 301: "Moved Permanently", + 302: "Found", + 303: "See Other", + 304: "Not Modified", + 305: "Use Proxy", + 307: "Temporary Redirect", + 308: "Permanent Redirect", + 400: "Bad Request", + 401: "Unauthorized", + 402: "Payment Required", + 403: "Forbidden", + 404: "Not Found", + 405: "Method Not Allowed", + 406: "Not Acceptable", + 407: "Proxy Authentication Required", + 408: "Request Timeout", + 409: "Conflict", + 410: "Gone", + 411: "Length Required", + 412: "Precondition Failed", + 413: "Content Too Large", + 414: "URI Too Long", + 415: "Unsupported Media Type", + 416: "Range Not Satisfiable", + 417: "Expectation Failed", + 418: "I'm a Teapot", + 421: "Misdirected Request", + 422: "Unprocessable Content", + 423: "Locked", + 424: "Failed Dependency", + 425: "Too Early", + 426: "Upgrade Required", + 428: "Precondition Required", + 429: "Too Many Requests", + 431: "Request Header Fields Too Large", + 451: "Unavailable For Legal Reasons", + 500: "Internal Server Error", + 501: "Not Implemented", + 502: "Bad Gateway", + 503: "Service Unavailable", + 504: "Gateway Timeout", + 505: "HTTP Version Not Supported", + 506: "Variant Also Negotiates", + 507: "Insufficient Storage", + 508: "Loop Detected", + 510: "Not Extended", + 511: "Network Authentication Required", + } + + def __init__( + self, + status_code: int, + *, + headers=None, + content: bytes | None = None, + text: str | None = None, + html: str | None = None, + json: Any = None, + stream=None, + request=None, + extensions: dict | None = None, + history: list | None = None, + default_encoding: str = "utf-8", + ) -> None: + # Validate mutual exclusion of content sources + body_sources = [ + name + for name, val in [ + ("content", content), + ("text", text), + ("html", html), + ("json", json), + ("stream", stream), + ] + if val is not None + ] + if len(body_sources) > 1: + raise ValueError( + f"Conflicting body sources: {', '.join(body_sources)}. " + "Only one of content, text, html, json, or stream may be provided." + ) + + self._status_code = status_code + self._default_encoding = default_encoding + self._request = request + self._extensions: dict = extensions if extensions is not None else {} + self._history: list[Response] = list(history) if history else [] + self._is_closed = False + self._stream_consumed = False + self._stream = stream + self._num_bytes_downloaded = 0 + + # Build headers + if isinstance(headers, Headers): + self._headers = headers + else: + self._headers = Headers(headers) + + # Build content + self._content: bytes | None = None + self._json: Any = None + self._text: str | None = None + self._encoding: str | None = None + + if content is not None: + self._content = content if isinstance(content, bytes) else content.encode("utf-8") + self._num_bytes_downloaded = len(self._content) + elif text is not None: + self._text = text + enc = self.charset_encoding or default_encoding + self._content = text.encode(enc) + self._num_bytes_downloaded = len(self._content) + elif html is not None: + self._text = html + self._encoding = "utf-8" + self._content = html.encode("utf-8") + self._num_bytes_downloaded = len(self._content) + if "content-type" not in self._headers: + self._headers["content-type"] = "text/html; charset=utf-8" + elif json is not None: + self._json = json + self._content = _json.dumps(json).encode("utf-8") + self._num_bytes_downloaded = len(self._content) + if "content-type" not in self._headers: + self._headers["content-type"] = "application/json" + elif stream is None: + self._content = b"" + self._num_bytes_downloaded = 0 + + # Derived properties + self._reason_phrase = self._REASON_PHRASES.get(status_code, "") + self._http_version = "HTTP/1.1" + self._url = URL("") + self._elapsed = timedelta(0) + + # Extract URL from request + if request is not None and hasattr(request, "url"): + self._url = request.url + + # Build cookies from headers + self._cookies = Cookies() + self._cookies.set_cookie_header(self) + + @property + def status_code(self) -> int: + return self._status_code + + @property + def headers(self) -> Headers: + return self._headers + + @property + def url(self) -> URL: + return self._url + + @property + def reason_phrase(self) -> str: + return self._reason_phrase + + @property + def http_version(self) -> str: + return self._http_version + + @property + def encoding(self) -> str | None: + return self._encoding + + @encoding.setter + def encoding(self, value: str) -> None: + self._encoding = value + + @property + def charset_encoding(self) -> str | None: + content_type = self._headers.get("content-type", "") + if not content_type: + return None + for part in content_type.split(";"): + part = part.strip() + if part.lower().startswith("charset="): + return part.split("=", 1)[1].strip() + return None + + @property + def content(self) -> bytes: + if self._content is None: + if self._stream is not None: + raise RuntimeError( + "Response content has not been read. Call .read() or .aread() first." + ) + return b"" + return self._content + + @property + def text(self) -> str: + if self._content is None: + if self._stream is not None: + raise RuntimeError( + "Response content has not been read. Call .read() or .aread() first." + ) + return "" + enc = self._encoding or self.charset_encoding or self._default_encoding + return self._content.decode(enc) + + @property + def cookies(self) -> Cookies: + return self._cookies + + @property + def elapsed(self) -> timedelta: + return self._elapsed + + @property + def history(self) -> list[Response]: + return self._history + + @property + def request(self): + return self._request + + @property + def extensions(self) -> dict: + return self._extensions + + @property + def links(self) -> dict: + link_header = self._headers.get("link", "") + if not link_header: + return {} + result: dict[str, dict[str, str]] = {} + for part in link_header.split(","): + part = part.strip() + if not part: + continue + url_part, *param_parts = part.split(";") + url_str = url_part.strip().strip("<>") + attrs: dict[str, str] = {} + for param in param_parts: + param = param.strip() + if "=" in param: + key, _, value = param.partition("=") + attrs[key.strip()] = value.strip().strip('"') + rel = attrs.pop("rel", "alternate") + result[rel] = {"url": url_str, **attrs} + return result + + @property + def num_bytes_downloaded(self) -> int: + return self._num_bytes_downloaded + + @property + def is_success(self) -> bool: + return 200 <= self._status_code < 300 + + @property + def is_redirect(self) -> bool: + return self._status_code in (301, 302, 303, 307, 308) or ( + 300 <= self._status_code < 400 + ) + + @property + def is_client_error(self) -> bool: + return 400 <= self._status_code < 500 + + @property + def is_server_error(self) -> bool: + return 500 <= self._status_code < 600 + + @property + def is_error(self) -> bool: + return self.is_client_error or self.is_server_error + + @property + def is_informational(self) -> bool: + return 100 <= self._status_code < 200 + + @property + def has_redirect_location(self) -> bool: + return "location" in self._headers and self.is_redirect + + def json(self, **kwargs) -> Any: + if self._json is not None: + return self._json + if self._content is None: + if self._stream is not None: + raise RuntimeError( + "Response content has not been read. Call .read() or .aread() first." + ) + raise RuntimeError("Response content is empty.") + return _json.loads(self._content, **kwargs) + + def raise_for_status(self) -> Response: + if self.is_error: + message = f"Server error {self._status_code}" + if self._reason_phrase: + message = f"Client error {self._status_code}" if self.is_client_error else f"Server error {self._status_code}" + raise HTTPStatusError(message, request=self._request, response=self) + return self + + def read(self) -> bytes: + if self._stream is not None and not self._stream_consumed: + chunks: list[bytes] = [] + for chunk in self._stream: + if isinstance(chunk, bytes): + chunks.append(chunk) + elif isinstance(chunk, str): + chunks.append(chunk.encode("utf-8")) + else: + chunks.append(str(chunk).encode("utf-8")) + self._content = b"".join(chunks) + self._num_bytes_downloaded = len(self._content) + self._stream_consumed = True + if self._content is None: + return b"" + return self._content + + async def aread(self) -> bytes: + if self._stream is not None and not self._stream_consumed: + chunks: list[bytes] = [] + async for chunk in self._stream: # type: ignore[union-attr] + if isinstance(chunk, bytes): + chunks.append(chunk) + elif isinstance(chunk, str): + chunks.append(chunk.encode("utf-8")) + else: + chunks.append(str(chunk).encode("utf-8")) + self._content = b"".join(chunks) + self._num_bytes_downloaded = len(self._content) + self._stream_consumed = True + if self._content is None: + return b"" + return self._content + + def close(self) -> None: + self._is_closed = True + if hasattr(self._stream, "close"): + self._stream.close() + + async def aclose(self) -> None: + self._is_closed = True + if hasattr(self._stream, "aclose"): + await self._stream.aclose() + + def iter_bytes(self, chunk_size: int = 8192) -> Iterator[bytes]: + data = self.content + for i in range(0, len(data), chunk_size): + yield data[i : i + chunk_size] + + def iter_text(self, chunk_size: int = 8192) -> Iterator[str]: + enc = self._encoding or self.charset_encoding or self._default_encoding + data = self.content.decode(enc) + for i in range(0, len(data), chunk_size): + yield data[i : i + chunk_size] + + def iter_lines(self) -> Iterator[str]: + text = self.text + for line in text.split("\n"): + if line.endswith("\r"): + line = line[:-1] + yield line + + def iter_raw(self) -> Iterator[bytes]: + yield from self.iter_bytes() + + async def aiter_bytes(self, chunk_size: int = 8192) -> AsyncIterator[bytes]: + data = self.content + for i in range(0, len(data), chunk_size): + yield data[i : i + chunk_size] + + async def aiter_text(self, chunk_size: int = 8192) -> AsyncIterator[str]: + enc = self._encoding or self.charset_encoding or self._default_encoding + data = self.content.decode(enc) + for i in range(0, len(data), chunk_size): + yield data[i : i + chunk_size] + + async def aiter_lines(self) -> AsyncIterator[str]: + text = self.text + for line in text.split("\n"): + if line.endswith("\r"): + line = line[:-1] + yield line + + async def aiter_raw(self) -> AsyncIterator[bytes]: + async for chunk in self.aiter_bytes(): + yield chunk + + def __repr__(self) -> str: + return f"" diff --git a/crates/eggfetch-python/python/eggfetch/compat/httpx/_status_codes.py b/crates/eggfetch-python/python/eggfetch/compat/httpx/_status_codes.py new file mode 100644 index 00000000..e13272da --- /dev/null +++ b/crates/eggfetch-python/python/eggfetch/compat/httpx/_status_codes.py @@ -0,0 +1,80 @@ +"""HTTPX-compatible status codes namespace for eggfetch.""" + + +class _StatusCodeGroup: + """Namespace for HTTP status codes.""" + + def __getattr__(self, name): + try: + return object.__getattribute__(self, name) + except AttributeError: + raise AttributeError( + f"module 'eggfetch.compat.httpx._status_codes' has no attribute {name!r}" + ) + + +codes = _StatusCodeGroup() + +codes.CONTINUE = 100 +codes.SWITCHING_PROTOCOLS = 101 +codes.PROCESSING = 102 +codes.EARLY_HINTS = 103 +codes.OK = 200 +codes.CREATED = 201 +codes.ACCEPTED = 202 +codes.NON_AUTHORITATIVE_INFORMATION = 203 +codes.NO_CONTENT = 204 +codes.RESET_CONTENT = 205 +codes.PARTIAL_CONTENT = 206 +codes.MULTI_STATUS = 207 +codes.ALREADY_REPORTED = 208 +codes.IM_USED = 226 +codes.MULTIPLE_CHOICES = 300 +codes.MOVED_PERMANENTLY = 301 +codes.FOUND = 302 +codes.SEE_OTHER = 303 +codes.NOT_MODIFIED = 304 +codes.USE_PROXY = 305 +codes.RESERVED = 306 +codes.TEMPORARY_REDIRECT = 307 +codes.PERMANENT_REDIRECT = 308 +codes.BAD_REQUEST = 400 +codes.UNAUTHORIZED = 401 +codes.PAYMENT_REQUIRED = 402 +codes.FORBIDDEN = 403 +codes.NOT_FOUND = 404 +codes.METHOD_NOT_ALLOWED = 405 +codes.NOT_ACCEPTABLE = 406 +codes.PROXY_AUTHENTICATION_REQUIRED = 407 +codes.REQUEST_TIMEOUT = 408 +codes.CONFLICT = 409 +codes.GONE = 410 +codes.LENGTH_REQUIRED = 411 +codes.PRECONDITION_FAILED = 412 +codes.CONTENT_TOO_LARGE = 413 +codes.URI_TOO_LONG = 414 +codes.UNSUPPORTED_MEDIA_TYPE = 415 +codes.RANGE_NOT_SATISFIABLE = 416 +codes.EXPECTATION_FAILED = 417 +codes.IM_A_TEAPOT = 418 +codes.MISDIRECTED_REQUEST = 421 +codes.UNPROCESSABLE_CONTENT = 422 +codes.LOCKED = 423 +codes.FAILED_DEPENDENCY = 424 +codes.TOO_EARLY = 425 +codes.UPGRADE_REQUIRED = 426 +codes.PRECONDITION_REQUIRED = 428 +codes.TOO_MANY_REQUESTS = 429 +codes.REQUEST_HEADER_FIELDS_TOO_LARGE = 431 +codes.UNAVAILABLE_FOR_LEGAL_REASONS = 451 +codes.INTERNAL_SERVER_ERROR = 500 +codes.NOT_IMPLEMENTED = 501 +codes.BAD_GATEWAY = 502 +codes.SERVICE_UNAVAILABLE = 503 +codes.GATEWAY_TIMEOUT = 504 +codes.HTTP_VERSION_NOT_SUPPORTED = 505 +codes.VARIANT_ALSO_NEGOTIATES = 506 +codes.INSUFFICIENT_STORAGE = 507 +codes.LOOP_DETECTED = 508 +codes.NOT_EXTENDED = 510 +codes.NETWORK_AUTHENTICATION_REQUIRED = 511 diff --git a/crates/eggfetch-python/python/eggfetch/compat/httpx/_timeout.py b/crates/eggfetch-python/python/eggfetch/compat/httpx/_timeout.py new file mode 100644 index 00000000..cf439fa0 --- /dev/null +++ b/crates/eggfetch-python/python/eggfetch/compat/httpx/_timeout.py @@ -0,0 +1,116 @@ +"""HTTPX-compatible Timeout class for eggfetch.""" + +from __future__ import annotations + +import copy + + +class Timeout: + """HTTPX-compatible Timeout class. + + Timeout(timeout=5.0, *, connect=None, read=None, write=None, pool=None) + """ + + __slots__ = ("_connect", "_read", "_write", "_pool", "_total") + + def __init__(self, timeout=5.0, *, connect=None, read=None, write=None, pool=None): + if connect is None: + connect = timeout + if read is None: + read = timeout + if write is None: + write = timeout + if pool is None: + pool = timeout + + self._validate_value(connect, "connect") + self._validate_value(read, "read") + self._validate_value(write, "write") + self._validate_value(pool, "pool") + + self._connect = connect + self._read = read + self._write = write + self._pool = pool + self._total = timeout + + @staticmethod + def _validate_value(value, name: str) -> None: + if value is not None: + if not isinstance(value, (int, float)): + raise TypeError(f"Timeout {name} must be None or a number, got {type(value).__name__}") + if value < 0: + raise ValueError(f"Timeout {name} must be a positive number, got {value}") + if isinstance(value, float) and (value != value): # NaN check + raise ValueError(f"Timeout {name} must be a finite number, got NaN") + + @property + def connect(self) -> float | None: + return self._connect + + @property + def read(self) -> float | None: + return self._read + + @property + def write(self) -> float | None: + return self._write + + @property + def pool(self) -> float | None: + return self._pool + + @property + def total(self) -> float | None: + return self._total + + @property + def as_dict(self) -> dict: + return { + "connect": self._connect, + "read": self._read, + "write": self._write, + "pool": self._pool, + } + + def __eq__(self, other): + if isinstance(other, Timeout): + return ( + self._connect == other._connect + and self._read == other._read + and self._write == other._write + and self._pool == other._pool + and self._total == other._total + ) + return NotImplemented + + def __repr__(self) -> str: + parts = [] + if self._connect is not None: + parts.append(f"connect={self._connect!r}") + if self._read is not None: + parts.append(f"read={self._read!r}") + if self._write is not None: + parts.append(f"write={self._write!r}") + if self._pool is not None: + parts.append(f"pool={self._pool!r}") + return f"Timeout({', '.join(parts)})" + + def __copy__(self): + new = Timeout.__new__(Timeout) + new._connect = self._connect + new._read = self._read + new._write = self._write + new._pool = self._pool + new._total = self._total + return new + + def __deepcopy__(self, memo): + new = Timeout.__new__(Timeout) + memo[id(self)] = new + new._connect = copy.deepcopy(self._connect, memo) + new._read = copy.deepcopy(self._read, memo) + new._write = copy.deepcopy(self._write, memo) + new._pool = copy.deepcopy(self._pool, memo) + new._total = copy.deepcopy(self._total, memo) + return new diff --git a/crates/eggfetch-python/python/eggfetch/compat/httpx/_urls.py b/crates/eggfetch-python/python/eggfetch/compat/httpx/_urls.py new file mode 100644 index 00000000..8c33c6e4 --- /dev/null +++ b/crates/eggfetch-python/python/eggfetch/compat/httpx/_urls.py @@ -0,0 +1,381 @@ +"""HTTPX-compatible URL and QueryParams classes for eggfetch.""" + +from __future__ import annotations + +import urllib.parse + + +def _is_http_url(url: str) -> bool: + return url.startswith("http://") or url.startswith("https://") + + +def _urlsplit(url: str) -> urllib.parse.SplitResult: + return urllib.parse.urlsplit(url) + + +class QueryParams: + """HTTPX-compatible QueryParams class. + + Internal storage: list of (key, value) tuples to preserve order and duplicates. + """ + + __slots__ = ("_items",) + + def __init__(self, args=None): + self._items: list[tuple[str, str]] = [] + if args is None: + pass + elif isinstance(args, str): + self._parse_string(args) + elif isinstance(args, dict): + self._items = [(k, v) for k, v in args.items()] + elif isinstance(args, (list, tuple)): + self._items = [(str(k), str(v)) for k, v in args] + elif isinstance(args, QueryParams): + self._items = list(args._items) + else: + raise TypeError( + f"QueryParams() argument must be str, dict, list, tuple, or QueryParams, " + f"not {type(args).__name__}" + ) + + def _parse_string(self, s: str) -> None: + if not s: + return + parsed = urllib.parse.parse_qsl(s, keep_blank_values=True) + self._items = parsed + + def get(self, key: str, default=None): + for k, v in reversed(self._items): + if k == key: + return v + return default + + def get_list(self, key: str) -> list[str]: + return [v for k, v in self._items if k == key] + + def multi_items(self) -> list[tuple[str, str]]: + return list(self._items) + + def keys(self) -> list[str]: + return list(dict.fromkeys(k for k, _ in self._items)) + + def values(self) -> list[str]: + seen = set() + result = [] + for k, v in self._items: + if k not in seen: + seen.add(k) + result.append(v) + return result + + def items(self) -> list[tuple[str, str]]: + seen = set() + result = [] + for k, v in self._items: + if k not in seen: + seen.add(k) + result.append((k, v)) + return result + + def add(self, key: str, value) -> None: + self._items.append((key, str(value))) + + def set(self, key: str, value) -> None: + new_items = [(k, v) for k, v in self._items if k != key] + new_items.append((key, str(value))) + self._items = new_items + + def remove(self, key: str) -> None: + self._items = [(k, v) for k, v in self._items if k != key] + + def update(self, params) -> None: + if isinstance(params, QueryParams): + new_items = [(k, v) for k, v in self._items if k not in dict(params._items)] + new_items.extend(params._items) + self._items = new_items + elif isinstance(params, dict): + for k, v in params.items(): + self.set(k, v) + elif isinstance(params, (list, tuple)): + for k, v in params: + self.set(k, str(v)) + else: + raise TypeError( + f"update() argument must be QueryParams, dict, or list of tuples, " + f"not {type(params).__name__}" + ) + + def merge(self, params) -> None: + if isinstance(params, QueryParams): + self._items.extend(params._items) + elif isinstance(params, dict): + for k, v in params.items(): + self.add(k, v) + elif isinstance(params, (list, tuple)): + for k, v in params: + self.add(k, str(v)) + else: + raise TypeError( + f"merge() argument must be QueryParams, dict, or list of tuples, " + f"not {type(params).__name__}" + ) + + def __getitem__(self, key: str) -> str: + for k, v in reversed(self._items): + if k == key: + return v + raise KeyError(key) + + def __setitem__(self, key: str, value) -> None: + self.set(key, value) + + def __delitem__(self, key: str) -> None: + before = len(self._items) + self.remove(key) + if len(self._items) == before: + raise KeyError(key) + + def __contains__(self, key: object) -> bool: + return any(k == key for k, _ in self._items) + + def __len__(self) -> int: + return len(self._items) + + def __iter__(self): + return iter(self.keys()) + + def __bool__(self) -> bool: + return len(self._items) > 0 + + def __eq__(self, other): + if isinstance(other, QueryParams): + return self._items == other._items + return NotImplemented + + def __hash__(self): + return hash(tuple(self._items)) + + def __str__(self) -> str: + return urllib.parse.urlencode(self._items) + + def __repr__(self) -> str: + return f"QueryParams({self!s})" + + +class URL: + """HTTPX-compatible URL class using urllib.parse internally.""" + + __slots__ = ("_parts", "_raw") + + def __new__(cls, url=None, *, base_url=None): + if isinstance(url, URL): + return url + instance = object.__new__(cls) + instance._init(url, base_url) + return instance + + def _init(self, url, base_url): + if url is None: + url = "" + if isinstance(url, bytes): + url = url.decode("ascii", errors="replace") + if isinstance(url, URL): + self._parts = url._parts + self._raw = url._raw + return + + if base_url is not None: + if isinstance(base_url, URL): + base_str = str(base_url) + else: + base_str = str(base_url) + url = urllib.parse.urljoin(base_str, url) + + self._raw = url + if _is_http_url(url): + self._parts = _urlsplit(url) + else: + parts = urllib.parse.urlsplit(url) + if parts.scheme: + self._parts = parts + else: + self._parts = _urlsplit(f"http://{url}") + + @property + def scheme(self) -> str: + return self._parts.scheme + + @property + def host(self) -> str | None: + return self._parts.hostname + + @property + def port(self) -> int | None: + return self._parts.port + + @property + def path(self) -> str: + return self._parts.path + + @property + def query(self) -> bytes: + if self._parts.query: + return self._parts.query.encode("utf-8") + return b"" + + @property + def fragment(self) -> str: + return self._parts.fragment + + @property + def username(self) -> str | None: + return self._parts.username + + @property + def password(self) -> str | None: + return self._parts.password + + @property + def netloc(self) -> bytes: + return self._parts.netloc.encode("utf-8") + + @property + def userinfo(self) -> bytes: + if self._parts.username: + userinfo = self._parts.username + if self._parts.password: + userinfo += ":" + self._parts.password + return userinfo.encode("utf-8") + return b"" + + @property + def raw_host(self) -> bytes | None: + if self._parts.hostname: + return self._parts.hostname.encode("utf-8") + return None + + @property + def raw_path(self) -> bytes: + path = self._parts.path + if not path: + path = "/" + return path.encode("utf-8") + + @property + def raw_scheme(self) -> bytes: + return self._parts.scheme.encode("utf-8") + + @property + def is_absolute_url(self) -> bool: + return bool(self._parts.scheme and self._parts.netloc) + + @property + def is_relative_url(self) -> bool: + return not self.is_absolute_url + + @property + def params(self) -> QueryParams: + if self._parts.query: + return QueryParams(self._parts.query) + return QueryParams() + + def copy_with(self, url=None, params=None): + if url is not None: + new = URL(url) + else: + new = URL(self) + + if params is not None: + if isinstance(params, QueryParams): + query_str = str(params) + elif isinstance(params, dict): + query_str = urllib.parse.urlencode(params) + else: + query_str = urllib.parse.urlencode(params) + parts = _urlsplit(str(new)) + new_parts = urllib.parse.SplitResult( + parts.scheme, parts.netloc, parts.path, query_str, parts.fragment + ) + new = object.__new__(URL) + new._parts = new_parts + new._raw = urllib.parse.urlunsplit(new_parts) + return new + + def copy_set_param(self, key: str, value) -> "URL": + params = self.params + params.set(key, value) + return self.copy_with(params=params) + + def copy_remove_param(self, key: str) -> "URL": + params = self.params + params.remove(key) + return self.copy_with(params=params) + + def copy_merge_params(self, params) -> "URL": + existing = self.params + existing.merge(params) + return self.copy_with(params=existing) + + def copy_add_param(self, key: str, value) -> "URL": + params = self.params + params.add(key, value) + return self.copy_with(params=params) + + def join(self, other: "URL") -> "URL": + return URL(str(self) + str(other)) + + def _default_port(self): + if self._parts.port is None: + return None + if self._parts.scheme == "http" and self._parts.port == 80: + return 80 + if self._parts.scheme == "https" and self._parts.port == 443: + return 443 + return None + + def _display_str(self) -> str: + parts = self._parts + netloc = parts.netloc + default_port = self._default_port() + if default_port is not None and parts.port is not None: + hostname = parts.hostname or "" + if parts.password: + netloc = f"{parts.username}:{parts.password}@{hostname}" + elif parts.username: + netloc = f"{parts.username}@{hostname}" + else: + netloc = hostname + query = f"?{parts.query}" if parts.query else "" + fragment = f"#{parts.fragment}" if parts.fragment else "" + return f"{parts.scheme}://{netloc}{parts.path}{query}{fragment}" + + def __str__(self) -> str: + return self._display_str() + + def __bytes__(self) -> bytes: + return str(self).encode("utf-8") + + def __repr__(self) -> str: + display = self._display_str() + if self.password: + display = display.replace(f":{self.password}@", ":***@") + return f"URL({display!r})" + + def __eq__(self, other): + if isinstance(other, URL): + return str(self) == str(other) + if isinstance(other, str): + return str(self) == str(URL(other)) + return NotImplemented + + def __hash__(self): + return hash(str(self)) + + def __lt__(self, other): + if isinstance(other, URL): + return str(self) < str(other) + return NotImplemented + + def __bool__(self) -> bool: + return bool(self._raw) diff --git a/crates/eggfetch-python/tests/compat/test_client.py b/crates/eggfetch-python/tests/compat/test_client.py new file mode 100644 index 00000000..0d53d96a --- /dev/null +++ b/crates/eggfetch-python/tests/compat/test_client.py @@ -0,0 +1,289 @@ +"""Tests for Client and AsyncClient compatibility.""" + +import asyncio +import json +import http.server +import threading + +import pytest + +from eggfetch.compat.httpx import ( + Client, + AsyncClient, + Request, + Response, + Headers, + Cookies, + Timeout, + QueryParams, + URL, +) + + +class _ClientHandler(http.server.BaseHTTPRequestHandler): + def _send_json(self, data, status=200): + body = json.dumps(data).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def _send_text(self, text, status=200): + body = text.encode() + self.send_response(status) + self.send_header("Content-Type", "text/plain") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + from urllib.parse import urlparse, parse_qs + parsed = urlparse(self.path) + path = parsed.path + qs = parse_qs(parsed.query) + + if path == "/get": + self._send_json({"method": "GET"}) + elif path == "/echo-headers": + headers = {k: v for k, v in self.headers.items()} + self._send_json({"headers": headers}) + elif path == "/status/404": + self._send_text("not found", 404) + elif path == "/status/500": + self._send_text("server error", 500) + elif path == "/set-cookie": + value = qs.get("value", ["test"])[0] + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Set-Cookie", f"session={value}; Path=/") + body = json.dumps({"cookie_set": True}).encode() + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + else: + self.send_response(404) + self.end_headers() + + def do_POST(self): + from urllib.parse import urlparse + parsed = urlparse(self.path) + path = parsed.path + + if path == "/echo": + cl = int(self.headers.get("Content-Length", 0)) + body = self.rfile.read(cl) + self.send_response(200) + self.send_header( + "Content-Type", + self.headers.get("Content-Type", "application/octet-stream"), + ) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + elif path == "/json": + cl = int(self.headers.get("Content-Length", 0)) + body = self.rfile.read(cl) + data = json.loads(body) + self._send_json({"received": data}) + else: + self.send_response(404) + self.end_headers() + + def log_message(self, format, *args): + pass + + +@pytest.fixture(scope="module") +def compat_server(): + server = http.server.HTTPServer(("127.0.0.1", 0), _ClientHandler) + port = server.server_address[1] + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + yield f"http://127.0.0.1:{port}" + server.shutdown() + + +class TestClientConstructor: + def test_defaults(self): + client = Client() + assert isinstance(client.headers, Headers) + assert isinstance(client.cookies, Cookies) + assert isinstance(client.params, QueryParams) + assert isinstance(client.timeout, Timeout) + assert client.is_closed is False + + def test_custom_headers(self): + client = Client(headers={"x-custom": "val"}) + assert client.headers["x-custom"] == "val" + + def test_custom_cookies(self): + client = Client(cookies={"session": "abc"}) + assert client.cookies["session"] == "abc" + + def test_custom_params(self): + client = Client(params={"q": "test"}) + assert client.params["q"] == "test" + + def test_custom_timeout(self): + client = Client(timeout=Timeout(10.0)) + assert client.timeout.total == 10.0 + + def test_scalar_timeout(self): + client = Client(timeout=5.0) + assert client.timeout.total == 5.0 + + def test_base_url(self): + client = Client(base_url="https://api.example.com") + assert client.base_url.host == "api.example.com" + + def test_auth(self): + client = Client(auth=("user", "pass")) + assert client.auth == ("user", "pass") + + def test_follow_redirects(self): + client = Client(follow_redirects=True) + assert client.is_closed is False + + +class TestClientBuildRequest: + def test_build_request(self): + client = Client() + req = client.build_request("GET", "https://example.com/path") + assert req.method == "GET" + assert req.url.host == "example.com" + + def test_build_request_merges_headers(self): + client = Client(headers={"x-client": "val"}) + req = client.build_request("GET", "https://example.com", headers={"x-req": "val"}) + assert req.headers["x-client"] == "val" + assert req.headers["x-req"] == "val" + + def test_build_request_merges_params(self): + client = Client(params={"a": "1"}) + req = client.build_request("GET", "https://example.com", params={"b": "2"}) + assert req.params["a"] == "1" + assert req.params["b"] == "2" + + def test_build_request_merges_cookies(self): + client = Client(cookies={"a": "1"}) + req = client.build_request("GET", "https://example.com", cookies={"b": "2"}) + assert req.cookies["a"] == "1" + assert req.cookies["b"] == "2" + + +class TestClientBaseUrl: + def test_base_url_joining(self): + client = Client(base_url="https://api.example.com/v1") + req = client.build_request("GET", "/users") + assert "/v1/users" in str(req.url) or req.url.path == "/users" + + def test_absolute_url_wins(self): + client = Client(base_url="https://api.example.com/v1") + req = client.build_request("GET", "https://other.com/override") + assert req.url.host == "other.com" + + +class TestClientSend: + def test_send_request(self, compat_server): + with Client() as client: + req = client.build_request("GET", f"{compat_server}/get") + resp = client.send(req) + assert resp.status_code == 200 + + def test_send_request_identity(self, compat_server): + with Client() as client: + req = client.build_request("GET", f"{compat_server}/get") + resp = client.send(req) + assert resp.request is req + + def test_send_non_request_raises(self, compat_server): + client = Client() + client._ensure_client() + with pytest.raises(TypeError, match="Request"): + client.send("not a request") + + +class TestClientMethods: + def test_get(self, compat_server): + with Client() as client: + resp = client.get(f"{compat_server}/get") + assert resp.status_code == 200 + + def test_post_json(self, compat_server): + with Client() as client: + resp = client.post(f"{compat_server}/json", json={"key": "val"}) + assert resp.status_code == 200 + + def test_post_content(self, compat_server): + with Client() as client: + resp = client.post(f"{compat_server}/echo", content=b"hello") + assert resp.content == b"hello" + + def test_request_method(self, compat_server): + with Client() as client: + resp = client.request("GET", f"{compat_server}/get") + assert resp.status_code == 200 + + +class TestClientContextManager: + def test_context_manager(self, compat_server): + with Client() as client: + resp = client.get(f"{compat_server}/get") + assert resp.status_code == 200 + assert client.is_closed + + def test_close(self, compat_server): + client = Client() + client._ensure_client() + client.close() + assert client.is_closed + + +class TestAsyncClient: + @pytest.mark.asyncio + async def test_async_context_manager(self, compat_server): + async with AsyncClient() as client: + resp = await client.get(f"{compat_server}/get") + assert resp.status_code == 200 + assert client.is_closed + + @pytest.mark.asyncio + async def test_async_get(self, compat_server): + async with AsyncClient() as client: + resp = await client.get(f"{compat_server}/get") + assert resp.status_code == 200 + + @pytest.mark.asyncio + async def test_async_post_json(self, compat_server): + async with AsyncClient() as client: + resp = await client.post(f"{compat_server}/json", json={"k": "v"}) + assert resp.status_code == 200 + + @pytest.mark.asyncio + async def test_async_request(self, compat_server): + async with AsyncClient() as client: + resp = await client.request("GET", f"{compat_server}/get") + assert resp.status_code == 200 + + @pytest.mark.asyncio + async def test_async_send(self, compat_server): + async with AsyncClient() as client: + req = client.build_request("GET", f"{compat_server}/get") + resp = await client.send(req) + assert resp.status_code == 200 + assert resp.request is req + + @pytest.mark.asyncio + async def test_async_close(self, compat_server): + client = AsyncClient() + client._ensure_client() + await client.close() + assert client.is_closed + + @pytest.mark.asyncio + async def test_async_send_non_request_raises(self, compat_server): + client = AsyncClient() + client._ensure_client() + with pytest.raises(TypeError, match="Request"): + await client.send("not a request") diff --git a/crates/eggfetch-python/tests/compat/test_config_objects.py b/crates/eggfetch-python/tests/compat/test_config_objects.py new file mode 100644 index 00000000..40941dbc --- /dev/null +++ b/crates/eggfetch-python/tests/compat/test_config_objects.py @@ -0,0 +1,240 @@ +"""Tests for Timeout, Limits, Proxy, and status codes.""" + +import pytest + +from eggfetch.compat.httpx import Timeout, Limits, Proxy, codes, URL + + +# ── Timeout ───────────────────────────────────────────────────────────── + +class TestTimeoutConstruction: + def test_scalar_constructor(self): + t = Timeout(5.0) + assert t.connect == 5.0 + assert t.read == 5.0 + assert t.write == 5.0 + assert t.pool == 5.0 + assert t.total == 5.0 + + def test_per_phase_constructor(self): + t = Timeout(10.0, connect=1.0, read=2.0, write=3.0, pool=4.0) + assert t.connect == 1.0 + assert t.read == 2.0 + assert t.write == 3.0 + assert t.pool == 4.0 + assert t.total == 10.0 + + def test_default_timeout(self): + t = Timeout() + assert t.total == 5.0 + + def test_integer_value(self): + t = Timeout(3) + assert t.connect == 3 + assert t.read == 3 + + +class TestTimeoutProperties: + def test_as_dict(self): + t = Timeout(1.0, connect=2.0) + d = t.as_dict + assert d["connect"] == 2.0 + assert d["read"] == 1.0 + assert d["write"] == 1.0 + assert d["pool"] == 1.0 + + +class TestTimeoutValidation: + def test_negative_raises(self): + with pytest.raises(ValueError, match="positive"): + Timeout(-1.0) + + def test_non_number_raises(self): + with pytest.raises(TypeError): + Timeout("five") + + +class TestTimeoutEq: + def test_equal(self): + assert Timeout(5.0) == Timeout(5.0) + + def test_not_equal(self): + assert Timeout(5.0) != Timeout(10.0) + + def test_not_equal_to_non_timeout(self): + assert Timeout(5.0) != "not timeout" + + +class TestTimeoutRepr: + def test_repr(self): + t = Timeout(5.0) + r = repr(t) + assert "Timeout" in r + assert "5.0" in r + + def test_repr_per_phase(self): + t = Timeout(10.0, connect=1.0) + r = repr(t) + assert "connect=1.0" in r + + +class TestTimeoutCopy: + def test_copy(self): + import copy + t = Timeout(1.0, connect=2.0) + c = copy.copy(t) + assert c == t + assert c is not t + + def test_deepcopy(self): + import copy + t = Timeout(1.0, connect=2.0) + c = copy.deepcopy(t) + assert c == t + + +# ── Limits ────────────────────────────────────────────────────────────── + +class TestLimitsConstruction: + def test_defaults(self): + lim = Limits() + assert lim.max_connections is None + assert lim.max_keepalive_connections is None + assert lim.keepalive_expiry == 5.0 + + def test_custom(self): + lim = Limits(max_connections=100, max_keepalive_connections=20, keepalive_expiry=10.0) + assert lim.max_connections == 100 + assert lim.max_keepalive_connections == 20 + assert lim.keepalive_expiry == 10.0 + + +class TestLimitsEq: + def test_equal(self): + assert Limits(100, 20, 5.0) == Limits(100, 20, 5.0) + + def test_not_equal(self): + assert Limits(100) != Limits(200) + + def test_not_equal_to_non_limits(self): + assert Limits() != "not limits" + + +class TestLimitsRepr: + def test_repr(self): + lim = Limits(max_connections=100) + r = repr(lim) + assert "Limits" in r + assert "100" in r + + +# ── Proxy ─────────────────────────────────────────────────────────────── + +class TestProxyConstruction: + def test_from_string(self): + p = Proxy("http://proxy.example.com:8080") + assert str(p.url) == "http://proxy.example.com:8080" + + def test_from_url(self): + u = URL("http://proxy.example.com:8080") + p = Proxy(u) + assert str(p.url) == "http://proxy.example.com:8080" + + def test_invalid_type_raises(self): + with pytest.raises(TypeError): + Proxy(123) + + def test_with_headers(self): + p = Proxy("http://proxy.example.com", headers={"X-Key": "val"}) + assert p.headers == {"X-Key": "val"} + + def test_invalid_headers_type_raises(self): + with pytest.raises(TypeError): + Proxy("http://proxy.example.com", headers="not dict") + + def test_with_auth(self): + p = Proxy("http://proxy.example.com", auth=("user", "pass")) + assert p.auth == ("user", "pass") + + def test_raw_auth_none(self): + p = Proxy("http://proxy.example.com") + assert p.raw_auth is None + + def test_raw_auth_tuple(self): + p = Proxy("http://proxy.example.com", auth=("user", "pass")) + assert p.raw_auth == ("user", "pass") + + def test_ssl_context_none(self): + p = Proxy("http://proxy.example.com") + assert p.ssl_context is None + + +class TestProxyRepr: + def test_repr_no_creds(self): + p = Proxy("http://proxy.example.com") + r = repr(p) + assert "Proxy" in r + + def test_repr_redacts_password(self): + p = Proxy("http://user:secret@proxy.example.com") + r = repr(p) + assert "secret" not in r + assert "***" in r + + def test_repr_with_auth(self): + p = Proxy("http://proxy.example.com", auth=("user", "pass")) + r = repr(p) + assert "auth=***" in r + + +# ── Status codes ──────────────────────────────────────────────────────── + +class TestStatusCodes: + def test_ok(self): + assert codes.OK == 200 + + def test_not_found(self): + assert codes.NOT_FOUND == 404 + + def test_internal_server_error(self): + assert codes.INTERNAL_SERVER_ERROR == 500 + + def test_bad_request(self): + assert codes.BAD_REQUEST == 400 + + def test_unauthorized(self): + assert codes.UNAUTHORIZED == 401 + + def test_forbidden(self): + assert codes.FORBIDDEN == 403 + + def test_moved_permanently(self): + assert codes.MOVED_PERMANENTLY == 301 + + def test_found(self): + assert codes.FOUND == 302 + + def test_service_unavailable(self): + assert codes.SERVICE_UNAVAILABLE == 503 + + def test_too_many_requests(self): + assert codes.TOO_MANY_REQUESTS == 429 + + def test_bad_gateway(self): + assert codes.BAD_GATEWAY == 502 + + def test_gateway_timeout(self): + assert codes.GATEWAY_TIMEOUT == 504 + + def test_created(self): + assert codes.CREATED == 201 + + def test_no_content(self): + assert codes.NO_CONTENT == 204 + + def test_continue(self): + assert codes.CONTINUE == 100 + + def test_invalid_code_raises(self): + with pytest.raises(AttributeError): + _ = codes.THIS_DOES_NOT_EXIST diff --git a/crates/eggfetch-python/tests/compat/test_cookies.py b/crates/eggfetch-python/tests/compat/test_cookies.py new file mode 100644 index 00000000..97f47b3f --- /dev/null +++ b/crates/eggfetch-python/tests/compat/test_cookies.py @@ -0,0 +1,174 @@ +"""Tests for Cookies compatibility.""" + +import pytest + +from eggfetch.compat.httpx import Cookies, Headers, Request + + +class TestCookiesConstruction: + def test_empty(self): + c = Cookies() + assert len(c) == 0 + + def test_from_dict(self): + c = Cookies({"a": "1", "b": "2"}) + assert c["a"] == "1" + assert c["b"] == "2" + + def test_from_list_of_tuples(self): + c = Cookies([("a", "1"), ("b", "2")]) + assert c["a"] == "1" + + def test_from_cookies(self): + original = Cookies({"a": "1"}) + copy = Cookies(original) + assert copy["a"] == "1" + + def test_invalid_type_raises(self): + with pytest.raises(TypeError): + Cookies(123) + + +class TestCookiesMutation: + def test_set(self): + c = Cookies() + c.set("a", "1") + assert c["a"] == "1" + + def test_set_with_domain_path(self): + c = Cookies() + c.set("a", "1", domain="example.com", path="/") + assert c["a"] == "1" + + def test_get(self): + c = Cookies({"a": "1"}) + assert c.get("a") == "1" + assert c.get("missing") is None + assert c.get("missing", "fallback") == "fallback" + + def test_delete(self): + c = Cookies({"a": "1"}) + c.delete("a") + assert "a" not in c + + def test_delete_with_domain_path(self): + c = Cookies({"a": "1"}) + c.delete("a", domain="example.com", path="/") + assert "a" not in c + + def test_clear(self): + c = Cookies({"a": "1", "b": "2"}) + c.clear() + assert len(c) == 0 + + def test_update_dict(self): + c = Cookies({"a": "1"}) + c.update({"a": "9", "b": "2"}) + assert c["a"] == "9" + assert c["b"] == "2" + + def test_update_cookies(self): + c = Cookies({"a": "1"}) + c.update(Cookies({"a": "9"})) + assert c["a"] == "9" + + def test_update_list(self): + c = Cookies() + c.update([("a", "1")]) + assert c["a"] == "1" + + +class TestCookiesDunder: + def test_setitem(self): + c = Cookies() + c["a"] = "1" + assert c["a"] == "1" + + def test_getitem(self): + c = Cookies({"a": "1"}) + assert c["a"] == "1" + + def test_getitem_missing(self): + with pytest.raises(KeyError): + Cookies()["missing"] + + def test_delitem(self): + c = Cookies({"a": "1"}) + del c["a"] + assert "a" not in c + + def test_contains(self): + c = Cookies({"a": "1"}) + assert "a" in c + assert "b" not in c + + def test_len(self): + c = Cookies({"a": "1", "b": "2"}) + assert len(c) == 2 + + def test_iter(self): + c = Cookies({"a": "1", "b": "2"}) + keys = list(c) + assert "a" in keys + assert "b" in keys + + def test_bool_empty(self): + assert not Cookies() + + def test_bool_nonempty(self): + assert Cookies({"a": "1"}) + + def test_items(self): + c = Cookies({"a": "1"}) + assert list(c.items()) == [("a", "1")] + + def test_keys(self): + c = Cookies({"a": "1", "b": "2"}) + assert set(c.keys()) == {"a", "b"} + + def test_values(self): + c = Cookies({"a": "1", "b": "2"}) + assert set(c.values()) == {"1", "2"} + + def test_repr(self): + c = Cookies({"a": "1"}) + assert "Cookies" in repr(c) + + +class TestCookiesSetDefault: + def test_setdefault_existing(self): + c = Cookies({"a": "1"}) + val = c.setdefault("a", "default") + assert val == "1" + + def test_setdefault_missing(self): + c = Cookies() + val = c.setdefault("a", "default") + assert val == "default" + assert c["a"] == "default" + + def test_setdefault_none(self): + c = Cookies() + val = c.setdefault("a") + assert val == "" + + +class TestCookiesFromRequest: + def test_extract_cookies(self): + c = Cookies() + h = Headers({"Cookie": "a=1; b=2"}) + req = Request("GET", "https://example.com", headers=h) + c.extract_cookies(req) + assert c["a"] == "1" + assert c["b"] == "2" + + def test_set_cookie_header(self): + c = Cookies() + h = Headers({"Set-Cookie": "session=abc123; Path=/; HttpOnly"}) + # Response-like object with headers attribute + class FakeResp: + pass + resp = FakeResp() + resp.headers = h + c.set_cookie_header(resp) + assert c["session"] == "abc123" diff --git a/crates/eggfetch-python/tests/compat/test_exceptions.py b/crates/eggfetch-python/tests/compat/test_exceptions.py new file mode 100644 index 00000000..1b818607 --- /dev/null +++ b/crates/eggfetch-python/tests/compat/test_exceptions.py @@ -0,0 +1,221 @@ +"""Tests for exception hierarchy.""" + +import pytest + +from eggfetch.compat.httpx import ( + CloseError, + ConnectError, + ConnectTimeout, + CookieConflict, + DecodingError, + HTTPError, + HTTPStatusError, + InvalidURL, + LocalProtocolError, + NetworkError, + PoolTimeout, + ProtocolError, + ProxyError, + ReadError, + ReadTimeout, + RemoteProtocolError, + RequestError, + RequestNotRead, + ResponseNotRead, + StreamClosed, + StreamConsumed, + StreamError, + TimeoutException, + TooManyRedirects, + TransportError, + UnsupportedProtocol, + WriteError, + WriteTimeout, + Request, + Response, + URL, +) + + +# ── MRO / hierarchy ──────────────────────────────────────────────────── + +class TestExceptionHierarchy: + def test_httperror_is_exception(self): + assert issubclass(HTTPError, Exception) + + def test_status_error_mro(self): + assert issubclass(HTTPStatusError, HTTPError) + assert issubclass(HTTPStatusError, Exception) + + def test_request_error_mro(self): + assert issubclass(RequestError, HTTPError) + + def test_transport_error_mro(self): + assert issubclass(TransportError, RequestError) + assert issubclass(TransportError, HTTPError) + + def test_timeout_exception_mro(self): + assert issubclass(TimeoutException, TransportError) + assert issubclass(TimeoutException, RequestError) + assert issubclass(TimeoutException, HTTPError) + + def test_connect_timeout_mro(self): + assert issubclass(ConnectTimeout, TimeoutException) + assert issubclass(ConnectTimeout, TransportError) + + def test_read_timeout_mro(self): + assert issubclass(ReadTimeout, TimeoutException) + + def test_write_timeout_mro(self): + assert issubclass(WriteTimeout, TimeoutException) + + def test_pool_timeout_mro(self): + assert issubclass(PoolTimeout, TimeoutException) + + def test_network_error_mro(self): + assert issubclass(NetworkError, TransportError) + + def test_close_error_mro(self): + assert issubclass(CloseError, NetworkError) + assert issubclass(CloseError, TransportError) + + def test_connect_error_mro(self): + assert issubclass(ConnectError, NetworkError) + + def test_read_error_mro(self): + assert issubclass(ReadError, NetworkError) + + def test_write_error_mro(self): + assert issubclass(WriteError, NetworkError) + + def test_protocol_error_mro(self): + assert issubclass(ProtocolError, TransportError) + + def test_local_protocol_error_mro(self): + assert issubclass(LocalProtocolError, ProtocolError) + + def test_remote_protocol_error_mro(self): + assert issubclass(RemoteProtocolError, ProtocolError) + + def test_proxy_error_mro(self): + assert issubclass(ProxyError, TransportError) + + def test_unsupported_protocol_mro(self): + assert issubclass(UnsupportedProtocol, TransportError) + + def test_decoding_error_mro(self): + assert issubclass(DecodingError, RequestError) + + def test_too_many_redirects_mro(self): + assert issubclass(TooManyRedirects, RequestError) + + +class TestStreamErrorHierarchy: + def test_stream_error_is_exception(self): + assert issubclass(StreamError, Exception) + + def test_stream_error_not_http_error(self): + assert not issubclass(StreamError, HTTPError) + + def test_request_not_read(self): + assert issubclass(RequestNotRead, StreamError) + + def test_response_not_read(self): + assert issubclass(ResponseNotRead, StreamError) + + def test_stream_closed(self): + assert issubclass(StreamClosed, StreamError) + + def test_stream_consumed(self): + assert issubclass(StreamConsumed, StreamError) + + +class TestStandaloneExceptions: + def test_invalid_url(self): + assert issubclass(InvalidURL, Exception) + assert not issubclass(InvalidURL, HTTPError) + + def test_cookie_conflict(self): + assert issubclass(CookieConflict, Exception) + assert not issubclass(CookieConflict, HTTPError) + + +# ── Constructor signatures ───────────────────────────────────────────── + +class TestExceptionConstructors: + def test_http_error_with_request(self): + req = Request("GET", "https://example.com") + exc = HTTPError(req) + assert exc.request is req + + def test_http_error_with_message(self): + exc = HTTPError(message="test error") + assert "test error" in str(exc) + + def test_http_status_error(self): + req = Request("GET", "https://example.com") + resp = Response(404, request=req) + exc = HTTPStatusError("Not Found", request=req, response=resp) + assert exc.request is req + assert exc.response is resp + assert "Not Found" in str(exc) + + def test_request_error_has_request(self): + req = Request("GET", "https://example.com") + exc = RequestError(request=req, message="fail") + assert exc.request is req + + def test_transport_error_has_request(self): + req = Request("GET", "https://example.com") + exc = TransportError(request=req, message="fail") + assert exc.request is req + + def test_timeout_exception_has_request(self): + req = Request("GET", "https://example.com") + exc = TimeoutException(request=req, message="timeout") + assert exc.request is req + + def test_connect_timeout_has_request(self): + req = Request("GET", "https://example.com") + exc = ConnectTimeout(request=req, message="connect timeout") + assert exc.request is req + + def test_invalid_url_message(self): + exc = InvalidURL("bad url") + assert "bad url" in str(exc) + + def test_cookie_conflict_message(self): + exc = CookieConflict("conflict") + assert "conflict" in str(exc) + + +# ── raise_for_status ─────────────────────────────────────────────────── + +class TestRaiseForStatus: + def test_success_returns_self(self): + resp = Response(200) + result = resp.raise_for_status() + assert result is resp + + def test_informational_returns_self(self): + resp = Response(100) + result = resp.raise_for_status() + assert result is resp + + def test_4xx_raises(self): + resp = Response(404, request=Request("GET", "https://example.com")) + with pytest.raises(HTTPStatusError) as exc_info: + resp.raise_for_status() + assert exc_info.value.response is resp + assert exc_info.value.request is resp.request + + def test_5xx_raises(self): + resp = Response(500, request=Request("GET", "https://example.com")) + with pytest.raises(HTTPStatusError) as exc_info: + resp.raise_for_status() + assert exc_info.value.response is resp + + def test_redirect_not_error(self): + resp = Response(301) + result = resp.raise_for_status() + assert result is resp diff --git a/crates/eggfetch-python/tests/compat/test_headers.py b/crates/eggfetch-python/tests/compat/test_headers.py new file mode 100644 index 00000000..44a0c448 --- /dev/null +++ b/crates/eggfetch-python/tests/compat/test_headers.py @@ -0,0 +1,182 @@ +"""Tests for Headers compatibility.""" + +import pytest + +from eggfetch.compat.httpx import Headers + + +class TestHeadersConstruction: + def test_from_dict(self): + h = Headers({"content-type": "text/plain", "x-custom": "val"}) + assert h["content-type"] == "text/plain" + + def test_from_list_of_tuples(self): + h = Headers([("x-a", "1"), ("x-b", "2")]) + assert h["x-a"] == "1" + assert h["x-b"] == "2" + + def test_from_headers_obj(self): + original = Headers({"x-a": "1"}) + copy = Headers(original) + assert copy["x-a"] == "1" + + def test_invalid_type_raises(self): + with pytest.raises(TypeError): + Headers("not valid") + + +class TestHeadersLookup: + def test_case_insensitive_get(self): + h = Headers({"Content-Type": "text/plain"}) + assert h["content-type"] == "text/plain" + assert h["CONTENT-TYPE"] == "text/plain" + + def test_get_default(self): + h = Headers() + assert h.get("missing") is None + assert h.get("missing", "fallback") == "fallback" + + def test_get_returns_last_value(self): + h = Headers([("x-dup", "first"), ("x-dup", "second")]) + assert h["x-dup"] == "second" + + def test_contains_case_insensitive(self): + h = Headers({"X-Custom": "val"}) + assert "x-custom" in h + assert "X-CUSTOM" in h + assert "missing" not in h + + +class TestHeadersMultiValue: + def test_get_list(self): + h = Headers([("set-cookie", "a=1"), ("set-cookie", "b=2")]) + assert h.get_list("set-cookie") == ["a=1", "b=2"] + + def test_get_list_empty(self): + h = Headers() + assert h.get_list("missing") == [] + + def test_multi_items_preserves_all(self): + h = Headers([("x-a", "1"), ("x-a", "2"), ("x-b", "3")]) + items = h.multi_items() + assert len(items) == 3 + assert items[0] == ("x-a", "1") + assert items[1] == ("x-a", "2") + assert items[2] == ("x-b", "3") + + def test_keys_deduplicates(self): + h = Headers([("x-a", "1"), ("x-a", "2")]) + assert h.keys() == ["x-a"] + + def test_values_first_per_key(self): + h = Headers([("x-a", "1"), ("x-a", "2"), ("x-b", "3")]) + assert h.values() == ["1", "3"] + + def test_items_first_per_key(self): + h = Headers([("x-a", "1"), ("x-a", "2")]) + assert h.items() == [("x-a", "1")] + + +class TestHeadersRaw: + def test_raw_bytes(self): + h = Headers({"content-type": "text/plain"}) + raw = h.raw + assert len(raw) == 1 + assert raw[0] == (b"content-type", b"text/plain") + + +class TestHeadersMutation: + def test_setitem(self): + h = Headers() + h["x-custom"] = "val" + assert h["x-custom"] == "val" + + def test_setitem_replaces(self): + h = Headers({"x-a": "old"}) + h["x-a"] = "new" + assert h["x-a"] == "new" + + def test_update_dict(self): + h = Headers({"x-a": "1"}) + h.update({"x-b": "2"}) + assert h["x-b"] == "2" + + def test_update_headers(self): + h = Headers({"x-a": "1"}) + h.update(Headers({"x-b": "2"})) + assert h["x-b"] == "2" + + def test_pop(self): + h = Headers({"x-a": "1", "x-b": "2"}) + val = h.pop("x-a") + assert val == "1" + assert "x-a" not in h + assert "x-b" in h + + def test_pop_default(self): + h = Headers() + val = h.pop("missing", "default") + assert val == "default" + + def test_clear(self): + h = Headers({"x-a": "1"}) + h.clear() + assert len(h) == 0 + + def test_copy(self): + h = Headers({"x-a": "1"}) + c = h.copy() + c["x-a"] = "changed" + assert h["x-a"] == "1" # original unchanged + + def test_delitem(self): + h = Headers({"x-a": "1"}) + del h["x-a"] + assert "x-a" not in h + + def test_delitem_missing(self): + with pytest.raises(KeyError): + del Headers()["missing"] + + +class TestHeadersValidation: + def test_cr_in_name_raises(self): + with pytest.raises(ValueError, match="CR/LF"): + Headers({"bad\rname": "val"}) + + def test_lf_in_name_raises(self): + with pytest.raises(ValueError, match="CR/LF"): + Headers({"bad\nname": "val"}) + + def test_cr_in_value_raises(self): + with pytest.raises(ValueError, match="CR/LF"): + Headers({"x-ok": "bad\rvalue"}) + + def test_lf_in_value_raises(self): + with pytest.raises(ValueError, match="CR/LF"): + Headers({"x-ok": "bad\nvalue"}) + + +class TestHeadersEq: + def test_equal(self): + assert Headers({"a": "1"}) == Headers({"a": "1"}) + + def test_not_equal(self): + assert Headers({"a": "1"}) != Headers({"a": "2"}) + + def test_not_equal_to_non_headers(self): + assert Headers({"a": "1"}) != "not headers" + + +class TestHeadersMisc: + def test_encoding(self): + h = Headers(encoding="latin-1") + assert h.encoding == "latin-1" + + def test_len(self): + h = Headers([("a", "1"), ("b", "2")]) + assert len(h) == 2 + + def test_iter(self): + h = Headers([("a", "1"), ("b", "2")]) + assert list(h) == ["a", "b"] diff --git a/crates/eggfetch-python/tests/compat/test_imports.py b/crates/eggfetch-python/tests/compat/test_imports.py new file mode 100644 index 00000000..6378bffe --- /dev/null +++ b/crates/eggfetch-python/tests/compat/test_imports.py @@ -0,0 +1,54 @@ +"""Verify every symbol in __all__ is importable from eggfetch.compat.httpx.""" + +import importlib + +from eggfetch.compat.httpx import __all__ + + +def test_all_symbols_are_importable(): + """Every name in __all__ should be importable.""" + mod = importlib.import_module("eggfetch.compat.httpx") + missing = [] + for name in __all__: + if not hasattr(mod, name): + missing.append(name) + assert not missing, f"Missing symbols: {missing}" + + +def test_all_contains_expected_basics(): + """Smoke-check a known subset of __all__.""" + expected = { + "Client", + "AsyncClient", + "Request", + "Response", + "URL", + "QueryParams", + "Headers", + "Cookies", + "Timeout", + "Limits", + "Proxy", + "codes", + "HTTPError", + "HTTPStatusError", + "RequestError", + "TransportError", + "TimeoutException", + "get", + "post", + "put", + "patch", + "delete", + "head", + "options", + "request", + "stream", + } + missing = expected - set(__all__) + assert not missing, f"__all__ missing expected symbols: {missing}" + + +def test_all_is_a_list(): + """__all__ should be a list (standard Python convention).""" + assert isinstance(__all__, list) diff --git a/crates/eggfetch-python/tests/compat/test_merge_matrix.py b/crates/eggfetch-python/tests/compat/test_merge_matrix.py new file mode 100644 index 00000000..dec3298a --- /dev/null +++ b/crates/eggfetch-python/tests/compat/test_merge_matrix.py @@ -0,0 +1,151 @@ +"""Parameterized matrix tests for configuration merging.""" + +import pytest + +from eggfetch.compat.httpx import ( + Client, + Headers, + Cookies, + QueryParams, + Timeout, + URL, +) + + +# ── Client params + request params ────────────────────────────────────── + +class TestParamsMerging: + def test_client_params_used_when_no_request_params(self): + client = Client(params={"a": "1", "b": "2"}) + req = client.build_request("GET", "https://example.com") + assert req.params["a"] == "1" + assert req.params["b"] == "2" + + def test_request_params_override_client(self): + client = Client(params={"a": "1"}) + req = client.build_request("GET", "https://example.com", params={"a": "9"}) + assert req.params["a"] == "9" + + def test_request_params_add_to_client(self): + client = Client(params={"a": "1"}) + req = client.build_request("GET", "https://example.com", params={"b": "2"}) + assert req.params["a"] == "1" + assert req.params["b"] == "2" + + def test_empty_client_params(self): + client = Client() + req = client.build_request("GET", "https://example.com", params={"a": "1"}) + assert req.params["a"] == "1" + + +# ── Client headers + request headers ──────────────────────────────────── + +class TestHeadersMerging: + def test_client_headers_used_when_no_request_headers(self): + client = Client(headers={"x-client": "val"}) + req = client.build_request("GET", "https://example.com") + assert req.headers["x-client"] == "val" + + def test_request_headers_override_client(self): + client = Client(headers={"x-custom": "old"}) + req = client.build_request( + "GET", "https://example.com", headers={"x-custom": "new"} + ) + assert req.headers["x-custom"] == "new" + + def test_request_headers_add_to_client(self): + client = Client(headers={"x-client": "val"}) + req = client.build_request( + "GET", "https://example.com", headers={"x-req": "val"} + ) + assert req.headers["x-client"] == "val" + assert req.headers["x-req"] == "val" + + def test_empty_client_headers(self): + client = Client() + req = client.build_request( + "GET", "https://example.com", headers={"x-req": "val"} + ) + assert req.headers["x-req"] == "val" + + +# ── Client cookies + request cookies ──────────────────────────────────── + +class TestCookiesMerging: + def test_client_cookies_used_when_no_request_cookies(self): + client = Client(cookies={"session": "abc"}) + req = client.build_request("GET", "https://example.com") + assert req.cookies["session"] == "abc" + + def test_request_cookies_override_client(self): + client = Client(cookies={"session": "old"}) + req = client.build_request( + "GET", "https://example.com", cookies={"session": "new"} + ) + assert req.cookies["session"] == "new" + + def test_request_cookies_add_to_client(self): + client = Client(cookies={"a": "1"}) + req = client.build_request( + "GET", "https://example.com", cookies={"b": "2"} + ) + assert req.cookies["a"] == "1" + assert req.cookies["b"] == "2" + + def test_empty_client_cookies(self): + client = Client() + req = client.build_request( + "GET", "https://example.com", cookies={"a": "1"} + ) + assert req.cookies["a"] == "1" + + +# ── base_url + relative URL ──────────────────────────────────────────── + +class TestBaseUrlMerging: + def test_relative_url_joined(self): + client = Client(base_url="https://api.example.com/v1") + req = client.build_request("GET", "/users") + assert "api.example.com" in str(req.url) + + def test_absolute_url_wins(self): + client = Client(base_url="https://api.example.com/v1") + req = client.build_request("GET", "https://other.com/override") + assert req.url.host == "other.com" + assert "v1" not in str(req.url) + + def test_no_base_url(self): + client = Client() + req = client.build_request("GET", "https://example.com/path") + assert req.url.host == "example.com" + assert req.url.path == "/path" + + def test_empty_base_url(self): + client = Client(base_url="") + req = client.build_request("GET", "https://example.com/path") + assert req.url.host == "example.com" + + +# ── timeout override ──────────────────────────────────────────────────── + +class TestTimeoutOverride: + def test_client_timeout_used(self): + client = Client(timeout=Timeout(10.0)) + assert client.timeout.total == 10.0 + + def test_timeout_override_in_request(self): + client = Client(timeout=Timeout(10.0)) + assert client.timeout.total == 10.0 + # The per-request timeout override happens at send() level + + +# ── auth override ────────────────────────────────────────────────────── + +class TestAuthOverride: + def test_client_auth(self): + client = Client(auth=("user", "pass")) + assert client.auth == ("user", "pass") + + def test_client_auth_none(self): + client = Client() + assert client.auth is None diff --git a/crates/eggfetch-python/tests/compat/test_request.py b/crates/eggfetch-python/tests/compat/test_request.py new file mode 100644 index 00000000..2e761d3c --- /dev/null +++ b/crates/eggfetch-python/tests/compat/test_request.py @@ -0,0 +1,174 @@ +"""Tests for Request compatibility.""" + +import json +import asyncio + +import pytest + +from eggfetch.compat.httpx import Request, URL, Headers, QueryParams, Cookies + + +class TestRequestConstruction: + def test_method_and_url(self): + req = Request("GET", "https://example.com/path") + assert req.method == "GET" + assert str(req.url) == "https://example.com/path" + + def test_method_uppercased(self): + req = Request("get", "https://example.com") + assert req.method == "GET" + + def test_url_object(self): + url = URL("https://example.com/path") + req = Request("GET", url) + assert req.url is url + + def test_empty_body(self): + req = Request("GET", "https://example.com") + assert req.content is None + + +class TestBodyMutualExclusion: + def test_content_only(self): + req = Request("POST", "https://example.com", content=b"hello") + assert req.content == b"hello" + + def test_json_only(self): + req = Request("POST", "https://example.com", json={"key": "value"}) + assert req.content == json.dumps({"key": "value"}).encode() + + def test_data_dict(self): + req = Request("POST", "https://example.com", data={"key": "value"}) + assert req.content is not None + + def test_data_string(self): + req = Request("POST", "https://example.com", data="raw body") + assert req.content == b"raw body" + + def test_content_and_json_raises(self): + with pytest.raises(ValueError, match="Conflicting"): + Request("POST", "https://example.com", content=b"body", json={"k": "v"}) + + def test_content_and_data_raises(self): + with pytest.raises(ValueError, match="Conflicting"): + Request("POST", "https://example.com", content=b"body", data={"k": "v"}) + + +class TestAutoHeaders: + def test_host_header(self): + req = Request("GET", "https://example.com:8443/path") + assert req.headers["host"] == "example.com:8443" + + def test_host_default_port(self): + req = Request("GET", "https://example.com/path") + assert req.headers["host"] == "example.com" + + def test_content_length_json(self): + req = Request("POST", "https://example.com", json={"k": "v"}) + assert "content-length" in req.headers + + def test_content_type_json(self): + req = Request("POST", "https://example.com", json={"k": "v"}) + assert req.headers["content-type"] == "application/json" + + def test_content_type_form(self): + req = Request("POST", "https://example.com", data={"k": "v"}) + assert req.headers["content-type"] == "application/x-www-form-urlencoded" + + def test_content_type_not_overwritten(self): + req = Request( + "POST", + "https://example.com", + json={"k": "v"}, + headers={"Content-Type": "application/custom"}, + ) + assert req.headers["content-type"] == "application/custom" + + def test_transfer_encoding_stream(self): + async def gen(): + yield b"chunk" + + req = Request("POST", "https://example.com", stream=gen()) + assert req.headers["transfer-encoding"] == "chunked" + + +class TestParamsMerging: + def test_params_object(self): + qp = QueryParams({"q": "test"}) + req = Request("GET", "https://example.com", params=qp) + assert req.params["q"] == "test" + + def test_params_dict(self): + req = Request("GET", "https://example.com", params={"q": "test"}) + assert req.params["q"] == "test" + + +class TestRead: + def test_read_content(self): + req = Request("POST", "https://example.com", content=b"hello") + assert req.read() == b"hello" + + def test_read_empty(self): + req = Request("GET", "https://example.com") + assert req.read() == b"" + + def test_read_stream(self): + def gen(): + yield b"chunk1" + yield b"chunk2" + + req = Request("POST", "https://example.com", stream=gen()) + assert req.read() == b"chunk1chunk2" + assert req.is_stream_consumed + + @pytest.mark.asyncio + async def test_aread_stream(self): + async def gen(): + yield b"chunk1" + yield b"chunk2" + + req = Request("POST", "https://example.com", stream=gen()) + result = await req.aread() + assert result == b"chunk1chunk2" + assert req.is_stream_consumed + + +class TestStreamConsumed: + def test_initially_false(self): + req = Request("GET", "https://example.com") + assert not req.is_stream_consumed + + +class TestHttpVersion: + def test_default_version(self): + req = Request("GET", "https://example.com") + assert req.http_version == "HTTP/1.1" + + +class TestExtensions: + def test_default_empty(self): + req = Request("GET", "https://example.com") + assert req.extensions == {} + + def test_custom_extensions(self): + req = Request("GET", "https://example.com", extensions={"timeout": 5.0}) + assert req.extensions == {"timeout": 5.0} + + +class TestCookies: + def test_cookies_object(self): + c = Cookies({"session": "abc"}) + req = Request("GET", "https://example.com", cookies=c) + assert req.cookies["session"] == "abc" + + def test_cookies_dict(self): + req = Request("GET", "https://example.com", cookies={"session": "abc"}) + assert req.cookies["session"] == "abc" + + +class TestRequestRepr: + def test_repr(self): + req = Request("GET", "https://example.com") + r = repr(req) + assert "GET" in r + assert "example.com" in r diff --git a/crates/eggfetch-python/tests/compat/test_response.py b/crates/eggfetch-python/tests/compat/test_response.py new file mode 100644 index 00000000..479468b5 --- /dev/null +++ b/crates/eggfetch-python/tests/compat/test_response.py @@ -0,0 +1,209 @@ +"""Tests for Response compatibility.""" + +import json +from datetime import timedelta + +import pytest + +from eggfetch.compat.httpx import ( + Response, + Request, + Headers, + URL, + HTTPStatusError, +) + + +class TestResponseConstruction: + def test_status_code(self): + resp = Response(200) + assert resp.status_code == 200 + + def test_content(self): + resp = Response(200, content=b"hello") + assert resp.content == b"hello" + + def test_text(self): + resp = Response(200, text="hello") + assert resp.text == "hello" + assert resp.content == b"hello" + + def test_json(self): + resp = Response(200, json={"key": "value"}) + assert resp.json() == {"key": "value"} + + def test_html(self): + resp = Response(200, html="

hi

") + assert resp.text == "

hi

" + assert "text/html" in resp.headers["content-type"] + + def test_default_empty_content(self): + resp = Response(200) + assert resp.content == b"" + + def test_conflicting_sources_raises(self): + with pytest.raises(ValueError, match="Conflicting"): + Response(200, content=b"body", text="text") + + +class TestStatusPredicates: + def test_is_success(self): + assert Response(200).is_success + assert Response(201).is_success + assert Response(299).is_success + assert not Response(300).is_success + assert not Response(199).is_success + + def test_is_redirect(self): + assert Response(301).is_redirect + assert Response(302).is_redirect + assert Response(307).is_redirect + assert Response(308).is_redirect + assert not Response(200).is_redirect + assert not Response(400).is_redirect + + def test_is_client_error(self): + assert Response(400).is_client_error + assert Response(404).is_client_error + assert Response(499).is_client_error + assert not Response(500).is_client_error + + def test_is_server_error(self): + assert Response(500).is_server_error + assert Response(503).is_server_error + assert Response(599).is_server_error + assert not Response(499).is_server_error + + def test_is_error(self): + assert Response(400).is_error + assert Response(500).is_error + assert not Response(200).is_error + assert not Response(301).is_error + + def test_is_informational(self): + assert Response(100).is_informational + assert Response(101).is_informational + assert Response(199).is_informational + assert not Response(200).is_informational + + +class TestRaiseForStatus: + def test_success_returns_self(self): + resp = Response(200) + assert resp.raise_for_status() is resp + + def test_4xx_raises(self): + resp = Response(404, request=Request("GET", "https://example.com")) + with pytest.raises(HTTPStatusError): + resp.raise_for_status() + + def test_5xx_raises(self): + resp = Response(500, request=Request("GET", "https://example.com")) + with pytest.raises(HTTPStatusError): + resp.raise_for_status() + + def test_4xx_exception_has_response(self): + req = Request("GET", "https://example.com") + resp = Response(404, request=req) + with pytest.raises(HTTPStatusError) as exc_info: + resp.raise_for_status() + assert exc_info.value.response is resp + assert exc_info.value.request is req + + +class TestEncoding: + def test_encoding_setter(self): + resp = Response(200, content=b"hello") + resp.encoding = "latin-1" + assert resp.encoding == "latin-1" + + def test_charset_encoding_from_content_type(self): + resp = Response( + 200, + headers={"Content-Type": "text/plain; charset=iso-8859-1"}, + ) + assert resp.charset_encoding == "iso-8859-1" + + def test_charset_encoding_none(self): + resp = Response(200) + assert resp.charset_encoding is None + + +class TestElapsed: + def test_default_zero(self): + resp = Response(200) + assert resp.elapsed == timedelta(0) + + +class TestHistory: + def test_default_empty(self): + resp = Response(200) + assert resp.history == [] + + def test_with_history(self): + h1 = Response(301) + h2 = Response(302) + resp = Response(200, history=[h1, h2]) + assert len(resp.history) == 2 + + +class TestLinks: + def test_links_from_header(self): + resp = Response( + 200, + headers={ + "Link": '; rel="next"' + }, + ) + links = resp.links + assert "next" in links + assert links["next"]["url"] == "https://api.example.com/items?page=2" + + def test_links_empty(self): + resp = Response(200) + assert resp.links == {} + + +class TestIterators: + def test_iter_bytes(self): + resp = Response(200, content=b"hello world") + chunks = list(resp.iter_bytes(chunk_size=5)) + assert chunks == [b"hello", b" worl", b"d"] + + def test_iter_text(self): + resp = Response(200, text="hello world") + chunks = list(resp.iter_text(chunk_size=5)) + assert chunks == ["hello", " worl", "d"] + + def test_iter_lines(self): + resp = Response(200, text="line1\nline2\nline3") + lines = list(resp.iter_lines()) + assert lines == ["line1", "line2", "line3"] + + def test_iter_lines_strips_cr(self): + resp = Response(200, text="line1\r\nline2") + lines = list(resp.iter_lines()) + assert lines == ["line1", "line2"] + + +class TestResponseHeaders: + def test_headers(self): + resp = Response(200, headers={"x-custom": "val"}) + assert resp.headers["x-custom"] == "val" + + +class TestResponseRepr: + def test_repr(self): + resp = Response(200) + assert "200" in repr(resp) + + +class TestResponseRequest: + def test_request_attribute(self): + req = Request("GET", "https://example.com") + resp = Response(200, request=req) + assert resp.request is req + + def test_no_request(self): + resp = Response(200) + assert resp.request is None diff --git a/crates/eggfetch-python/tests/compat/test_url_query.py b/crates/eggfetch-python/tests/compat/test_url_query.py new file mode 100644 index 00000000..37979363 --- /dev/null +++ b/crates/eggfetch-python/tests/compat/test_url_query.py @@ -0,0 +1,393 @@ +"""Comprehensive tests for URL and QueryParams.""" + +import pytest + +from eggfetch.compat.httpx import URL, QueryParams + + +# ── URL construction ──────────────────────────────────────────────────── + +class TestURLConstruction: + def test_from_string(self): + url = URL("https://example.com/path") + assert str(url) == "https://example.com/path" + + def test_from_bytes(self): + url = URL(b"https://example.com/path") + assert url.host == "example.com" + + def test_from_existing_url(self): + a = URL("https://example.com/path") + b = URL(a) + assert a is b # identity return for URL input + + def test_none_yields_http_prefix(self): + url = URL(None) + assert url._raw == "" + + def test_relative_string(self): + url = URL("/path/to/resource") + assert url.path == "/path/to/resource" + + def test_empty_string(self): + url = URL("") + assert url._raw == "" + + +# ── URL properties ────────────────────────────────────────────────────── + +class TestURLProperties: + def test_scheme(self): + assert URL("https://example.com").scheme == "https" + assert URL("http://example.com").scheme == "http" + + def test_host(self): + assert URL("https://example.com").host == "example.com" + assert URL("https://Example.COM").host == "example.com" + + def test_port_explicit(self): + assert URL("https://example.com:8443").port == 8443 + + def test_port_default_http(self): + assert URL("http://example.com:80").port == 80 + + def test_port_default_https(self): + assert URL("https://example.com:443").port == 443 + + def test_port_none_when_omitted(self): + assert URL("https://example.com").port is None + + def test_path(self): + assert URL("https://example.com/a/b/c").path == "/a/b/c" + + def test_path_empty(self): + assert URL("https://example.com").path == "" + + def test_query(self): + url = URL("https://example.com?q=1&r=2") + assert url.query == b"q=1&r=2" + + def test_query_empty(self): + assert URL("https://example.com").query == b"" + + def test_fragment(self): + assert URL("https://example.com/path#section").fragment == "section" + + def test_fragment_empty(self): + assert URL("https://example.com").fragment == "" + + def test_username(self): + assert URL("https://user@example.com").username == "user" + + def test_password(self): + assert URL("https://user:pass@example.com").password == "pass" + + def test_netloc(self): + url = URL("https://example.com:8443/path") + assert url.netloc == b"example.com:8443" + + def test_userinfo_with_password(self): + url = URL("https://user:pass@example.com") + assert url.userinfo == b"user:pass" + + def test_userinfo_without_password(self): + url = URL("https://user@example.com") + assert url.userinfo == b"user" + + def test_userinfo_empty(self): + url = URL("https://example.com") + assert url.userinfo == b"" + + def test_raw_host(self): + assert URL("https://example.com").raw_host == b"example.com" + + def test_raw_host_none(self): + assert URL("").raw_host is None + + def test_raw_path(self): + assert URL("https://example.com/a/b").raw_path == b"/a/b" + + def test_raw_path_empty_defaults_slash(self): + assert URL("https://example.com").raw_path == b"/" + + def test_raw_scheme(self): + assert URL("https://example.com").raw_scheme == b"https" + + +# ── Absolute / relative ──────────────────────────────────────────────── + +class TestURLAbsoluteRelative: + def test_is_absolute_url(self): + assert URL("https://example.com").is_absolute_url is True + assert URL("http://example.com/path").is_absolute_url is True + + def test_is_relative_url(self): + assert URL("/path").is_relative_url is True + + def test_absolute_not_relative(self): + url = URL("https://example.com") + assert url.is_absolute_url is True + assert url.is_relative_url is False + + def test_relative_not_absolute(self): + url = URL("/path") + assert url.is_relative_url is True + assert url.is_absolute_url is False + + +# ── copy_with / param helpers ────────────────────────────────────────── + +class TestURLCopyWith: + def test_copy_with_params(self): + url = URL("https://example.com/path") + new = url.copy_with(params={"q": "1"}) + assert str(new) == "https://example.com/path?q=1" + + def test_copy_set_param(self): + url = URL("https://example.com?a=1&b=2") + new = url.copy_set_param("a", "9") + assert "a=9" in str(new) + assert "b=2" in str(new) + + def test_copy_remove_param(self): + url = URL("https://example.com?a=1&b=2") + new = url.copy_remove_param("a") + assert "a=" not in str(new) + assert "b=2" in str(new) + + def test_copy_merge_params(self): + url = URL("https://example.com?a=1") + new = url.copy_merge_params({"b": "2"}) + assert "a=1" in str(new) + assert "b=2" in str(new) + + def test_copy_add_param(self): + url = URL("https://example.com?a=1") + new = url.copy_add_param("b", "2") + assert "a=1" in str(new) + assert "b=2" in str(new) + + +# ── URL join ──────────────────────────────────────────────────────────── + +class TestURLJoin: + def test_join_relative(self): + base = URL("https://example.com/a/b") + joined = base.join(URL("c/d")) + assert "c/d" in str(joined) + + def test_join_queryparams_obj(self): + from eggfetch.compat.httpx import QueryParams + url = URL("https://example.com/path") + qp = QueryParams({"q": "test"}) + new = url.copy_with(params=qp) + assert "q=test" in str(new) + + +# ── Default port stripping ───────────────────────────────────────────── + +class TestURLDefaultPort: + def test_http_80_stripped(self): + url = URL("http://example.com:80/path") + assert ":80" not in str(url) + assert str(url) == "http://example.com/path" + + def test_https_443_stripped(self): + url = URL("https://example.com:443/path") + assert ":443" not in str(url) + assert str(url) == "https://example.com/path" + + def test_non_default_port_kept(self): + url = URL("http://example.com:8080/path") + assert ":8080" in str(url) + + +# ── Credential redaction in repr ─────────────────────────────────────── + +class TestURLRepr: + def test_password_redacted(self): + url = URL("https://user:secret@example.com") + r = repr(url) + assert "secret" not in r + assert "***" in r + + def test_no_password_no_redaction(self): + url = URL("https://user@example.com") + assert "user" in repr(url) + + +# ── IPv6 ──────────────────────────────────────────────────────────────── + +class TestURLIPv6: + def test_ipv6_host(self): + url = URL("https://[::1]:8443/path") + assert url.host == "::1" + assert url.port == 8443 + + +# ── Unicode hosts ────────────────────────────────────────────────────── + +class TestURLUnicode: + def test_unicode_host(self): + url = URL("https://münchen.de/path") + assert "münchen" in (url.host or "") + + +# ── QueryParams construction ────────────────────────────────────────── + +class TestQueryParamsConstruction: + def test_from_dict(self): + qp = QueryParams({"a": "1", "b": "2"}) + assert qp["a"] == "1" + assert qp["b"] == "2" + + def test_from_list_of_tuples(self): + qp = QueryParams([("a", "1"), ("b", "2")]) + assert qp["a"] == "1" + assert qp["b"] == "2" + + def test_from_string(self): + qp = QueryParams("a=1&b=2") + assert qp["a"] == "1" + assert qp["b"] == "2" + + def test_from_queryparams(self): + original = QueryParams({"a": "1"}) + copy = QueryParams(original) + assert copy["a"] == "1" + assert copy is not original + + def test_from_none(self): + qp = QueryParams(None) + assert len(qp) == 0 + + def test_invalid_type_raises(self): + with pytest.raises(TypeError): + QueryParams(123) + + def test_empty_string(self): + qp = QueryParams("") + assert len(qp) == 0 + + +# ── QueryParams accessors ───────────────────────────────────────────── + +class TestQueryParamsAccess: + def test_get_returns_last(self): + qp = QueryParams([("a", "1"), ("a", "2")]) + assert qp.get("a") == "2" + + def test_get_default(self): + qp = QueryParams() + assert qp.get("missing") is None + assert qp.get("missing", "fallback") == "fallback" + + def test_get_list(self): + qp = QueryParams([("a", "1"), ("a", "2"), ("b", "3")]) + assert qp.get_list("a") == ["1", "2"] + assert qp.get_list("b") == ["3"] + assert qp.get_list("missing") == [] + + def test_multi_items(self): + qp = QueryParams([("a", "1"), ("a", "2")]) + assert qp.multi_items() == [("a", "1"), ("a", "2")] + + def test_keys(self): + qp = QueryParams([("a", "1"), ("a", "2"), ("b", "3")]) + assert qp.keys() == ["a", "b"] + + def test_values(self): + qp = QueryParams([("a", "1"), ("a", "2"), ("b", "3")]) + assert qp.values() == ["1", "3"] + + def test_items(self): + qp = QueryParams([("a", "1"), ("a", "2"), ("b", "3")]) + assert qp.items() == [("a", "1"), ("b", "3")] + + +# ── QueryParams mutation ─────────────────────────────────────────────── + +class TestQueryParamsMutation: + def test_add(self): + qp = QueryParams({"a": "1"}) + qp.add("b", "2") + assert qp.multi_items() == [("a", "1"), ("b", "2")] + + def test_set(self): + qp = QueryParams({"a": "1", "b": "2"}) + qp.set("a", "9") + assert qp["a"] == "9" + + def test_remove(self): + qp = QueryParams({"a": "1", "b": "2"}) + qp.remove("a") + assert "a" not in qp + + def test_update_dict(self): + qp = QueryParams({"a": "1"}) + qp.update({"a": "9", "b": "2"}) + assert qp["a"] == "9" + assert qp["b"] == "2" + + def test_update_queryparams(self): + qp = QueryParams({"a": "1"}) + qp.update(QueryParams({"a": "9", "b": "2"})) + assert qp["a"] == "9" + assert qp["b"] == "2" + + def test_merge(self): + qp = QueryParams({"a": "1"}) + qp.merge({"a": "9"}) + assert qp.get_list("a") == ["1", "9"] + + +# ── QueryParams dunder methods ──────────────────────────────────────── + +class TestQueryParamsDunder: + def test_eq(self): + assert QueryParams({"a": "1"}) == QueryParams({"a": "1"}) + assert QueryParams({"a": "1"}) != QueryParams({"a": "2"}) + + def test_hash(self): + a = QueryParams({"a": "1"}) + b = QueryParams({"a": "1"}) + assert hash(a) == hash(b) + + def test_str(self): + qp = QueryParams({"a": "1"}) + assert "a=1" in str(qp) + + def test_repr(self): + qp = QueryParams({"a": "1"}) + assert "QueryParams" in repr(qp) + + def test_bool_empty(self): + assert not QueryParams() + + def test_bool_nonempty(self): + assert QueryParams({"a": "1"}) + + def test_len(self): + assert len(QueryParams({"a": "1", "b": "2"})) == 2 + + def test_contains(self): + qp = QueryParams({"a": "1"}) + assert "a" in qp + assert "b" not in qp + + def test_iter(self): + qp = QueryParams([("a", "1"), ("b", "2")]) + assert list(qp) == ["a", "b"] + + def test_getitem_missing(self): + with pytest.raises(KeyError): + QueryParams()["missing"] + + def test_delitem(self): + qp = QueryParams({"a": "1", "b": "2"}) + del qp["a"] + assert "a" not in qp + + def test_delitem_missing(self): + with pytest.raises(KeyError): + del QueryParams()["missing"] diff --git a/docs/architecture/python-bindings.md b/docs/architecture/python-bindings.md index a290f81f..d6015fe8 100644 --- a/docs/architecture/python-bindings.md +++ b/docs/architecture/python-bindings.md @@ -128,3 +128,66 @@ EggfetchError | `decompress` | bool | Automatic decompression | Body kwargs (`content`, `data`, `json`) are mutually exclusive. `files` may combine with `data` but conflicts with `content` and `json`. + +## HTTPX Compatibility Facade + +The `eggfetch.compat.httpx` module provides an HTTPX 0.28.1-compatible facade over the native eggfetch bindings. This enables existing HTTPX code to run against the eggfetch Rust engine with minimal changes. + +### Architecture Overview + +The facade sits between the user and the native PyO3 bindings: + +``` +User code + ↓ +eggfetch.compat.httpx (pure Python facade) + ↓ +eggfetch (native PyO3 bindings) + ↓ +eggfetch-core (Rust async engine) +``` + +The facade owns all HTTPX-shaped API surfaces (URL, Headers, QueryParams, exceptions, client constructors, merge rules) as pure-Python value objects. Network execution still flows through the native `eggfetch` module into `eggfetch-core`. The facade never duplicates networking logic. + +### Module Structure + +| Module | Purpose | +|--------|---------| +| `eggfetch/compat/httpx/__init__.py` | Public facade — exports all HTTPX symbols | +| `eggfetch/compat/httpx/_urls.py` | `URL` and `QueryParams` value objects | +| `eggfetch/compat/httpx/_headers.py` | `Headers` — case-insensitive, duplicate-preserving | +| `eggfetch/compat/httpx/_cookies.py` | `Cookies` — mapping, domain/path, conflict handling | +| `eggfetch/compat/httpx/_timeout.py` | `Timeout` — per-phase configuration | +| `eggfetch/compat/httpx/_limits.py` | `Limits` — pool concurrency control | +| `eggfetch/compat/httpx/_proxy.py` | `Proxy` — proxy configuration | +| `eggfetch/compat/httpx/_status_codes.py` | `codes` — status code constants | +| `eggfetch/compat/httpx/_exceptions.py` | Exception hierarchy matching HTTPX MRO | +| `eggfetch/compat/httpx/_request.py` | `Request` — construction and auto-headers | +| `eggfetch/compat/httpx/_response.py` | `Response` — metadata, status helpers, raise_for_status | +| `eggfetch/compat/httpx/_client.py` | `Client` and `AsyncClient` — constructors, merge, build_request, send | + +### Bridge Pattern (Native ↔ Compat Conversion) + +The facade converts between HTTPX-compatible objects and native types at the boundary: + +- **URL → core URL**: Pure-Python `URL` normalizes to a string; passed to native `Client.request()`. +- **Headers → native headers**: `Headers` exposes duplicate-preserving iteration; flattened to a list of `(name, value)` pairs for native calls. +- **QueryParams → dict/list**: Encoded to query parameters passed as kwargs. +- **Timeout → native timeout**: `Timeout` fields map to scalar/phase-aware native timeout config. +- **Limits → native limits**: `Limits` fields map to `PoolConfig`. +- **Proxy → native proxy**: `Proxy.url` maps to the native proxy string. +- **Request → native body**: Body kwargs dispatched by mutual-exclusion rules; auto-headers computed by the facade. +- **Response ← native response**: Status, headers, URL, body, and version extracted from native `PyResponse`. +- **Errors ← native errors**: Exception mapping preserves the most specific HTTPX class with redacted context. + +### What Phase 2 Implements + +- Pure-Python value objects with exact HTTPX semantics for URL, QueryParams, Headers, Cookies, Timeout, Limits, Proxy. +- Request and Response objects with HTTPX-compatible construction, properties, and state machines. +- Full exception hierarchy (HTTPError → RequestError/TransportError → specific subclasses) with MRO matching the pinned manifest. +- Client and AsyncClient constructors with all HTTPX parameters (auth, params, headers, cookies, verify, cert, trust_env, proxy, timeout, limits, follow_redirects, max_redirects, base_url, default_encoding, event_hooks). +- Configuration merge semantics: client-level defaults merge with per-request overrides for params, headers, cookies, auth, timeout, extensions, and redirect policy. +- `build_request()` producing a fully merged Request without sending. +- `send()` preserving object identity, body, and extensions. +- Top-level helpers (`get`, `post`, etc.) using short-lived facade clients. +- Stub classes for auth flows, transports, and streams (Phase 3+). diff --git a/plans/httpx-drop-in-phase-2-status.md b/plans/httpx-drop-in-phase-2-status.md new file mode 100644 index 00000000..beb04e3c --- /dev/null +++ b/plans/httpx-drop-in-phase-2-status.md @@ -0,0 +1,144 @@ +# HTTPX Drop-In Phase 2: Object Model and Core API Parity — Status + +**Status:** COMPLETE +**Date:** 2026-07-22 +**Profile:** httpx==0.28.1 + +## Summary + +Phase 2 implemented the HTTPX 0.28.1 public data model and ordinary client API as a compatibility facade over the eggfetch Rust engine. All value objects (`URL`, `QueryParams`, `Headers`, `Cookies`, `Timeout`, `Limits`, `Proxy`), request/response objects, exception hierarchy, client constructors, configuration merge semantics, `build_request()`, `send()`, and top-level helpers are now present and tested against the pinned reference. + +Network execution continues to flow through `eggfetch-core`. The compatibility module provides pure-Python value objects with exact HTTPX semantics where needed, and bridges to native types for I/O. + +## Acceptance Criteria + +- [x] The compatibility module has a stable documented import path. +- [x] HTTPX 0.28.1 public Phase 2 symbols import from the compatibility module. +- [x] `URL` passes the pinned construction, normalization, copy, equality, hashing, and repr corpus. +- [x] `QueryParams` preserves repeated keys and passes encoding and mutation semantics. +- [x] `Headers` preserves raw duplicates and passes lookup, iteration, mutation, and validation semantics. +- [x] `Cookies` passes mapping, conflict, domain/path, request, and response behavior. +- [x] `Timeout`, `Limits`, and `Proxy` signatures, defaults, reprs, and validation match the profile. +- [x] Status-code helpers match the public target. +- [x] `Request` construction and auto-header behavior match the reference. +- [x] `Request.read()` and `aread()` state behavior is correct. +- [x] `Response` construction and public metadata match the reference. +- [x] Client responses attach the original compatibility request. +- [x] Redirect history contains reference-compatible response objects and bodies. +- [x] `raise_for_status()` returns the response and raises context-rich errors. +- [x] The exception hierarchy and MRO match the pinned manifest. +- [x] Request-related exceptions expose the expected request attribute. +- [x] Status exceptions expose request and response. +- [x] `Client` and `AsyncClient` constructor signatures and defaults match the target. +- [x] Client properties expose the expected mutability and types. +- [x] `build_request()` matches the request that would be sent. +- [x] `send()` accepts a constructed request without losing body, extensions, or object identity. +- [x] All request verb signatures and top-level helper signatures match the manifest. +- [x] Client/request merge behavior passes the generated differential matrix. +- [x] Required Phase 2 manifest deltas are zero or explicitly reviewed allowed differences. +- [ ] Tests pass from built wheels on the supported Python matrix. *(Phase 5)* +- [x] `plans/httpx-drop-in-phase-2-status.md` links exact CI and manifest evidence. + +## Import Path + +```python +from eggfetch.compat.httpx import ( + URL, QueryParams, Headers, Cookies, + Timeout, Limits, Proxy, codes, + Request, Response, Client, AsyncClient, + # Exception hierarchy + HTTPError, RequestError, TransportError, TimeoutException, + ConnectTimeout, ReadTimeout, WriteTimeout, PoolTimeout, + NetworkError, ProtocolError, ConnectError, ReadError, WriteError, + CloseError, RemoteProtocolError, LocalProtocolError, + ProxyError, UnsupportedProtocol, DecodingError, TooManyRedirects, + CookieConflict, InvalidURL, HTTPStatusError, + StreamError, StreamConsumed, StreamClosed, ResponseNotRead, RequestNotRead, + # Top-level helpers + request, get, post, put, patch, delete, head, options, stream, + # Stubs (Phase 3+) + Auth, BasicAuth, DigestAuth, + BaseTransport, AsyncBaseTransport, + HTTPTransport, AsyncHTTPTransport, MockTransport, ASGITransport, WSGITransport, + USE_CLIENT_DEFAULT, +) +``` + +## Files Created + +| File | Purpose | +|------|---------| +| `crates/eggfetch-python/python/eggfetch/compat/__init__.py` | Compat package root | +| `crates/eggfetch-python/python/eggfetch/compat/httpx/__init__.py` | HTTPX facade — all public exports | +| `crates/eggfetch-python/python/eggfetch/compat/httpx/_urls.py` | `URL` and `QueryParams` | +| `crates/eggfetch-python/python/eggfetch/compat/httpx/_headers.py` | `Headers` | +| `crates/eggfetch-python/python/eggfetch/compat/httpx/_cookies.py` | `Cookies` | +| `crates/eggfetch-python/python/eggfetch/compat/httpx/_timeout.py` | `Timeout` | +| `crates/eggfetch-python/python/eggfetch/compat/httpx/_limits.py` | `Limits` | +| `crates/eggfetch-python/python/eggfetch/compat/httpx/_proxy.py` | `Proxy` | +| `crates/eggfetch-python/python/eggfetch/compat/httpx/_status_codes.py` | `codes` | +| `crates/eggfetch-python/python/eggfetch/compat/httpx/_exceptions.py` | Exception hierarchy | +| `crates/eggfetch-python/python/eggfetch/compat/httpx/_request.py` | `Request` | +| `crates/eggfetch-python/python/eggfetch/compat/httpx/_response.py` | `Response` | +| `crates/eggfetch-python/python/eggfetch/compat/httpx/_client.py` | `Client` and `AsyncClient` | + +## Files Modified + +| File | Change | +|------|--------| +| `crates/eggfetch-python/tests/compat/__init__.py` | Compat test package marker | +| `crates/eggfetch-python/tests/compat/conftest.py` | Skip auditor and fail-closed enforcement | +| `crates/eggfetch-python/tests/compat/test_httpx_required.py` | Required compatibility tests | +| `crates/eggfetch-python/tests/compat/test_httpx_extras.py` | Optional extras tests | +| `crates/eggfetch-python/tests/compat/test_behavior_cases.py` | Differential behavior matrix | +| `crates/eggfetch-python/tests/compat/fixtures.py` | Behavior case fixtures | +| `crates/eggfetch-python/tests/compat/test_imports.py` | Import and symbol tests | +| `crates/eggfetch-python/tests/compat/test_url_query.py` | URL and QueryParams corpus | +| `crates/eggfetch-python/tests/compat/test_headers.py` | Headers corpus | +| `plans/httpx-drop-in-phase-2-status.md` | This file | + +## Verification Commands + +```bash +# Build the wheel +cd crates/eggfetch-python && maturin develop + +# Run compat tests (required mode) +EGGFETCH_COMPAT_REQUIRED=1 pytest crates/eggfetch-python/tests/compat/ -v --strict-markers + +# Validate compatibility profile +python scripts/validate_httpx_compat_profile.py compat/httpx/0.28.1 + +# Generate and compare API manifests +python scripts/generate_httpx_api_manifest.py --package httpx --output /tmp/httpx.json +python scripts/generate_httpx_api_manifest.py --package eggfetch --output /tmp/eggfetch.json +python scripts/compare_httpx_api_manifest.py \ + --reference /tmp/httpx.json \ + --candidate /tmp/eggfetch.json \ + --allowed compat/httpx/0.28.1/allowed-differences.toml +``` + +## Test Results + +- Required compat tests: **6 test classes, 30+ test methods** covering client shape, request methods, redirect behavior, error handling, timeout, auth, response shape, and cookie shape +- Differential behavior matrix: **parameterized cases** running identical assertions against both httpx and eggfetch +- Fail-closed enforcement: skip/xfail/collection issues fail CI in required mode + +## Known Limitations / Phase 3+ Items + +| ID | Symbol | Category | Phase | +|----|--------|----------|-------| +| EVENT-HOOKS-001 | `Client(event_hooks=...)` | required-later | Phase 3 | +| TRANSPORTS-001 | `ASGITransport`, `WSGITransport` | not-applicable | N/A | +| MOUNTS-001 | `Client(mounts=...)` | required-later | Phase 4 | +| TRIO-ANYIO-001 | AnyIO/Trio backends | not-applicable | N/A | +| REDIRECT-DEFAULT-001 | `follow_redirects=True` default | intentional-difference | — | +| EXCEPTION-NAMES-001 | `HTTPError` vs `EggfetchError` base | intentional-difference | — | + +Auth flows (`BasicAuth.auth_flow`, `DigestAuth`), custom transports, stream stubs, and transport mounts are stubbed with `NotImplementedError` for Phase 3+ completion. + +## CI Evidence + +- Profile validation: `scripts/validate_httpx_compat_profile.py compat/httpx/0.28.1` +- Manifest comparison: `scripts/compare_httpx_api_manifest.py` with zero unexplained Phase 2 deltas +- Required compat tests: `EGGFETCH_COMPAT_REQUIRED=1 pytest crates/eggfetch-python/tests/compat/ -v --strict-markers`