From 22976b08f7f8f53f96993b82fe629c54db83c862 Mon Sep 17 00:00:00 2001 From: zacchua-stripe Date: Thu, 12 Nov 2026 10:12:33 -0800 Subject: [PATCH 1/4] Link v17 migration guide to the wiki (#1977) Point the major changefile's migration guide link at the published wiki page and rebuild CHANGELOG.md. The previous link pointed at a branch or repo path that can move or be deleted. Committed-By-Agent: claude Co-authored-by: Claude Opus 5.5 --- .../changes/2026-10-30_zacchua_omit-pickled-api-keys.change.md | 2 +- CHANGELOG.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.hark/changes/2026-10-30_zacchua_omit-pickled-api-keys.change.md b/.hark/changes/2026-10-30_zacchua_omit-pickled-api-keys.change.md index 3642fa3ee..bc7173ee9 100644 --- a/.hark/changes/2026-10-30_zacchua_omit-pickled-api-keys.change.md +++ b/.hark/changes/2026-10-30_zacchua_omit-pickled-api-keys.change.md @@ -6,4 +6,4 @@ released_in_version: 17.0.0 StripeObject pickles no longer preserve API keys. Before making requests through an unpickled object, call `reattach_api_key(api_key)`. This also reattaches API keys to nested objects. -See the [v17 migration guide](https://github.com/stripe/stripe-python/blob/master/.hark/migration-guides/v17.md#api-keys-are-no-longer-preserved-in-pickled-stripeobjects) for details. +See the [v17 migration guide](https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v17#api-keys-are-no-longer-preserved-in-pickled-stripeobjects) for details. diff --git a/CHANGELOG.md b/CHANGELOG.md index 168094b29..2f1f0bb35 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,7 @@ Instead, edit a corresponding `.change.md` file and run `hark build`. StripeObject pickles no longer preserve API keys. Before making requests through an unpickled object, call `reattach_api_key(api_key)`. This also reattaches API keys to nested objects. - See the [v17 migration guide](https://github.com/stripe/stripe-python/blob/master/.hark/migration-guides/v17.md#api-keys-are-no-longer-preserved-in-pickled-stripeobjects) for details. + See the [v17 migration guide](https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v17#api-keys-are-no-longer-preserved-in-pickled-stripeobjects) for details. * Fix stale Stripe-Account header when fetching an object related to a directly-retrieved Event * Reject header values containing CR, LF or NUL in the pycurl HTTP client From 7254286570dcacb689f933db913e7cdf303818db Mon Sep 17 00:00:00 2001 From: itsrayeedscodespace Date: Fri, 13 Nov 2026 11:42:09 -0500 Subject: [PATCH 2/4] Allow configurable timeouts for PycurlClient (#1975) * fix: make PycurlClient timeouts configurable PycurlClient hardcoded CONNECTTIMEOUT=30 and TIMEOUT=80 on every request, unlike RequestsClient, HTTPXClient and AIOHTTPClient, which accept a `timeout` constructor argument. Add keyword-only `timeout` and `connect_timeout` arguments (defaults 80 and 30) after the existing parameters so positional callers are unaffected. Fixes #1962 * Remove unnecessary PycurlClient constructor docstring --- ...ace_pycurl-configurable-timeouts.change.md | 8 ++ stripe/_http_client.py | 9 +- tests/test_http_client.py | 101 ++++++++++++++++++ 3 files changed, 116 insertions(+), 2 deletions(-) create mode 100644 .hark/changes/2026-11-06_itsrayeedscodespace_pycurl-configurable-timeouts.change.md diff --git a/.hark/changes/2026-11-06_itsrayeedscodespace_pycurl-configurable-timeouts.change.md b/.hark/changes/2026-11-06_itsrayeedscodespace_pycurl-configurable-timeouts.change.md new file mode 100644 index 000000000..0e93637c7 --- /dev/null +++ b/.hark/changes/2026-11-06_itsrayeedscodespace_pycurl-configurable-timeouts.change.md @@ -0,0 +1,8 @@ +--- +title: Add configurable `timeout` and `connect_timeout` to `PycurlClient` +semver_level: minor +github_issues_resolved: +- https://github.com/stripe/stripe-python/issues/1962 +--- + +`PycurlClient` now accepts keyword-only `timeout` (total request time, curl's `TIMEOUT`) and `connect_timeout` (curl's `CONNECTTIMEOUT`) arguments, in whole seconds. They default to the previous hardcoded values of 80 and 30 seconds. diff --git a/stripe/_http_client.py b/stripe/_http_client.py index 51740e156..f11f6c600 100644 --- a/stripe/_http_client.py +++ b/stripe/_http_client.py @@ -858,12 +858,17 @@ def __init__( proxy: Optional[HTTPClient._Proxy] = None, async_fallback_client: Optional[HTTPClient] = None, _lib=None, # used for internal unit testing + *, + timeout: int = 80, + connect_timeout: int = 30, ): super(PycurlClient, self).__init__( verify_ssl_certs=verify_ssl_certs, proxy=proxy, async_fallback_client=async_fallback_client, ) + self._timeout = timeout + self._connect_timeout = connect_timeout if _lib is None: import pycurl # pyright: ignore[reportMissingModuleSource] @@ -985,8 +990,8 @@ def _request_internal( curl.setopt(self.pycurl.WRITEFUNCTION, b.write) curl.setopt(self.pycurl.HEADERFUNCTION, rheaders.write) curl.setopt(self.pycurl.NOSIGNAL, 1) - curl.setopt(self.pycurl.CONNECTTIMEOUT, 30) - curl.setopt(self.pycurl.TIMEOUT, 80) + curl.setopt(self.pycurl.CONNECTTIMEOUT, self._connect_timeout) + curl.setopt(self.pycurl.TIMEOUT, self._timeout) _assert_no_header_injection(headers) curl.setopt( self.pycurl.HTTPHEADER, diff --git a/tests/test_http_client.py b/tests/test_http_client.py index 937eec3fa..153704ed8 100644 --- a/tests/test_http_client.py +++ b/tests/test_http_client.py @@ -1167,6 +1167,107 @@ def test_request_rejects_header_injection( with pytest.raises(ValueError): make_request("get", self.valid_url, headers, None) + @pytest.mark.parametrize( + "client_kwargs,expected_connect_timeout,expected_timeout", + [ + ({}, 30, 80), + ({"connect_timeout": 5, "timeout": 10}, 5, 10), + ({"connect_timeout": 5}, 5, 80), + ({"timeout": 10}, 30, 10), + ], + ) + def test_timeout( + self, + mocked_request_lib, + mock_response, + make_request, + client_kwargs, + expected_connect_timeout, + expected_timeout, + ): + mock_response(mocked_request_lib, '{"foo": "baz"}', 200) + make_request( + "GET", self.valid_url, {}, None, client_kwargs=client_kwargs + ) + + curl_mock = mocked_request_lib.Curl() + curl_mock.setopt.assert_any_call( + mocked_request_lib.CONNECTTIMEOUT, expected_connect_timeout + ) + curl_mock.setopt.assert_any_call( + mocked_request_lib.TIMEOUT, expected_timeout + ) + + def test_timeout_stream( + self, mocked_request_lib, mock_response, make_streamed_request + ): + mock_response(mocked_request_lib, "some streamed content", 200) + make_streamed_request( + "GET", + self.valid_url, + {}, + None, + client_kwargs={"connect_timeout": 5, "timeout": 10}, + ) + + curl_mock = mocked_request_lib.Curl() + curl_mock.setopt.assert_any_call(mocked_request_lib.CONNECTTIMEOUT, 5) + curl_mock.setopt.assert_any_call(mocked_request_lib.TIMEOUT, 10) + + def test_timeout_reapplied_after_reset( + self, mocked_request_lib, mock_response, make_client + ): + mock_response(mocked_request_lib, '{"foo": "baz"}', 200) + client = make_client(connect_timeout=5, timeout=10) + + client.request("get", self.valid_url, {}) + client.request("get", self.valid_url, {}) + + curl_mock = mocked_request_lib.Curl() + # reset() clears every option, so each request must set the + # timeouts again after its own reset() call. + relevant_calls = [ + c + for c in curl_mock.mock_calls + if c == call.reset() + or ( + c[0] == "setopt" + and c[1][0] + in ( + mocked_request_lib.CONNECTTIMEOUT, + mocked_request_lib.TIMEOUT, + ) + ) + ] + assert ( + relevant_calls + == [ + call.reset(), + call.setopt(mocked_request_lib.CONNECTTIMEOUT, 5), + call.setopt(mocked_request_lib.TIMEOUT, 10), + ] + * 2 + ) + + def test_positional_args(self, mocked_request_lib): + client = self.REQUEST_CLIENT(False, None, None, mocked_request_lib) + + assert client.pycurl is mocked_request_lib + assert client._verify_ssl_certs is False + assert client._connect_timeout == 30 + assert client._timeout == 80 + + # Timeouts are keyword-only so they can't be confused with each + # other or with the existing positional parameters. + with pytest.raises(TypeError): + self.REQUEST_CLIENT( + False, + None, + None, + mocked_request_lib, + 10, # pyright: ignore[reportGeneralTypeIssues] + ) + @pytest.fixture def created_curls(self, mocked_request_lib): curls: List[Mock] = [] From 11ff99cbecb2eba530f23eee2fac65bd52144eb5 Mon Sep 17 00:00:00 2001 From: mark-kogan-stripe Date: Mon, 16 Nov 2026 06:26:17 -0800 Subject: [PATCH 3/4] Clean up supported python versions (#1992) --- deps/test-requirements.txt | 12 +++--------- pyproject.toml | 4 ++-- tests/test_http_client.py | 6 +----- 3 files changed, 6 insertions(+), 16 deletions(-) diff --git a/deps/test-requirements.txt b/deps/test-requirements.txt index e8ab486b2..a09422ca6 100644 --- a/deps/test-requirements.txt +++ b/deps/test-requirements.txt @@ -1,17 +1,11 @@ # packages needed to run unit tests (including extra supported http libraries) -# version requirements: all supported versions (currently 3.6-3.12) +# version requirements: all supported versions (currently 3.9-3.14) -# This is the last version of httpx compatible with Python 3.6 -httpx == 0.22.0; python_version == "3.6" -httpx >= 0.24.1; python_version == "3.7" -httpx >= 0.27.0; python_version >= "3.8" -aiohttp == 3.8.6; python_version <= "3.7" -aiohttp == 3.10.11; python_version == "3.8" -aiohttp == 3.12.15; python_version >= "3.9" +httpx >= 0.27.0 +aiohttp == 3.12.15 anyio[trio] == 3.6.2; python_version < "3.13" anyio[trio] == 4.11.0; python_version >= "3.13" pytest-mock >= 2.0.0 -mock >= 4.0; python_version < "3.8" pytest-xdist >= 1.31.0 pytest >= 6.0.0,<9.0.0 diff --git a/pyproject.toml b/pyproject.toml index 60e87b3a8..1123ce641 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,12 +15,12 @@ classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Software Development :: Libraries :: Python Modules", diff --git a/tests/test_http_client.py b/tests/test_http_client.py index 153704ed8..016bfa176 100644 --- a/tests/test_http_client.py +++ b/tests/test_http_client.py @@ -1,7 +1,6 @@ import io import base64 import json -import sys import threading from typing import Any, Callable, Dict, List, Optional from unittest.mock import MagicMock, Mock, call, patch @@ -9,10 +8,7 @@ import pytest from typing_extensions import Type -if sys.version_info >= (3, 8): - from unittest.mock import AsyncMock -else: - from mock import AsyncMock +from unittest.mock import AsyncMock from contextlib import contextmanager From a970e4aa5d816e6a9618157d46e87e9bbd2c4896 Mon Sep 17 00:00:00 2001 From: mark-kogan-stripe Date: Tue, 17 Nov 2026 11:32:45 -0800 Subject: [PATCH 4/4] Add support for using httpx2 for async requests (#1997) * Replace httpx with httpx2 for async requests httpx, which backs HTTPXClient and the default async client, is no longer maintained, so it won't receive security fixes. httpx2 is its community-accepted continuation, maintained by Pydantic, and keeps mostly the same API. Two calls needed adjusting for httpx2: - The encoded body is sent as `content=`, since passing raw bodies as `data=` is deprecated and emits a warning on every request. - Proxies are configured through client-level `mounts`, since the per-request `proxies=` argument isn't accepted. Closes #1886 * Restore support for httpx, preferring httpx2 when both are installed in an environment * Add short integration test asserting that the request passes successfully through httpx and httpx2 * Make it clearer that httpx is not a blessed path * Convert timeout to in-use httpx/httpx2 library on the fly to avoid breaking * Add note relating to httpx deprecation --- .claude/CLAUDE.md | 2 +- ...16_markisaackogan_httpx2-support.change.md | 8 ++ ...an_use-standard-params-on-httpx2.change.md | 6 + README.md | 11 +- deps/test-requirements.txt | 7 +- stripe/_http_client.py | 130 ++++++++++++++---- tests/test_http_client.py | 84 +++++++++-- tests/test_integration.py | 48 ++++++- 8 files changed, 252 insertions(+), 44 deletions(-) create mode 100644 .hark/changes/2026-11-16_markisaackogan_httpx2-support.change.md create mode 100644 .hark/changes/2026-11-17_markisaackogan_use-standard-params-on-httpx2.change.md diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index b65b38505..b9e11f38e 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -28,7 +28,7 @@ ## Conventions -- Uses `requests` library by default for sync HTTP, `httpx` for async +- Uses `requests` library by default for sync HTTP, `httpx2` (falling back to `httpx`) for async - Type hints throughout - Virtual env managed in `.venv/`; `just` recipes handle setup automatically - Work is not complete until `just test`, `just lint` and `just typecheck` complete successfully. diff --git a/.hark/changes/2026-11-16_markisaackogan_httpx2-support.change.md b/.hark/changes/2026-11-16_markisaackogan_httpx2-support.change.md new file mode 100644 index 000000000..ae0d72ac6 --- /dev/null +++ b/.hark/changes/2026-11-16_markisaackogan_httpx2-support.change.md @@ -0,0 +1,8 @@ +--- +title: "Support httpx2 for async requests, falling back to httpx when httpx2 isn't installed" +semver_level: minor +pr_url: https://github.com/stripe/stripe-python/pull/1997 +github_issues_resolved: +- https://github.com/stripe/stripe-python/issues/1886 +--- +`HTTPXClient` and the default async client now use `httpx2` when it's installed and fall back to `httpx` otherwise. `httpx` support is deprecated and will be removed in the next major version; we recommend installing `httpx2` for async use. diff --git a/.hark/changes/2026-11-17_markisaackogan_use-standard-params-on-httpx2.change.md b/.hark/changes/2026-11-17_markisaackogan_use-standard-params-on-httpx2.change.md new file mode 100644 index 000000000..89852fa3b --- /dev/null +++ b/.hark/changes/2026-11-17_markisaackogan_use-standard-params-on-httpx2.change.md @@ -0,0 +1,6 @@ +--- +title: "Fix `HTTPXClient` raising a network error when a proxy is configured" +semver_level: patch +pr_url: https://github.com/stripe/stripe-python/pull/1997 +--- +`HTTPXClient` passed `proxies` on each request, which httpx doesn't accept. Proxies are now configured on the client instead. Request bodies are also now sent as `content=`, which avoids httpx's deprecation warning for `data=`. diff --git a/README.md b/README.md index c40ed3e96..6dd63449e 100644 --- a/README.md +++ b/README.md @@ -370,9 +370,12 @@ async for c in await stripe.Customer.list_async().auto_paging_iter(): There is no `.save_async` as `.save` is [deprecated since stripe-python v5](https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v5#deprecated). Please migrate to `.modify_async`. The default HTTP client uses `requests` for making synchronous requests but -`httpx` for making async requests. If you're migrating to async, we recommend -you to explicitly initialize your own http client and pass it to StripeClient -or set it as the global default. +`httpx2` for making async requests, falling back to `httpx` if `httpx2` isn't +installed (and to `aiohttp` if neither is). We recommend `pip install httpx2` +for async use, since `httpx` is no longer actively maintained. `httpx` support +is deprecated and will be removed in the next major version of stripe-python. +If you're migrating to async, we recommend you to explicitly initialize your own +http client and pass it to StripeClient or set it as the global default. If you don't already have a dependency on an async-compatible HTTP library, `pip install stripe[async]` will install one for you (new in `v13.0.1`). @@ -382,7 +385,7 @@ If you don't already have a dependency on an async-compatible HTTP library, `pip # make sure you don't unintentionally make a synchronous request. my_http_client = stripe.HTTPXClient() -# If you want to use httpx to make sync requests, you can disable this +# If you want to use httpx2 to make sync requests, you can disable this # behavior. my_http_client = stripe.HTTPXClient(allow_sync_methods=True) diff --git a/deps/test-requirements.txt b/deps/test-requirements.txt index a09422ca6..24fffcb55 100644 --- a/deps/test-requirements.txt +++ b/deps/test-requirements.txt @@ -1,10 +1,13 @@ # packages needed to run unit tests (including extra supported http libraries) # version requirements: all supported versions (currently 3.9-3.14) +httpx2 >= 2.0.0 +# fallback when httpx2 isn't installed +# TODO: (DEVSDK-3427) remove httpx in the next major version httpx >= 0.27.0 aiohttp == 3.12.15 -anyio[trio] == 3.6.2; python_version < "3.13" -anyio[trio] == 4.11.0; python_version >= "3.13" +# httpx2 requires anyio >= 4.10 since 2.9.0 +anyio[trio] == 4.10.0 pytest-mock >= 2.0.0 pytest-xdist >= 1.31.0 diff --git a/stripe/_http_client.py b/stripe/_http_client.py index f11f6c600..75f8d35bd 100644 --- a/stripe/_http_client.py +++ b/stripe/_http_client.py @@ -48,8 +48,10 @@ pass try: - from httpx import Timeout as HTTPXTimeout - from httpx import Client as HTTPXClientType + from httpx2 import Timeout as HTTPXTimeout + from httpx2 import Client as HTTPXClientType + from httpx2 import AsyncBaseTransport as HTTPXAsyncTransport + from httpx2 import BaseTransport as HTTPXSyncTransport except ImportError: pass @@ -1193,6 +1195,67 @@ def close(self): pass +def _get_httpx_async_mounts( + httpx: Any, + proxy: Optional[HTTPClient._Proxy], + verify: Union[ssl.SSLContext, bool], +) -> Optional[Dict[str, "HTTPXAsyncTransport"]]: + """ + Returns the `mounts` option that routes an `httpx.AsyncClient` (or the + `httpx2` equivalent) through `proxy`, or `None` when there's no proxy. + + httpx only accepts proxies at the client level, and needs a transport + mounted per URL scheme to use a different proxy for each one. + """ + if not proxy: + return None + + return { + f"{scheme}://": httpx.AsyncHTTPTransport( + proxy=proxy_url, verify=verify + ) + for scheme, proxy_url in proxy.items() + if proxy_url + } + + +def _get_httpx_sync_mounts( + httpx: Any, + proxy: Optional[HTTPClient._Proxy], + verify: Union[ssl.SSLContext, bool], +) -> Optional[Dict[str, "HTTPXSyncTransport"]]: + """ + The sync `Client` counterpart of `_get_httpx_async_mounts`, since sync + and async clients can't share transports. + """ + if not proxy: + return None + + return { + f"{scheme}://": httpx.HTTPTransport(proxy=proxy_url, verify=verify) + for scheme, proxy_url in proxy.items() + if proxy_url + } + + +# TODO: (DEVSDK-3427) No longer necessary in the next major version. +def _coerce_httpx_timeout(httpx_lib: Any, timeout: Any) -> Any: + """ + `httpx` and `httpx2` each define their own `Timeout` class and neither + recognizes the other's, so a `Timeout` from the library that isn't in use + is rebuilt as one from the library that is. + """ + if timeout is None or isinstance(timeout, (int, float, httpx_lib.Timeout)): + return timeout + + return httpx_lib.Timeout( + connect=timeout.connect, + read=timeout.read, + write=timeout.write, + pool=timeout.pool, + ) + + class HTTPXClient(HTTPClient): name = "httpx" @@ -1208,28 +1271,32 @@ def __init__( super(HTTPXClient, self).__init__(**kwargs) if _lib is None: - import httpx - - _lib = httpx - self.httpx = _lib + # TODO: (DEVSDK-3427) drop the httpx fallback in the next major version. + try: + import httpx2 as _lib + except ImportError: + import httpx as _lib + self.httpx: Any = _lib import anyio self.anyio = anyio - kwargs = {} + verify: Union[ssl.SSLContext, Literal[False]] = False if self._verify_ssl_certs: - kwargs["verify"] = ssl.create_default_context( - cafile=stripe.ca_bundle_path - ) - else: - kwargs["verify"] = False + verify = ssl.create_default_context(cafile=stripe.ca_bundle_path) - self._client_async = self.httpx.AsyncClient(**kwargs) + self._client_async = self.httpx.AsyncClient( + verify=verify, + mounts=_get_httpx_async_mounts(self.httpx, self._proxy, verify), + ) self._client = None if allow_sync_methods: - self._client = self.httpx.Client(**kwargs) - self._timeout = timeout + self._client = self.httpx.Client( + verify=verify, + mounts=_get_httpx_sync_mounts(self.httpx, self._proxy, verify), + ) + self._timeout = _coerce_httpx_timeout(self.httpx, timeout) def sleep_async(self, secs): return self.anyio.sleep(secs) @@ -1239,14 +1306,13 @@ def _get_request_args_kwargs( ): kwargs = {} - if self._proxy: - kwargs["proxies"] = self._proxy - if self._timeout: kwargs["timeout"] = self._timeout + # `post_data` is an already-encoded body, which httpx takes as + # `content`; passing it as `data` is deprecated. return [ (method, url), - {"headers": headers, "data": post_data or {}, **kwargs}, + {"headers": headers, "content": post_data or None, **kwargs}, ] def request( @@ -1498,9 +1564,9 @@ def __init__(self, **kwargs): def raise_async_client_import_error() -> Never: raise ImportError( ( - "Import httpx not found. To make async http requests," - "You must either install httpx or define your own" - "async http client by subclassing stripe.HTTPClient" + "Import httpx2 not found. To make async http requests, " + "you must either install httpx2 or define your own " + "async http client by subclassing stripe.HTTPClient " "and setting stripe.default_http_client to an instance of it." ) ) @@ -1521,7 +1587,7 @@ async def close_async(self): # --- Client resolution --- # Detect available HTTP libraries at module load time so the expensive imports -# (e.g. requests, httpx) happen during Python's init phase rather than when +# (e.g. requests, httpx2) happen during Python's init phase rather than when # StripeClient() is constructed. This matters in environments like AWS Lambda # where module loading has a generous timeout (10s) but handler invocation # does not (often 3s). @@ -1533,9 +1599,14 @@ async def close_async(self): # 4. urllib (stdlib fallback, basically always present) # # Async client precedence: -# 1. httpx + anyio (both required) -# 2. aiohttp -# 3. NoImportFoundAsyncClient (raises on use) +# 1. httpx2 + anyio (both required) +# 2. (deprecated, see note) httpx + anyio (both required) +# 3. aiohttp +# 4. NoImportFoundAsyncClient (raises on use) +# +# Note: httpx is no longer maintained, so we only fall back to it for users who +# haven't installed httpx2 yet. That fallback is deprecated and will be removed +# in the next major version (DEVSDK-3427). # # To add a new client: define the class above, then add it to the appropriate # cascade below. The resolved class is stored directly — new_default_http_client() @@ -1569,9 +1640,14 @@ def _resolve_sync_client(): def _resolve_async_client(): try: - import httpx # noqa: F401 import anyio # noqa: F401 + # TODO: (DEVSDK-3427) drop the httpx fallback in the next major version. + try: + import httpx2 # noqa: F401 + except ImportError: + import httpx # noqa: F401 + return HTTPXClient except ImportError: pass diff --git a/tests/test_http_client.py b/tests/test_http_client.py index 016bfa176..959d72104 100644 --- a/tests/test_http_client.py +++ b/tests/test_http_client.py @@ -1,3 +1,4 @@ +import importlib import io import base64 import json @@ -40,7 +41,15 @@ def mocked_request_lib(): SUPPORTED_LIBS = frozenset( - ("google.appengine.api", "requests", "pycurl", "httpx", "aiohttp", "anyio") + ( + "google.appengine.api", + "requests", + "pycurl", + "httpx2", + "httpx", # TODO: (DEVSDK-3427) drop in the next major version. + "aiohttp", + "anyio", + ) ) @@ -104,10 +113,15 @@ def test_default_httpclient_from_imports( @pytest.mark.parametrize( ["available_libs", "expected"], [ - # needs both httpx and anyio + # TODO: (DEVSDK-3427) delete the httpx-only cases in the next major version. + # needs both httpx2 (or httpx) and anyio + [["httpx2"], NoImportFoundAsyncClient], [["httpx"], NoImportFoundAsyncClient], [["anyio"], NoImportFoundAsyncClient], + [["httpx2", "anyio"], HTTPXClient], [["httpx", "anyio"], HTTPXClient], + [["httpx2", "httpx", "anyio"], HTTPXClient], + [["httpx", "anyio", "aiohttp"], HTTPXClient], # having only one required lib means we proceed [["anyio", "aiohttp"], AIOHTTPClient], [["aiohttp"], AIOHTTPClient], @@ -1420,7 +1434,7 @@ class TestHTTPXClient(ClientTestBase): @pytest.fixture def request_mock(self, mocked_request_lib): - # Set up the httpx library mock structure + # Set up the httpx2 library mock structure async_client_instance = Mock() sync_client_instance = Mock() @@ -1492,9 +1506,8 @@ def _check_call( args = (method, url) kwargs = { "headers": headers, - "data": post_data or {}, + "content": post_data or None, "timeout": timeout, - "proxies": {"http": "http://slap/", "https": "http://slap/"}, } if is_streaming: @@ -1521,9 +1534,8 @@ def _check_call_async( args = (method, url) kwargs = { "headers": headers, - "data": post_data, + "content": post_data or None, "timeout": timeout, - "proxies": {"http": "http://slap/", "https": "http://slap/"}, } if is_streaming: @@ -1828,6 +1840,62 @@ def test_timeout_async(self): pass +class TestHTTPXClientTimeout: + @pytest.fixture(params=["httpx2", "httpx"]) + def lib(self, request): + return importlib.import_module(request.param) + + @pytest.fixture + def other_lib(self, lib): + name = "httpx" if lib.__name__ == "httpx2" else "httpx2" + return importlib.import_module(name) + + @pytest.mark.parametrize("timeout", [None, 5, 2.5, 80]) + def test_numeric_timeout_is_unchanged(self, lib, timeout): + client = HTTPXClient(timeout=timeout, _lib=lib) + + assert client._timeout == timeout + + def test_timeout_from_same_lib_is_unchanged(self, lib): + timeout = lib.Timeout(30.0, connect=5.0) + + client = HTTPXClient(timeout=timeout, _lib=lib) + + assert client._timeout is timeout + + def test_timeout_from_other_lib_is_converted(self, lib, other_lib): + timeout = other_lib.Timeout(30.0, connect=5.0, read=10.0) + + client = HTTPXClient(timeout=timeout, _lib=lib) + + assert isinstance(client._timeout, lib.Timeout) + assert client._timeout == lib.Timeout(30.0, connect=5.0, read=10.0) + + @pytest.mark.anyio + async def test_converted_timeout_is_accepted_by_request( + self, lib, other_lib + ): + seen = {} + + def handler(request): + seen.update(request.extensions["timeout"]) + return lib.Response(200, request=request, content=b"{}") + + client = HTTPXClient( + timeout=other_lib.Timeout(5.0, read=1.0), _lib=lib + ) + client._client_async = lib.AsyncClient( + transport=lib.MockTransport(handler) + ) + + _, status, _ = await client.request_async( + "get", "https://api.stripe.com/", {}, None + ) + + assert status == 200 + assert seen == {"connect": 5.0, "read": 1.0, "write": 5.0, "pool": 5.0} + + class TestAIOHTTPClient(ClientTestBase): REQUEST_CLIENT: Type[_http_client.AIOHTTPClient] = ( _http_client.AIOHTTPClient @@ -2239,7 +2307,7 @@ class TestLiveHTTPClients: @pytest.mark.anyio async def test_httpx_request_async_https(self): """ - Test to ensure that httpx https calls succeed by making a live test call + Test to ensure that httpx2 https calls succeed by making a live test call to the public stripe API. """ method = "get" diff --git a/tests/test_integration.py b/tests/test_integration.py index 9572ff127..05d3b8534 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -1,3 +1,4 @@ +import importlib import platform from threading import Thread, Lock import json @@ -5,7 +6,7 @@ import warnings import time -import httpx +import httpx2 import aiohttp import sys import stripe @@ -227,6 +228,49 @@ class MockServerRequestHandler(MyTestHandler): assert MockServerRequestHandler.num_requests == 1 + # TODO: (DEVSDK-3427) drop the httpx param in the next major version. + @pytest.fixture(params=["httpx2", "httpx"]) + def httpx_lib(self, request): + return importlib.import_module(request.param) + + def test_hits_proxy_through_httpx_client(self, httpx_lib): + class MockServerRequestHandler(MyTestHandler): + pass + + self.setup_mock_server(MockServerRequestHandler) + + client = stripe.StripeClient( + "sk_test_123", + http_client=stripe.HTTPXClient( + proxy=f"http://{MOCK_HOST}:{self.mock_server_port}", + allow_sync_methods=True, + _lib=httpx_lib, + ), + base_addresses={"api": f"http://{MOCK_HOST}:12111"}, + ) + client.balance.retrieve() + + assert MockServerRequestHandler.num_requests == 1 + + @pytest.mark.anyio + async def test_hits_proxy_through_httpx_client_async(self, httpx_lib): + class MockServerRequestHandler(MyTestHandler): + pass + + self.setup_mock_server(MockServerRequestHandler) + + client = stripe.StripeClient( + "sk_test_123", + http_client=stripe.HTTPXClient( + proxy=f"http://{MOCK_HOST}:{self.mock_server_port}", + _lib=httpx_lib, + ), + base_addresses={"api": f"http://{MOCK_HOST}:12111"}, + ) + await client.balance.retrieve_async() + + assert MockServerRequestHandler.num_requests == 1 + def test_passes_client_telemetry_when_enabled(self): class MockServerRequestHandler(MyTestHandler): def do_request(self, req_num): @@ -420,7 +464,7 @@ def do_request(self, n): expected_message = "" if isinstance(hc, stripe.HTTPXClient): - hc._timeout = httpx.Timeout(None, read=0.01) + hc._timeout = httpx2.Timeout(None, read=0.01) expected_message = "A ReadTimeout was raised" elif isinstance(hc, stripe.AIOHTTPClient): hc._timeout = aiohttp.ClientTimeout(sock_read=0.01)