diff --git a/README.md b/README.md index 2112462f..e014848e 100644 --- a/README.md +++ b/README.md @@ -33,11 +33,9 @@ import os from sumup import Sumup -client = Sumup(api_key="sup_sk_MvxmLOl0...") - -# Get merchant profile -merchant = client.merchants.get(merchant_code=os.environ["SUMUP_MERCHANT_CODE"]) -print(f"Merchant: {merchant.merchant_code}") +with Sumup(api_key="sup_sk_MvxmLOl0...") as client: + merchant = client.merchants.get(merchant_code=os.environ["SUMUP_MERCHANT_CODE"]) + print(f"Merchant: {merchant.merchant_code}") ``` ### Async Client @@ -50,16 +48,18 @@ from sumup import AsyncSumup async def main(): - client = AsyncSumup(api_key="sup_sk_MvxmLOl0...") - - # Get merchant profile - merchant = await client.merchants.get(merchant_code=os.environ["SUMUP_MERCHANT_CODE"]) - print(f"Merchant: {merchant.merchant_code}") + async with AsyncSumup(api_key="sup_sk_MvxmLOl0...") as client: + merchant = await client.merchants.get(merchant_code=os.environ["SUMUP_MERCHANT_CODE"]) + print(f"Merchant: {merchant.merchant_code}") asyncio.run(main()) ``` +Context managers close the client when the block exits, including when an exception occurs. +For long-running applications, reuse a client and call `client.close()` or +`await client.aclose()` during shutdown. + ### Creating a Checkout ```python diff --git a/codegen/templates/client.py.tmpl b/codegen/templates/client.py.tmpl index 550ae558..39e5a4ff 100644 --- a/codegen/templates/client.py.tmpl +++ b/codegen/templates/client.py.tmpl @@ -1,7 +1,9 @@ # Code generated by `py-sdk-gen`. DO NOT EDIT. import os +from types import TracebackType import typing import httpx +from typing_extensions import Self from ._service import Resource, AsyncResource, runtime_headers if typing.TYPE_CHECKING: @@ -42,6 +44,23 @@ class Sumup(Resource): }, )) + def close(self) -> None: + """Close the underlying HTTP client and release its connections.""" + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + """Release connections without suppressing exceptions from the block.""" + self._client.__exit__(exc_type, exc_value, traceback) + def events_handler( self, secret: str, @@ -150,6 +169,23 @@ class AsyncSumup(AsyncResource): }, )) + async def aclose(self) -> None: + """Close the underlying HTTP client and release its connections.""" + await self._client.aclose() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + """Release connections without suppressing exceptions from the block.""" + await self._client.__aexit__(exc_type, exc_value, traceback) + def events_handler( self, secret: str, diff --git a/sumup/_client.py b/sumup/_client.py index 4062972c..f174953a 100644 --- a/sumup/_client.py +++ b/sumup/_client.py @@ -1,8 +1,10 @@ # Code generated by `py-sdk-gen`. DO NOT EDIT. import os import typing +from types import TracebackType import httpx +from typing_extensions import Self from ._service import AsyncResource, Resource, runtime_headers @@ -60,6 +62,23 @@ def __init__( ) ) + def close(self) -> None: + """Close the underlying HTTP client and release its connections.""" + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + """Release connections without suppressing exceptions from the block.""" + self._client.__exit__(exc_type, exc_value, traceback) + def events_handler( self, secret: str, @@ -233,6 +252,23 @@ def __init__( ) ) + async def aclose(self) -> None: + """Close the underlying HTTP client and release its connections.""" + await self._client.aclose() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + """Release connections without suppressing exceptions from the block.""" + await self._client.__aexit__(exc_type, exc_value, traceback) + def events_handler( self, secret: str, diff --git a/tests/test_client_lifecycle.py b/tests/test_client_lifecycle.py new file mode 100644 index 00000000..b3b0dbad --- /dev/null +++ b/tests/test_client_lifecycle.py @@ -0,0 +1,76 @@ +import asyncio + +import httpx +import pytest + +from sumup import AsyncSumup, Sumup + + +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +def test_explicit_close(use_async): + if use_async: + + async def run(): + client = AsyncSumup(api_key="test") + await client.aclose() + await client.aclose() + assert client._client.is_closed + + asyncio.run(run()) + else: + client = Sumup(api_key="test") + client.close() + client.close() + assert client._client.is_closed + + +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("raise_error", [False, True], ids=["success", "exception"]) +def test_context_manager_closes_transport(use_async, raise_error, monkeypatch): + error = ValueError("processing failed") + + def handler(request): + return httpx.Response(200, json={"items": []}) + + # Inject a transport so requests and cleanup can be tested without network access. + transport = httpx.MockTransport(handler) + if use_async: + http_client = httpx.AsyncClient(base_url="https://api.sumup.test", transport=transport) + monkeypatch.setattr("sumup._client.httpx.AsyncClient", lambda **kwargs: http_client) + + async def run(): + client = AsyncSumup(api_key="test") + try: + async with client as entered: + assert entered is client + assert not http_client.is_closed + page = await client.transactions.list("merchant-123") + assert page.items == [] + if raise_error: + raise error + except ValueError as caught: + assert raise_error + assert caught is error + else: + assert not raise_error + assert http_client.is_closed + + asyncio.run(run()) + else: + http_client = httpx.Client(base_url="https://api.sumup.test", transport=transport) + monkeypatch.setattr("sumup._client.httpx.Client", lambda **kwargs: http_client) + client = Sumup(api_key="test") + try: + with client as entered: + assert entered is client + assert not http_client.is_closed + page = client.transactions.list("merchant-123") + assert page.items == [] + if raise_error: + raise error + except ValueError as caught: + assert raise_error + assert caught is error + else: + assert not raise_error + assert http_client.is_closed