From 9029621eb927cbdc2143bf30596877cf5bf94b93 Mon Sep 17 00:00:00 2001 From: Steve Chaloner Date: Mon, 16 Nov 2026 20:40:08 +0100 Subject: [PATCH] Send an Idempotency-Key with every POST, PUT and DELETE The key is reused on 429 and 409 IDEMPOTENCY_KEY_IN_USE retries and is exposed on SeatsioException, so a caller can retry an operation with the same key via Client.with_idempotency_key, which only accepts v4 UUIDs. Co-Authored-By: Claude Opus 5.5 --- README.md | 26 ++++- seatsio/client.py | 22 +++- seatsio/exceptions.py | 16 ++- seatsio/httpClient.py | 114 ++++++++++++++++++--- tests/httpbin.py | 8 ++ tests/testErrorHandling.py | 5 +- tests/testExponentialBackoff.py | 27 ++--- tests/testIdempotencyKey.py | 175 ++++++++++++++++++++++++++++++++ 8 files changed, 357 insertions(+), 36 deletions(-) create mode 100644 tests/httpbin.py create mode 100644 tests/testIdempotencyKey.py diff --git a/README.md b/README.md index 90ab733..3b31e01 100644 --- a/README.md +++ b/README.md @@ -187,9 +187,29 @@ When an API call results in a 4xx or 5xx error (e.g. when a chart could not be f This exception contains a message string describing what went wrong, and also two other properties: -- `Errors`: a list of errors (containing a code and a message) that the server returned. In most cases, this list will contain only one element. -- `RequestId`: the identifier of the request you made. Please mention this to us when you have questions, as it will make debugging easier. -- +- `errors`: a list of errors (containing a code and a message) that the server returned. In most cases, this list will contain only one element. +- `requestId`: the identifier of the request you made. Please mention this to us when you have questions, as it will make debugging easier. + +## Idempotency + +**NOTE**: Idempotency is currently in a soft launch: it is enabled per company and not yet publicly available. Contact seats.io support to have it enabled for your company. + +Every `POST`, `PUT` and `DELETE` request is sent with an `Idempotency-Key` header (a v4 UUID, generated by the client). If idempotency is enabled for your company, the server executes a request with a given key only once, and replays the original response when it receives the same request again. If it isn't enabled, the server ignores the key, and retrying a request can execute it a second time. + +If a request fails and you can't tell whether it was processed (e.g. the connection dropped before you received the response), the exception carries the key that was used, so you can retry the operation with the same key: + +```python +try: + client.events.create(chart_key) +except SeatsioException as e: + # only retry when the outcome is unknown (a connection error, a timeout or a 5xx); retrying a 4xx can never succeed + client.with_idempotency_key(e.idempotency_key).events.create(chart_key) +``` + +The retried request must be identical to the original one. All requests made with the client returned by `with_idempotency_key` send the same key, so use it for one operation only. You can also supply your own key (e.g. `str(uuid.uuid4())`); it must be a v4 UUID, otherwise `with_idempotency_key` raises a `ValueError`. + +The client reuses the key when it retries a request after a `429`, and also when the server answers `409` because an earlier request with the same key is still being processed. + ## Rate limiting - exponential backoff This library supports [exponential backoff](https://en.wikipedia.org/wiki/Exponential_backoff). diff --git a/seatsio/client.py b/seatsio/client.py index 781990a..1f54c82 100644 --- a/seatsio/client.py +++ b/seatsio/client.py @@ -10,10 +10,20 @@ class Client: + IDEMPOTENCY_KEY_HEADER = "Idempotency-Key" + def __init__(self, region, secret_key, workspace_key=None, max_retries=5): - base_url = region.url - self.base_url = base_url - self.http_client = HttpClient(base_url, secret_key, workspace_key, max_retries) + self.__init_with_http_client(HttpClient(region.url, secret_key, workspace_key, max_retries)) + + @classmethod + def _from_http_client(cls, http_client): + client = cls.__new__(cls) + client.__init_with_http_client(http_client) + return client + + def __init_with_http_client(self, http_client): + self.http_client = http_client + self.base_url = http_client.base_url self.charts = ChartsClient(self.http_client) self.events = EventsClient(self.http_client) self.seasons = SeasonsClient(self.http_client, self) @@ -22,3 +32,9 @@ def __init__(self, region, secret_key, workspace_key=None, max_retries=5): self.usage_reports = UsageReports(self.http_client) self.event_log = EventLogClient(self.http_client) self.ticket_buyers = TicketBuyersClient(self.http_client) + + def with_idempotency_key(self, idempotency_key): + return Client._from_http_client(self.http_client.with_idempotency_key(idempotency_key)) + + def withIdempotencyKey(self, idempotency_key): + return self.with_idempotency_key(idempotency_key) diff --git a/seatsio/exceptions.py b/seatsio/exceptions.py index 46d11ab..586fd6f 100644 --- a/seatsio/exceptions.py +++ b/seatsio/exceptions.py @@ -1,6 +1,18 @@ class SeatsioException(Exception): def __init__(self, request, response=None, cause=None): + if isinstance(request, str): + self.errors = None + self.requestId = None + self.cause = cause + self.message = request + self.idempotency_key = None + self.idempotencyKey = None + super(SeatsioException, self).__init__(self.message) + return + + self.idempotency_key = getattr(request, 'idempotency_key', None) + self.idempotencyKey = self.idempotency_key if (response is not None) and ("application/json" in response.headers.get("content-type", "")): body = response.json() self.errors = body["errors"] @@ -12,7 +24,9 @@ def __init__(self, request, response=None, cause=None): self.errors = None self.requestId = None self.cause = cause - self.message = "Error while executing " + request.http_method + " " + request.url + http_method = getattr(request, 'http_method', '') + url = getattr(request, 'url', '') + self.message = f"Error while executing {http_method} {url}".strip() super(SeatsioException, self).__init__(self.message) @staticmethod diff --git a/seatsio/httpClient.py b/seatsio/httpClient.py index 16e2809..c6b5709 100644 --- a/seatsio/httpClient.py +++ b/seatsio/httpClient.py @@ -1,4 +1,6 @@ +import re import time +import uuid from urllib.parse import quote, urlencode import jsonpickle @@ -7,32 +9,45 @@ from seatsio.exceptions import SeatsioException, RateLimitExceededException +UUID_V4 = re.compile(r'\A[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\Z', re.IGNORECASE) + + def handle_error(request, response): raise SeatsioException.from_response(request, response) class HttpClient: - def __init__(self, base_url, secret_key, workspace_key, max_retries, timeout=10): + def __init__(self, base_url, secret_key, workspace_key, max_retries, timeout=10, idempotency_key=None): self.base_url = base_url self.secret_key = secret_key self.workspace_key = workspace_key self.max_retries = max_retries self.timeout = timeout + self.idempotency_key = idempotency_key + + def with_idempotency_key(self, idempotency_key): + if not isinstance(idempotency_key, str) or not UUID_V4.match(idempotency_key): + raise ValueError("idempotency key %r is not a v4 UUID" % (idempotency_key,)) + return HttpClient(self.base_url, self.secret_key, self.workspace_key, self.max_retries, self.timeout, idempotency_key) + + def withIdempotencyKey(self, idempotency_key): + return self.with_idempotency_key(idempotency_key) def url(self, relative_url, query_params=None, **path_params): if query_params is None: query_params = {} return ApiResource(self.max_retries, self.secret_key, self.workspace_key, self.base_url, relative_url, - query_params, self.timeout, **path_params) + query_params, self.timeout, self.idempotency_key, **path_params) class ApiResource: - def __init__(self, max_retries, secret_key, workspace_key, base_url, relative_url, query_params, timeout, **path_params): + def __init__(self, max_retries, secret_key, workspace_key, base_url, relative_url, query_params, timeout, idempotency_key=None, **path_params): self.max_retries = max_retries self.url = self.__create_full_url(base_url, relative_url, query_params, **path_params) self.secret_key = secret_key self.workspace_key = workspace_key self.timeout = timeout + self.idempotency_key = idempotency_key def __create_full_url(self, base_url, relative_url, query_params, **path_params): for key in path_params: @@ -53,18 +68,24 @@ def get_as(self, cls): def post(self, body=None): if body is None: - return POST(self.max_retries, self.url, self.secret_key, self.workspace_key, self.timeout).execute() + return POST(self.max_retries, self.url, self.secret_key, self.workspace_key, self.timeout, self.idempotency_key).execute() else: - return POST(self.max_retries, self.url, self.secret_key, self.workspace_key, self.timeout).body(body).execute() + return POST(self.max_retries, self.url, self.secret_key, self.workspace_key, self.timeout, self.idempotency_key).body(body).execute() def post_empty_and_return(self, cls): return cls(self.post().json()) def delete(self, body=None): if body is None: - return DELETE(self.max_retries, self.url, self.secret_key, self.workspace_key, self.timeout).execute() + return DELETE(self.max_retries, self.url, self.secret_key, self.workspace_key, self.timeout, self.idempotency_key).execute() else: - return DELETE(self.max_retries, self.url, self.secret_key, self.workspace_key, self.timeout).body(body).execute() + return DELETE(self.max_retries, self.url, self.secret_key, self.workspace_key, self.timeout, self.idempotency_key).body(body).execute() + + def put(self, body=None): + if body is None: + return PUT(self.max_retries, self.url, self.secret_key, self.workspace_key, self.timeout, self.idempotency_key).execute() + else: + return PUT(self.max_retries, self.url, self.secret_key, self.workspace_key, self.timeout, self.idempotency_key).body(body).execute() class GET: @@ -76,6 +97,7 @@ def __init__(self, max_retries, url, secret_key, workspace_key, timeout): self.secret_key = secret_key self.workspace_key = workspace_key self.timeout = timeout + self.idempotency_key = None def execute(self): response = retry(self.try_execute, self.max_retries) @@ -100,7 +122,7 @@ def try_execute(self): class POST: - def __init__(self, max_retries, url, secret_key, workspace_key, timeout): + def __init__(self, max_retries, url, secret_key, workspace_key, timeout, idempotency_key=None): self.http_method = "POST" self.max_retries = max_retries self.url = url @@ -108,6 +130,7 @@ def __init__(self, max_retries, url, secret_key, workspace_key, timeout): self.workspace_key = workspace_key self.timeout = timeout self.body_object = None + self.idempotency_key = idempotency_key if idempotency_key is not None else str(uuid.uuid4()) def body(self, body): self.body_object = body @@ -126,7 +149,7 @@ def try_execute(self): return requests.post( url=self.url, auth=(self.secret_key, ''), - headers=(common_headers(self.workspace_key)), + headers=(common_headers(self.workspace_key, self.idempotency_key)), data=json, timeout=self.timeout ) @@ -136,7 +159,7 @@ def try_execute(self): class DELETE: - def __init__(self, max_retries, url, secret_key, workspace_key, timeout): + def __init__(self, max_retries, url, secret_key, workspace_key, timeout, idempotency_key=None): self.http_method = "DELETE" self.max_retries = max_retries self.url = url @@ -144,6 +167,7 @@ def __init__(self, max_retries, url, secret_key, workspace_key, timeout): self.workspace_key = workspace_key self.timeout = timeout self.body_object = None + self.idempotency_key = idempotency_key if idempotency_key is not None else str(uuid.uuid4()) def body(self, body): self.body_object = body @@ -162,7 +186,44 @@ def try_execute(self): return requests.delete( self.url, auth=(self.secret_key, ''), - headers=(common_headers(self.workspace_key)), + headers=(common_headers(self.workspace_key, self.idempotency_key)), + data=json, + timeout=self.timeout + ) + except Exception as cause: + raise SeatsioException(self, cause=cause) + + +class PUT: + + def __init__(self, max_retries, url, secret_key, workspace_key, timeout, idempotency_key=None): + self.http_method = "PUT" + self.max_retries = max_retries + self.url = url + self.secret_key = secret_key + self.workspace_key = workspace_key + self.timeout = timeout + self.body_object = None + self.idempotency_key = idempotency_key if idempotency_key is not None else str(uuid.uuid4()) + + def body(self, body): + self.body_object = body + return self + + def execute(self): + response = retry(self.try_execute, self.max_retries) + if response.status_code >= 400: + handle_error(self, response) + else: + return response + + def try_execute(self): + try: + json = jsonpickle.encode(self.body_object, unpicklable=False) + return requests.put( + self.url, + auth=(self.secret_key, ''), + headers=(common_headers(self.workspace_key, self.idempotency_key)), data=json, timeout=self.timeout ) @@ -170,20 +231,45 @@ def try_execute(self): raise SeatsioException(self, cause=cause) -def common_headers(workspace_key): - return { +def common_headers(workspace_key, idempotency_key=None): + headers = { 'X-Workspace-Key': str(workspace_key) if workspace_key else None, 'X-Client-Lib': 'python' } + if idempotency_key: + headers['Idempotency-Key'] = idempotency_key + return headers def retry(fn, max_retries): retry_count = 0 while True: response = fn() - if response.status_code != 429 or retry_count >= max_retries: + if not is_retryable(response) or retry_count >= max_retries: return response else: wait_time = (2 ** (retry_count + 2)) / 10.0 time.sleep(wait_time) retry_count += 1 + + +def is_retryable(response): + if response.status_code == 429: + return True + if response.status_code == 409: + codes = api_error_codes(response) + return len(codes) > 0 and codes[0] == 'IDEMPOTENCY_KEY_IN_USE' + return False + + +def api_error_codes(response): + if "application/json" not in response.headers.get("content-type", ""): + return [] + try: + body = response.json() + except ValueError: + return [] + errors = body.get("errors") if isinstance(body, dict) else None + if not isinstance(errors, list): + return [] + return [error["code"] for error in errors if isinstance(error, dict) and "code" in error] diff --git a/tests/httpbin.py b/tests/httpbin.py new file mode 100644 index 0000000..75b07c3 --- /dev/null +++ b/tests/httpbin.py @@ -0,0 +1,8 @@ +import os + +DEFAULT_URL = "https://httpbingo.org" + + +def httpbin_url(path=""): + base = os.environ.get("HTTPBIN_URL", DEFAULT_URL) + return base + path diff --git a/tests/testErrorHandling.py b/tests/testErrorHandling.py index 6945f1b..bc1ef12 100644 --- a/tests/testErrorHandling.py +++ b/tests/testErrorHandling.py @@ -30,10 +30,11 @@ def test_weird_error(self): def test_timeout_raises_seatsio_exception(self): from seatsio.httpClient import HttpClient + from tests.httpbin import httpbin_url try: - client = HttpClient("https://httpbingo.org", "aSecretKey", None, 0, timeout=0.1) + client = HttpClient(httpbin_url(), "aSecretKey", None, 0, timeout=0.1) client.url("/delay/1").get() self.fail("expected exception") except SeatsioException as e: - assert_that(e.message).is_equal_to("Error while executing GET https://httpbingo.org/delay/1") + assert_that(e.message).is_equal_to("Error while executing GET " + httpbin_url("/delay/1")) assert_that(e.cause).is_not_none() diff --git a/tests/testExponentialBackoff.py b/tests/testExponentialBackoff.py index 5595b8d..a831f30 100644 --- a/tests/testExponentialBackoff.py +++ b/tests/testExponentialBackoff.py @@ -1,70 +1,71 @@ import time +import unittest from seatsio.exceptions import SeatsioException, RateLimitExceededException from seatsio.httpClient import HttpClient -from tests.seatsioClientTest import SeatsioClientTest +from tests.httpbin import httpbin_url from tests.util.asserts import assert_that -class ExponentialBackoffTest(SeatsioClientTest): +class ExponentialBackoffTest(unittest.TestCase): def test_aborts_eventually_if_server_keeps_returning_429_get(self): start = time.time() try: - client = HttpClient("https://httpbingo.org", "aSecretKey", None, 5) + client = HttpClient(httpbin_url(), "aSecretKey", None, 5) client.url("/status/429").get() raise Exception("Should have failed") except RateLimitExceededException as e: - assert_that(e.message).is_equal_to("Error while executing GET https://httpbingo.org/status/429") + assert_that(e.message).is_equal_to("Error while executing GET " + httpbin_url("/status/429")) wait_time = int(time.time() - start) assert_that(wait_time).is_between(10, 20) def test_aborts_eventually_if_server_keeps_returning_429_post(self): start = time.time() try: - client = HttpClient("https://httpbingo.org", "aSecretKey", None, 5) + client = HttpClient(httpbin_url(), "aSecretKey", None, 5) client.url("/status/429").post() raise Exception("Should have failed") except RateLimitExceededException as e: - assert_that(e.message).is_equal_to("Error while executing POST https://httpbingo.org/status/429") + assert_that(e.message).is_equal_to("Error while executing POST " + httpbin_url("/status/429")) wait_time = int(time.time() - start) assert_that(wait_time).is_between(10, 20) def test_aborts_eventually_if_server_keeps_returning_429_delete(self): start = time.time() try: - client = HttpClient("https://httpbingo.org", "aSecretKey", None, 5) + client = HttpClient(httpbin_url(), "aSecretKey", None, 5) client.url("/status/429").delete() raise Exception("Should have failed") except RateLimitExceededException as e: - assert_that(e.message).is_equal_to("Error while executing DELETE https://httpbingo.org/status/429") + assert_that(e.message).is_equal_to("Error while executing DELETE " + httpbin_url("/status/429")) wait_time = int(time.time() - start) assert_that(wait_time).is_between(10, 20) def test_aborts_directly_if_server_returns_other_error_than_429(self): start = time.time() try: - client = HttpClient("https://httpbingo.org", "aSecretKey", None, 5) + client = HttpClient(httpbin_url(), "aSecretKey", None, 5) client.url("/status/400").get() raise Exception("Should have failed") except SeatsioException as e: - assert_that(e.message).is_equal_to("Error while executing GET https://httpbingo.org/status/400") + assert_that(e.message).is_equal_to("Error while executing GET " + httpbin_url("/status/400")) wait_time = int(time.time() - start) assert_that(wait_time).is_between(0, 5) def test_aborts_directly_if_server_returns_429_but_max_retries_0(self): start = time.time() try: - client = HttpClient("https://httpbingo.org", "aSecretKey", None, 0) + client = HttpClient(httpbin_url(), "aSecretKey", None, 0) client.url("/status/429").get() raise Exception("Should have failed") except RateLimitExceededException as e: - assert_that(e.message).is_equal_to("Error while executing GET https://httpbingo.org/status/429") + assert_that(e.message).is_equal_to("Error while executing GET " + httpbin_url("/status/429")) wait_time = int(time.time() - start) assert_that(wait_time).is_between(0, 5) def test_returns_successfully_when_server_sends_429_and_then_successful_response(self): - client = HttpClient("https://httpbingo.org", "aSecretKey", None, 5) + client = HttpClient(httpbin_url(), "aSecretKey", None, 5) i = 0 while i < 20: diff --git a/tests/testIdempotencyKey.py b/tests/testIdempotencyKey.py new file mode 100644 index 0000000..21c8e0a --- /dev/null +++ b/tests/testIdempotencyKey.py @@ -0,0 +1,175 @@ +import contextlib +import unittest +import unittest.mock +import uuid +import requests + +from seatsio import Client, Region +from seatsio.exceptions import SeatsioException, RateLimitExceededException +from seatsio.httpClient import HttpClient +from tests.httpbin import httpbin_url +from tests.util.asserts import assert_that + + +class IdempotencyKeyTest(unittest.TestCase): + + def test_posts_get_an_idempotency_key(self): + client = HttpClient(httpbin_url(), "secretKey", None, 5) + response = client.url("/anything").post("{}") + key = self.sent_idempotency_key(response) + + assert_that(uuid.UUID(key).version).is_equal_to(4) + + def test_deletes_get_an_idempotency_key(self): + client = HttpClient(httpbin_url(), "secretKey", None, 5) + response = client.url("/anything").delete() + key = self.sent_idempotency_key(response) + + assert_that(uuid.UUID(key).version).is_equal_to(4) + + def test_puts_get_an_idempotency_key(self): + client = HttpClient(httpbin_url(), "secretKey", None, 5) + response = client.url("/anything").put("{}") + key = self.sent_idempotency_key(response) + + assert_that(uuid.UUID(key).version).is_equal_to(4) + + def test_gets_do_not_get_an_idempotency_key(self): + client = HttpClient(httpbin_url(), "secretKey", None, 5) + response = client.url("/anything").get() + + assert_that("Idempotency-Key" in response.get("headers", {})).is_false() + + def test_each_request_gets_its_own_key(self): + client = HttpClient(httpbin_url(), "secretKey", None, 5) + + first = self.sent_idempotency_key(client.url("/anything").post("{}")) + second = self.sent_idempotency_key(client.url("/anything").post("{}")) + + assert_that(first).is_not_equal_to(second) + + def test_failed_requests_expose_their_idempotency_key(self): + with self.spy_on_post() as sent_keys: + try: + HttpClient(httpbin_url(), "secretKey", None, 5).url("/status/500").post("{}") + self.fail("expected exception") + except SeatsioException as e: + assert_that(sent_keys).has_size(1) + assert_that(e.idempotency_key).is_equal_to(sent_keys[0]) + assert_that(e.idempotencyKey).is_equal_to(sent_keys[0]) + + def test_connection_failures_expose_their_idempotency_key(self): + with self.spy_on_post() as sent_keys: + try: + HttpClient("http://localhost:1", "secretKey", None, 5).url("/anything").post("{}") + self.fail("expected exception") + except SeatsioException as e: + assert_that(sent_keys).has_size(1) + assert_that(e.idempotency_key).is_equal_to(sent_keys[0]) + assert_that(e.idempotencyKey).is_equal_to(sent_keys[0]) + + def test_rejects_idempotency_keys_that_are_not_v4_uuids(self): + for key in ["", "not-a-uuid", str(uuid.uuid1()), uuid.uuid4(), None]: + with self.assertRaises(ValueError): + HttpClient(httpbin_url(), "secretKey", None, 5).with_idempotency_key(key) + with self.assertRaises(ValueError): + Client(Region(httpbin_url()), "secretKey").with_idempotency_key(key) + + def test_accepts_uppercase_v4_uuids(self): + key = str(uuid.uuid4()).upper() + client = HttpClient(httpbin_url(), "secretKey", None, 5).with_idempotency_key(key) + + assert_that(self.sent_idempotency_key(client.url("/anything").post("{}"))).is_equal_to(key) + + def test_retries_409_idempotency_key_in_use_with_the_same_key(self): + responses = [self.json_response(409, "IDEMPOTENCY_KEY_IN_USE"), self.json_response(200)] + with unittest.mock.patch("requests.post", side_effect=responses) as post, \ + unittest.mock.patch("time.sleep"): + response = HttpClient(httpbin_url(), "secretKey", None, 5).url("/anything").post("{}") + + assert_that(response.status_code).is_equal_to(200) + assert_that(post.call_count).is_equal_to(2) + keys = [call.kwargs["headers"]["Idempotency-Key"] for call in post.call_args_list] + assert_that(keys[0]).is_equal_to(keys[1]) + + def test_does_not_retry_other_409s(self): + responses = [self.json_response(409, "SOMETHING_ELSE"), self.json_response(200)] + with unittest.mock.patch("requests.post", side_effect=responses) as post, \ + unittest.mock.patch("time.sleep"): + with self.assertRaises(SeatsioException): + HttpClient(httpbin_url(), "secretKey", None, 5).url("/anything").post("{}") + + assert_that(post.call_count).is_equal_to(1) + + def test_a_client_can_retry_with_the_same_idempotency_key(self): + key = str(uuid.uuid4()) + client = HttpClient(httpbin_url(), "secretKey", None, 5).with_idempotency_key(key) + + assert_that(self.sent_idempotency_key(client.url("/anything").post("{}"))).is_equal_to(key) + assert_that(self.sent_idempotency_key(client.url("/anything").post("{}"))).is_equal_to(key) + + def test_seatsio_client_can_retry_with_the_same_idempotency_key(self): + key = str(uuid.uuid4()) + client = Client(Region(httpbin_url()), "secretKey").with_idempotency_key(key) + + res1 = client.http_client.url("/anything").post("{}") + res2 = client.http_client.url("/anything").post("{}") + + assert_that(self.sent_idempotency_key(res1)).is_equal_to(key) + assert_that(self.sent_idempotency_key(res2)).is_equal_to(key) + + def test_seatsio_client_can_retry_with_the_same_idempotency_key_camel_case(self): + key = str(uuid.uuid4()) + client = Client(Region(httpbin_url()), "secretKey").withIdempotencyKey(key) + + res = client.http_client.url("/anything").post("{}") + assert_that(self.sent_idempotency_key(res)).is_equal_to(key) + + def test_retries_reuse_same_idempotency_key(self): + captured_keys = [] + original_post = requests.post + + def mock_post(*args, **kwargs): + headers = kwargs.get("headers", {}) + if "Idempotency-Key" in headers: + captured_keys.append(headers["Idempotency-Key"]) + return original_post(*args, **kwargs) + + with unittest.mock.patch("requests.post", side_effect=mock_post): + try: + HttpClient(httpbin_url(), "secretKey", None, 2, timeout=5).url("/status/429").post("{}") + except RateLimitExceededException: + pass + + assert len(captured_keys) > 1 + assert_that(set(captured_keys)).has_size(1) + assert_that(uuid.UUID(captured_keys[0]).version).is_equal_to(4) + + @staticmethod + @contextlib.contextmanager + def spy_on_post(): + sent_keys = [] + original_post = requests.post + + def spy(*args, **kwargs): + sent_keys.append(kwargs.get("headers", {}).get("Idempotency-Key")) + return original_post(*args, **kwargs) + + with unittest.mock.patch("requests.post", side_effect=spy): + yield sent_keys + + @staticmethod + def json_response(status_code, error_code=None): + response = unittest.mock.Mock() + response.status_code = status_code + response.headers = {"content-type": "application/json"} + errors = [{"code": error_code, "message": error_code}] if error_code else [] + response.json.return_value = {"errors": errors, "requestId": "123"} + return response + + @staticmethod + def sent_idempotency_key(response): + data = response.json() if hasattr(response, "json") else response + header = data.get("headers", {}).get("Idempotency-Key") + # httpbingo returns header values as arrays, httpbin as strings + return header[0] if isinstance(header, list) else header