Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
36 changes: 36 additions & 0 deletions codegen/templates/client.py.tmpl
Original file line number Diff line number Diff line change
@@ -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:
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
36 changes: 36 additions & 0 deletions sumup/_client.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
76 changes: 76 additions & 0 deletions tests/test_client_lifecycle.py
Original file line number Diff line number Diff line change
@@ -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
Loading