summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRoger Gonzalez <roger@rogs.me>2024-03-09 19:20:57 -0300
committerRoger Gonzalez <roger@rogs.me>2024-03-09 19:20:57 -0300
commit92bd17ce309a929eda2a9b1ec6ea58bf0448d155 (patch)
treeee8057cda76810e56ca7d94eaa85d176a7890328
parent8b13798eec3ac732919ffefafa764901b186055a (diff)
Reauthorizing if the token expires
-rwxr-xr-xsrc/ute_wrapper/ute.py11
-rw-r--r--tests/test_ute.py12
2 files changed, 19 insertions, 4 deletions
diff --git a/src/ute_wrapper/ute.py b/src/ute_wrapper/ute.py
index 786b2a2..4851167 100755
--- a/src/ute_wrapper/ute.py
+++ b/src/ute_wrapper/ute.py
@@ -112,7 +112,7 @@ class UTEClient:
delay: float = 2,
) -> requests.Response:
"""
- Make a HTTP request with retries.
+ Make a HTTP request with retries and handle expired authorization.
Args:
method (str): The HTTP method to use. Accepted methods are ``GET``, ``POST``.
@@ -134,12 +134,15 @@ class UTEClient:
"Connection": "Keep-Alive",
}
- if self.authorization:
- headers["Authorization"] = f"Bearer {self.authorization}"
-
for attempt in range(retries):
+ if self.authorization:
+ headers["Authorization"] = f"Bearer {self.authorization}"
+
try:
response = getattr(requests, method.lower(), self._method_not_supported)(url, headers=headers, json=data)
+ if response.status_code == requests.codes.unauthorized:
+ self._login()
+ continue
response.raise_for_status()
return response
except (requests.RequestException, Exception):
diff --git a/tests/test_ute.py b/tests/test_ute.py
index 9e33b38..03d8e84 100644
--- a/tests/test_ute.py
+++ b/tests/test_ute.py
@@ -50,6 +50,18 @@ def test_make_request_no_authorization(ute_client, mocker: MockerFixture):
assert response.json()["success"] is True
+def test_make_request_expired_authorization(ute_client, mocker: MockerFixture):
+ """Test the _make_request method when the authorization code has expired."""
+ mocked_unauthorized_response = mocker.Mock(status_code=requests.codes.unauthorized)
+ mocked_success_response = mocker.Mock(status_code=requests.codes.ok, json=lambda: {"success": True})
+ mocker.patch("requests.get", side_effect=[mocked_unauthorized_response, mocked_success_response])
+ mocker.patch.object(ute_client, "_login")
+ response = ute_client._make_request("GET", "http://example.com")
+ assert response.status_code == requests.codes.ok
+ assert response.json()["success"] is True
+ ute_client._login.assert_called_once()
+
+
def test_make_request_all_retries_failed(ute_client, mocker: MockerFixture):
"""Test the _make_request method when all retries fail."""
mocked_response = mocker.Mock()