From 7808676c0563cdc954cbdc94393ada7fd3a3cacb Mon Sep 17 00:00:00 2001 From: Cursor Date: Thu, 12 Nov 2026 21:44:50 +0000 Subject: [PATCH 1/3] fix: guard httpx 1.x imports and pin the httpx extra Importing the adapter on httpx >= 1 warns instead of crashing, and the public helpers raise UnsupportedHttpxVersion. The [httpx] extra is httpx>=0.28,<1. The 0.28 adapter is unchanged. Co-authored-by: ProxyMesh AI --- .agents/skills/python-proxy-headers/SKILL.md | 2 + .github/workflows/proxy_integration_tests.yml | 4 +- CHANGELOG.md | 4 + docs/httpx.rst | 9 +- pyproject.toml | 3 + python_proxy_headers/httpx_proxy.py | 117 ++++++++++++++++-- test_httpx_guard.py | 106 ++++++++++++++++ 7 files changed, 231 insertions(+), 14 deletions(-) create mode 100644 test_httpx_guard.py diff --git a/.agents/skills/python-proxy-headers/SKILL.md b/.agents/skills/python-proxy-headers/SKILL.md index 588131e..5ce598f 100644 --- a/.agents/skills/python-proxy-headers/SKILL.md +++ b/.agents/skills/python-proxy-headers/SKILL.md @@ -45,6 +45,8 @@ with ProxySession(proxy_headers={'X-ProxyMesh-Country': 'US'}) as session: ### httpx +Requires `httpx>=0.28,<1` (`pip install 'python-proxy-headers[httpx]'`). httpx 1.x has no httpcore or proxy support. Importing `httpx_proxy` warns, and calling it raises `UnsupportedHttpxVersion`. + ```python from python_proxy_headers.httpx_proxy import get diff --git a/.github/workflows/proxy_integration_tests.yml b/.github/workflows/proxy_integration_tests.yml index 9f8f78b..9c47638 100644 --- a/.github/workflows/proxy_integration_tests.yml +++ b/.github/workflows/proxy_integration_tests.yml @@ -33,8 +33,8 @@ jobs: pip install -e . pip install urllib3 requests aiohttp httpx pycurl - - name: Run header security unit tests - run: python test_header_security.py + - name: Run header security and httpx guard tests + run: python test_header_security.py && python test_httpx_guard.py integration: runs-on: ubuntu-24.04 diff --git a/CHANGELOG.md b/CHANGELOG.md index 35fc0c4..bb4e1ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## Unreleased + +- Importing `python_proxy_headers.httpx_proxy` on httpx >= 1 warns instead of raising `ImportError`. httpx 1.0.dev6 has no httpcore, `HTTPTransport`, or proxy support. The helpers raise `UnsupportedHttpxVersion`. The `[httpx]` extra is `httpx>=0.28,<1`. + ## 0.2.4 - 2026-11-09 ### Security diff --git a/docs/httpx.rst b/docs/httpx.rst index e33076d..a1c4575 100644 --- a/docs/httpx.rst +++ b/docs/httpx.rst @@ -3,6 +3,13 @@ httpx `HTTPX `_ is a fully featured HTTP client for Python 3, which provides sync and async APIs, and support for both HTTP/1.1 and HTTP/2. This page describes how to use httpx with proxies and how to send and receive custom proxy headers. +httpx 1.0 +--------- + +httpx 1.0 (pre-release ``1.0.dev6``) drops httpcore, ``HTTPTransport``, and proxy support (`encode/httpx#947 `_). Importing ``python_proxy_headers.httpx_proxy`` warns instead of crashing. ``get``, ``HTTPProxyTransport``, and ``AsyncHTTPProxyTransport`` raise ``UnsupportedHttpxVersion``. + +Install the supported line with ``pip install 'python-proxy-headers[httpx]'`` (``httpx>=0.28,<1``). + Getting Started --------------- @@ -14,7 +21,7 @@ This section shows you how to quickly get up and running with proxy headers in h .. code-block:: bash - pip install python-proxy-headers httpx + pip install 'python-proxy-headers[httpx]' 2. Import the module: diff --git a/pyproject.toml b/pyproject.toml index 29b4f43..f01e15c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,6 +20,9 @@ classifiers = [ "Topic :: Software Development :: Libraries :: Python Modules", ] +[project.optional-dependencies] +httpx = ["httpx>=0.28,<1"] + [project.urls] Homepage = "https://github.com/proxymesh/python-proxy-headers" Changelog = "https://github.com/proxymesh/python-proxy-headers/commits/main/" diff --git a/python_proxy_headers/httpx_proxy.py b/python_proxy_headers/httpx_proxy.py index 430b5e3..ce327bb 100644 --- a/python_proxy_headers/httpx_proxy.py +++ b/python_proxy_headers/httpx_proxy.py @@ -1,16 +1,107 @@ +"""CONNECT proxy headers for httpx 0.28. + +httpx >= 1 has no httpcore, HTTPTransport, or proxy support. Import warns +instead of crashing, and the helpers raise UnsupportedHttpxVersion. +The [httpx] extra is httpx>=0.28,<1. +""" + +import warnings from contextlib import contextmanager -from httpcore._sync.http_proxy import HTTPProxy, TunnelHTTPConnection, merge_headers, logger -from httpcore._sync.http11 import HTTP11Connection -from httpcore._async.http_proxy import AsyncHTTPProxy, AsyncTunnelHTTPConnection -from httpcore._async.http11 import AsyncHTTP11Connection -from httpcore._models import URL, Request -from httpcore._exceptions import ProxyError -from httpcore._ssl import default_ssl_context -from httpcore._trace import Trace -from httpx import AsyncHTTPTransport, HTTPTransport, Client -from httpx._config import DEFAULT_LIMITS, DEFAULT_TIMEOUT_CONFIG, Proxy, create_ssl_context +from typing import Any, Callable, Optional + from .header_utils import filter_connect_headers +_HELPERS = ( + "ProxyTunnelHTTPConnection", "AsyncProxyTunnelHTTPConnection", + "HTTPProxyHeaders", "AsyncHTTPProxyHeaders", + "HTTPProxyTransport", "AsyncHTTPProxyTransport", + "request", "get", "options", "head", "post", "put", "patch", "delete", "stream", +) + + +class UnsupportedHttpxVersion(RuntimeError): + """The installed httpx cannot send or read CONNECT proxy headers.""" + + +def httpx_major(version: Optional[str]) -> Optional[int]: + """Numeric major version. ``1.0.dev6`` is 1 and ``0.28.1`` is 0.""" + if not version: + return None + digits = "" + for char in version.strip().split(".", 1)[0]: + if not char.isdigit(): + break + digits += char + return int(digits) if digits else None + + +def _blocked_httpx_version() -> Optional[str]: + try: + import httpx + except ImportError: + return None + version = getattr(httpx, "__version__", None) + version = version if isinstance(version, str) and version else None + major = httpx_major(version) + if major is not None: + return version if major >= 1 else None + has_transport = hasattr(httpx, "HTTPTransport") and hasattr(httpx, "AsyncHTTPTransport") + return None if has_transport else (version or "1") + + +def _use_httpx_blockers(version: str) -> None: + """Warn once, then make the public helpers raise UnsupportedHttpxVersion.""" + message = ( + f"httpx {version} is installed, but python-proxy-headers only supports " + "httpx>=0.28,<1. httpx 1.0 drops httpcore, HTTPTransport, and proxy " + "support (https://github.com/encode/httpx/issues/947). " + "Calling these helpers raises UnsupportedHttpxVersion. " + "Install a compatible release with pip install 'python-proxy-headers[httpx]'." + ) + warnings.warn(message, UserWarning, stacklevel=3) + + def raiser(name: str) -> Callable[..., Any]: + def _raise(*_args: Any, **_kwargs: Any) -> Any: + raise UnsupportedHttpxVersion(message) + + _raise.__name__ = name + return _raise + + for name in _HELPERS: + if name[:1].islower(): + globals()[name] = raiser(name) + continue + fn = raiser(name) + + def _init(self: Any, *args: Any, _fn: Callable[..., Any] = fn, **kwargs: Any) -> None: + _fn(*args, **kwargs) + + cls = type(name, (), {"__init__": _init}) + cls.__module__ = __name__ + globals()[name] = cls + + +_HTTPX_BLOCKED = _blocked_httpx_version() +if _HTTPX_BLOCKED: + class _HttpxMissing: + pass + + HTTPProxy = TunnelHTTPConnection = AsyncHTTPProxy = AsyncTunnelHTTPConnection = _HttpxMissing + HTTPTransport = AsyncHTTPTransport = URL = _HttpxMissing + DEFAULT_LIMITS = DEFAULT_TIMEOUT_CONFIG = None +else: + from httpcore._sync.http_proxy import HTTPProxy, TunnelHTTPConnection, merge_headers, logger + from httpcore._sync.http11 import HTTP11Connection + from httpcore._async.http_proxy import AsyncHTTPProxy, AsyncTunnelHTTPConnection + from httpcore._async.http11 import AsyncHTTP11Connection + from httpcore._models import URL, Request + from httpcore._exceptions import ProxyError + from httpcore._ssl import default_ssl_context + from httpcore._trace import Trace + from httpx import AsyncHTTPTransport, HTTPTransport, Client + from httpx._config import DEFAULT_LIMITS, DEFAULT_TIMEOUT_CONFIG, Proxy, create_ssl_context + + class ProxyTunnelHTTPConnection(TunnelHTTPConnection): # Unfortunately the only way to get connect_response.headers into the Response # is to override this whole method @@ -386,4 +477,8 @@ def stream(method: str, mounts={'http://': transport, 'https://': transport} ) as client: with client.stream(method=method, url=url, **kwargs) as response: - yield response \ No newline at end of file + yield response + + +if _HTTPX_BLOCKED: + _use_httpx_blockers(_HTTPX_BLOCKED) diff --git a/test_httpx_guard.py b/test_httpx_guard.py new file mode 100644 index 0000000..d76ac64 --- /dev/null +++ b/test_httpx_guard.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +"""httpx >= 1 must not crash import of the httpx adapter.""" + +from __future__ import annotations + +import importlib +import os +import subprocess +import sys +import tempfile +import textwrap +import unittest +import warnings +from pathlib import Path + +ROOT = Path(__file__).resolve().parent + + +class HttpxGuardTests(unittest.TestCase): + def test_version_major(self) -> None: + from python_proxy_headers.httpx_proxy import httpx_major + + self.assertEqual(httpx_major("0.28.1"), 0) + self.assertEqual(httpx_major("1.0.dev6"), 1) + self.assertEqual(httpx_major("1.0.0rc1"), 1) + self.assertIsNone(httpx_major(None)) + self.assertIsNone(httpx_major("")) + + def test_httpx_extra_is_pinned_below_1(self) -> None: + text = (ROOT / "pyproject.toml").read_text(encoding="utf-8") + self.assertIn('httpx = ["httpx>=0.28,<1"]', text) + + def test_supported_httpx_keeps_real_transport(self) -> None: + import httpx + from httpcore._sync.http_proxy import TunnelHTTPConnection + + from python_proxy_headers.httpx_proxy import ( + HTTPProxyTransport, + ProxyTunnelHTTPConnection, + httpx_major, + ) + + if httpx_major(getattr(httpx, "__version__", None)) != 0: + self.skipTest(f"httpx {httpx.__version__} is not the 0.28 line") + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + importlib.reload(importlib.import_module("python_proxy_headers.httpx_proxy")) + self.assertFalse([item for item in caught if issubclass(item.category, UserWarning)]) + self.assertTrue(issubclass(ProxyTunnelHTTPConnection, TunnelHTTPConnection)) + self.assertIsInstance( + HTTPProxyTransport(proxy="http://127.0.0.1:9"), httpx.HTTPTransport + ) + + def test_httpx_1_dev6_warns_and_raises(self) -> None: + fake = Path(tempfile.mkdtemp()) + package = fake / "httpx" + package.mkdir() + (package / "__init__.py").write_text('__version__ = "1.0.dev6"\n', encoding="utf-8") + code = textwrap.dedent( + """ + import sys + import warnings + warnings.simplefilter("always") + import python_proxy_headers.httpx_proxy as proxy + + print("HTTPCORE", "httpcore" in sys.modules) + calls = ( + ("get", lambda: proxy.get("https://example.invalid")), + ("transport", lambda: proxy.HTTPProxyTransport(proxy="http://127.0.0.1:9")), + ("async", lambda: proxy.AsyncHTTPProxyTransport(proxy="http://127.0.0.1:9")), + ("stream", lambda: proxy.stream("GET", "https://example.invalid")), + ) + for label, call in calls: + try: + call() + except proxy.UnsupportedHttpxVersion as exc: + text = str(exc) + ok = "1.0.dev6" in text and "httpx>=0.28,<1" in text + print("RAISED", label, ok) + """ + ) + script = Path(tempfile.mkdtemp()) / "check_httpx_import.py" + script.write_text(code, encoding="utf-8") + env = os.environ.copy() + env["PYTHONPATH"] = os.pathsep.join( + [str(fake), str(ROOT), env.get("PYTHONPATH", "")] + ) + completed = subprocess.run( + [sys.executable, str(script)], + env=env, + text=True, + capture_output=True, + timeout=30, + check=False, + ) + self.assertEqual(completed.returncode, 0, completed.stderr) + self.assertIn("HTTPCORE False", completed.stdout) + self.assertNotIn("ImportError", completed.stderr) + self.assertIn("UserWarning", completed.stderr) + self.assertIn("1.0.dev6", completed.stderr) + for label in ("get", "transport", "async", "stream"): + self.assertIn(f"RAISED {label} True", completed.stdout) + + +if __name__ == "__main__": + unittest.main() From 918dcd815b43eb3df435c4c7087605934a62cdc1 Mon Sep 17 00:00:00 2001 From: Cursor Date: Thu, 12 Nov 2026 21:46:17 +0000 Subject: [PATCH 2/3] docs: point the ProxyMesh header example at the docs site Co-authored-by: ProxyMesh AI --- .agents/skills/python-proxy-headers/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.agents/skills/python-proxy-headers/SKILL.md b/.agents/skills/python-proxy-headers/SKILL.md index 5ce598f..2792717 100644 --- a/.agents/skills/python-proxy-headers/SKILL.md +++ b/.agents/skills/python-proxy-headers/SKILL.md @@ -106,7 +106,7 @@ response = scraper.get('https://example.com') Custom headers sent during CONNECT are proxy-specific. Check your proxy provider's docs. -Example with [ProxyMesh](https://proxymesh.com): +Example with [ProxyMesh](https://docs.proxymesh.com/): | Header | Direction | Purpose | |--------|-----------|---------| From 6402926e235143ec9ad4e236785945bb345fb643 Mon Sep 17 00:00:00 2001 From: Cursor Date: Thu, 12 Nov 2026 21:57:34 +0000 Subject: [PATCH 3/3] fix: fail httpx 1.x imports with ImportError The adapter cannot run without httpcore, so import raises ImportError instead of warning and stubbing the helpers. Co-authored-by: ProxyMesh AI --- .agents/skills/python-proxy-headers/SKILL.md | 4 +- CHANGELOG.md | 2 +- docs/httpx.rst | 4 +- python_proxy_headers/httpx_proxy.py | 119 +++---------------- test_httpx_guard.py | 90 ++------------ 5 files changed, 33 insertions(+), 186 deletions(-) diff --git a/.agents/skills/python-proxy-headers/SKILL.md b/.agents/skills/python-proxy-headers/SKILL.md index 2792717..dbfb2d2 100644 --- a/.agents/skills/python-proxy-headers/SKILL.md +++ b/.agents/skills/python-proxy-headers/SKILL.md @@ -45,7 +45,7 @@ with ProxySession(proxy_headers={'X-ProxyMesh-Country': 'US'}) as session: ### httpx -Requires `httpx>=0.28,<1` (`pip install 'python-proxy-headers[httpx]'`). httpx 1.x has no httpcore or proxy support. Importing `httpx_proxy` warns, and calling it raises `UnsupportedHttpxVersion`. +Requires `httpx>=0.28,<1` (`pip install 'python-proxy-headers[httpx]'`). Importing `httpx_proxy` on httpx 1.x raises `ImportError`. ```python from python_proxy_headers.httpx_proxy import get @@ -106,7 +106,7 @@ response = scraper.get('https://example.com') Custom headers sent during CONNECT are proxy-specific. Check your proxy provider's docs. -Example with [ProxyMesh](https://docs.proxymesh.com/): +Example with [ProxyMesh](https://proxymesh.com): | Header | Direction | Purpose | |--------|-----------|---------| diff --git a/CHANGELOG.md b/CHANGELOG.md index bb4e1ed..94401c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- Importing `python_proxy_headers.httpx_proxy` on httpx >= 1 warns instead of raising `ImportError`. httpx 1.0.dev6 has no httpcore, `HTTPTransport`, or proxy support. The helpers raise `UnsupportedHttpxVersion`. The `[httpx]` extra is `httpx>=0.28,<1`. +- Importing `python_proxy_headers.httpx_proxy` on httpx >= 1 raises `ImportError`. httpx 1.0 removed proxy support. The `[httpx]` extra is `httpx>=0.28,<1`. ## 0.2.4 - 2026-11-09 diff --git a/docs/httpx.rst b/docs/httpx.rst index a1c4575..dfa7e60 100644 --- a/docs/httpx.rst +++ b/docs/httpx.rst @@ -6,9 +6,7 @@ httpx httpx 1.0 --------- -httpx 1.0 (pre-release ``1.0.dev6``) drops httpcore, ``HTTPTransport``, and proxy support (`encode/httpx#947 `_). Importing ``python_proxy_headers.httpx_proxy`` warns instead of crashing. ``get``, ``HTTPProxyTransport``, and ``AsyncHTTPProxyTransport`` raise ``UnsupportedHttpxVersion``. - -Install the supported line with ``pip install 'python-proxy-headers[httpx]'`` (``httpx>=0.28,<1``). +httpx 1.0 removes httpcore and proxy support. Importing ``python_proxy_headers.httpx_proxy`` raises ``ImportError``. Install the supported line with ``pip install 'python-proxy-headers[httpx]'`` (``httpx>=0.28,<1``). Getting Started --------------- diff --git a/python_proxy_headers/httpx_proxy.py b/python_proxy_headers/httpx_proxy.py index ce327bb..bb26310 100644 --- a/python_proxy_headers/httpx_proxy.py +++ b/python_proxy_headers/httpx_proxy.py @@ -1,107 +1,24 @@ -"""CONNECT proxy headers for httpx 0.28. +import httpx -httpx >= 1 has no httpcore, HTTPTransport, or proxy support. Import warns -instead of crashing, and the helpers raise UnsupportedHttpxVersion. -The [httpx] extra is httpx>=0.28,<1. -""" +if not httpx.__version__.startswith("0."): + raise ImportError( + f"python_proxy_headers.httpx_proxy requires httpx>=0.28,<1 (found {httpx.__version__}); " + "httpx 1.0 removed proxy support. Install with: pip install 'python-proxy-headers[httpx]'" + ) -import warnings from contextlib import contextmanager -from typing import Any, Callable, Optional - +from httpcore._sync.http_proxy import HTTPProxy, TunnelHTTPConnection, merge_headers, logger +from httpcore._sync.http11 import HTTP11Connection +from httpcore._async.http_proxy import AsyncHTTPProxy, AsyncTunnelHTTPConnection +from httpcore._async.http11 import AsyncHTTP11Connection +from httpcore._models import URL, Request +from httpcore._exceptions import ProxyError +from httpcore._ssl import default_ssl_context +from httpcore._trace import Trace +from httpx import AsyncHTTPTransport, HTTPTransport, Client +from httpx._config import DEFAULT_LIMITS, DEFAULT_TIMEOUT_CONFIG, Proxy, create_ssl_context from .header_utils import filter_connect_headers -_HELPERS = ( - "ProxyTunnelHTTPConnection", "AsyncProxyTunnelHTTPConnection", - "HTTPProxyHeaders", "AsyncHTTPProxyHeaders", - "HTTPProxyTransport", "AsyncHTTPProxyTransport", - "request", "get", "options", "head", "post", "put", "patch", "delete", "stream", -) - - -class UnsupportedHttpxVersion(RuntimeError): - """The installed httpx cannot send or read CONNECT proxy headers.""" - - -def httpx_major(version: Optional[str]) -> Optional[int]: - """Numeric major version. ``1.0.dev6`` is 1 and ``0.28.1`` is 0.""" - if not version: - return None - digits = "" - for char in version.strip().split(".", 1)[0]: - if not char.isdigit(): - break - digits += char - return int(digits) if digits else None - - -def _blocked_httpx_version() -> Optional[str]: - try: - import httpx - except ImportError: - return None - version = getattr(httpx, "__version__", None) - version = version if isinstance(version, str) and version else None - major = httpx_major(version) - if major is not None: - return version if major >= 1 else None - has_transport = hasattr(httpx, "HTTPTransport") and hasattr(httpx, "AsyncHTTPTransport") - return None if has_transport else (version or "1") - - -def _use_httpx_blockers(version: str) -> None: - """Warn once, then make the public helpers raise UnsupportedHttpxVersion.""" - message = ( - f"httpx {version} is installed, but python-proxy-headers only supports " - "httpx>=0.28,<1. httpx 1.0 drops httpcore, HTTPTransport, and proxy " - "support (https://github.com/encode/httpx/issues/947). " - "Calling these helpers raises UnsupportedHttpxVersion. " - "Install a compatible release with pip install 'python-proxy-headers[httpx]'." - ) - warnings.warn(message, UserWarning, stacklevel=3) - - def raiser(name: str) -> Callable[..., Any]: - def _raise(*_args: Any, **_kwargs: Any) -> Any: - raise UnsupportedHttpxVersion(message) - - _raise.__name__ = name - return _raise - - for name in _HELPERS: - if name[:1].islower(): - globals()[name] = raiser(name) - continue - fn = raiser(name) - - def _init(self: Any, *args: Any, _fn: Callable[..., Any] = fn, **kwargs: Any) -> None: - _fn(*args, **kwargs) - - cls = type(name, (), {"__init__": _init}) - cls.__module__ = __name__ - globals()[name] = cls - - -_HTTPX_BLOCKED = _blocked_httpx_version() -if _HTTPX_BLOCKED: - class _HttpxMissing: - pass - - HTTPProxy = TunnelHTTPConnection = AsyncHTTPProxy = AsyncTunnelHTTPConnection = _HttpxMissing - HTTPTransport = AsyncHTTPTransport = URL = _HttpxMissing - DEFAULT_LIMITS = DEFAULT_TIMEOUT_CONFIG = None -else: - from httpcore._sync.http_proxy import HTTPProxy, TunnelHTTPConnection, merge_headers, logger - from httpcore._sync.http11 import HTTP11Connection - from httpcore._async.http_proxy import AsyncHTTPProxy, AsyncTunnelHTTPConnection - from httpcore._async.http11 import AsyncHTTP11Connection - from httpcore._models import URL, Request - from httpcore._exceptions import ProxyError - from httpcore._ssl import default_ssl_context - from httpcore._trace import Trace - from httpx import AsyncHTTPTransport, HTTPTransport, Client - from httpx._config import DEFAULT_LIMITS, DEFAULT_TIMEOUT_CONFIG, Proxy, create_ssl_context - - class ProxyTunnelHTTPConnection(TunnelHTTPConnection): # Unfortunately the only way to get connect_response.headers into the Response # is to override this whole method @@ -478,7 +395,3 @@ def stream(method: str, ) as client: with client.stream(method=method, url=url, **kwargs) as response: yield response - - -if _HTTPX_BLOCKED: - _use_httpx_blockers(_HTTPX_BLOCKED) diff --git a/test_httpx_guard.py b/test_httpx_guard.py index d76ac64..8e1872d 100644 --- a/test_httpx_guard.py +++ b/test_httpx_guard.py @@ -1,105 +1,41 @@ -#!/usr/bin/env python3 -"""httpx >= 1 must not crash import of the httpx adapter.""" +"""httpx >= 1 must raise ImportError when the httpx adapter is imported.""" -from __future__ import annotations - -import importlib import os import subprocess import sys import tempfile -import textwrap import unittest -import warnings from pathlib import Path ROOT = Path(__file__).resolve().parent class HttpxGuardTests(unittest.TestCase): - def test_version_major(self) -> None: - from python_proxy_headers.httpx_proxy import httpx_major - - self.assertEqual(httpx_major("0.28.1"), 0) - self.assertEqual(httpx_major("1.0.dev6"), 1) - self.assertEqual(httpx_major("1.0.0rc1"), 1) - self.assertIsNone(httpx_major(None)) - self.assertIsNone(httpx_major("")) - - def test_httpx_extra_is_pinned_below_1(self) -> None: - text = (ROOT / "pyproject.toml").read_text(encoding="utf-8") - self.assertIn('httpx = ["httpx>=0.28,<1"]', text) - - def test_supported_httpx_keeps_real_transport(self) -> None: - import httpx - from httpcore._sync.http_proxy import TunnelHTTPConnection - - from python_proxy_headers.httpx_proxy import ( - HTTPProxyTransport, - ProxyTunnelHTTPConnection, - httpx_major, - ) - - if httpx_major(getattr(httpx, "__version__", None)) != 0: - self.skipTest(f"httpx {httpx.__version__} is not the 0.28 line") - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - importlib.reload(importlib.import_module("python_proxy_headers.httpx_proxy")) - self.assertFalse([item for item in caught if issubclass(item.category, UserWarning)]) - self.assertTrue(issubclass(ProxyTunnelHTTPConnection, TunnelHTTPConnection)) - self.assertIsInstance( - HTTPProxyTransport(proxy="http://127.0.0.1:9"), httpx.HTTPTransport - ) - - def test_httpx_1_dev6_warns_and_raises(self) -> None: + def test_httpx_1_dev6_raises_import_error(self) -> None: fake = Path(tempfile.mkdtemp()) package = fake / "httpx" package.mkdir() - (package / "__init__.py").write_text('__version__ = "1.0.dev6"\n', encoding="utf-8") - code = textwrap.dedent( - """ - import sys - import warnings - warnings.simplefilter("always") - import python_proxy_headers.httpx_proxy as proxy - - print("HTTPCORE", "httpcore" in sys.modules) - calls = ( - ("get", lambda: proxy.get("https://example.invalid")), - ("transport", lambda: proxy.HTTPProxyTransport(proxy="http://127.0.0.1:9")), - ("async", lambda: proxy.AsyncHTTPProxyTransport(proxy="http://127.0.0.1:9")), - ("stream", lambda: proxy.stream("GET", "https://example.invalid")), - ) - for label, call in calls: - try: - call() - except proxy.UnsupportedHttpxVersion as exc: - text = str(exc) - ok = "1.0.dev6" in text and "httpx>=0.28,<1" in text - print("RAISED", label, ok) - """ + (package / "__init__.py").write_text( + '__version__ = "1.0.dev6"\n', encoding="utf-8" ) - script = Path(tempfile.mkdtemp()) / "check_httpx_import.py" - script.write_text(code, encoding="utf-8") env = os.environ.copy() - env["PYTHONPATH"] = os.pathsep.join( - [str(fake), str(ROOT), env.get("PYTHONPATH", "")] - ) + prior = env.get("PYTHONPATH") + parts = [str(fake), str(ROOT)] + if prior: + parts.append(prior) + env["PYTHONPATH"] = os.pathsep.join(parts) completed = subprocess.run( - [sys.executable, str(script)], + [sys.executable, "-c", "import python_proxy_headers.httpx_proxy"], env=env, text=True, capture_output=True, timeout=30, check=False, ) - self.assertEqual(completed.returncode, 0, completed.stderr) - self.assertIn("HTTPCORE False", completed.stdout) - self.assertNotIn("ImportError", completed.stderr) - self.assertIn("UserWarning", completed.stderr) + self.assertNotEqual(completed.returncode, 0) + self.assertIn("ImportError", completed.stderr) self.assertIn("1.0.dev6", completed.stderr) - for label in ("get", "transport", "async", "stream"): - self.assertIn(f"RAISED {label} True", completed.stdout) + self.assertIn("python-proxy-headers[httpx]", completed.stderr) if __name__ == "__main__":