Skip to content

Commit 7ae97ce

Browse files
authored
Add retry logic for bad gateway response errors (#149)
1 parent eef7100 commit 7ae97ce

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

bring_api/bring.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from json import JSONDecodeError
88
import logging
99
import os
10+
from random import randint
1011
import time
1112
from typing import TYPE_CHECKING, Any
1213

@@ -144,6 +145,18 @@ async def _request(
144145
"the authorization token is invalid or expired."
145146
)
146147

148+
if (
149+
r.status
150+
in (
151+
HTTPStatus.BAD_GATEWAY,
152+
HTTPStatus.SERVICE_UNAVAILABLE,
153+
HTTPStatus.GATEWAY_TIMEOUT,
154+
)
155+
and not retry
156+
):
157+
await asyncio.sleep(delay=randint(1, 5000) / 1000)
158+
return await self._request(method, url, retry=True, **kwargs)
159+
147160
r.raise_for_status()
148161

149162
except aiohttp.ClientResponseError as e:

tests/test_request.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import asyncio
44
from http import HTTPStatus
5+
from unittest.mock import patch
56

67
import aiohttp
78
from aioresponses import aioresponses
@@ -88,3 +89,30 @@ async def test_auth_expired(
8889
method="get",
8990
headers=DEFAULT_HEADERS,
9091
)
92+
93+
94+
async def test_bad_gateway_retry(mocked: aioresponses, bring: Bring) -> None:
95+
"""Test retry logic for bad gateway errors."""
96+
97+
await bring.login()
98+
mocked.clear()
99+
100+
mocked.get(
101+
URL("https://api.getbring.com/test"),
102+
status=HTTPStatus.BAD_GATEWAY,
103+
)
104+
mocked.get(
105+
URL("https://api.getbring.com/test"),
106+
status=HTTPStatus.OK,
107+
)
108+
109+
with patch("bring_api.bring.randint", return_value=0):
110+
await bring._request("GET", URL("https://api.getbring.com/test"))
111+
112+
mocked.assert_called_with(
113+
"https://api.getbring.com/test",
114+
method="get",
115+
headers=DEFAULT_HEADERS,
116+
)
117+
118+
assert len(mocked._responses) == 2

0 commit comments

Comments
 (0)