From c3b7a6720dd6b68a583127294ff44b2a89b305b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20H=C3=B6ffner?= Date: Tue, 23 Jul 2024 23:44:40 +0200 Subject: [PATCH] Add SWORD tests and make them pass The SWORD API returns an empty string for 401 Unauthorized. This would cause the usual response handling of extracting the error message from the JSON to raise, so we except that in that case. Resolves review comment on #201. --- pyDataverse/api.py | 9 +++++++-- tests/api/test_api.py | 13 +++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/pyDataverse/api.py b/pyDataverse/api.py index d3a77f7..a846a4e 100644 --- a/pyDataverse/api.py +++ b/pyDataverse/api.py @@ -447,9 +447,14 @@ def _sync_request( kwargs = self._filter_kwargs(kwargs) try: - resp = method(**kwargs, auth=self.auth, follow_redirects=True, timeout=None) + resp: httpx.Response = method( + **kwargs, auth=self.auth, follow_redirects=True, timeout=None + ) if resp.status_code == 401: - error_msg = resp.json()["message"] + try: + error_msg = resp.json()["message"] + except json.JSONDecodeError: + error_msg = resp.reason_phrase raise ApiAuthorizationError( "ERROR: HTTP 401 - Authorization error {0}. MSG: {1}".format( kwargs["url"], error_msg diff --git a/tests/api/test_api.py b/tests/api/test_api.py index c8e7b72..817c4b3 100644 --- a/tests/api/test_api.py +++ b/tests/api/test_api.py @@ -217,3 +217,16 @@ def test_sword_api_requires_http_basic_auth(self): API_TOKEN = os.getenv("API_TOKEN") api = SwordApi(BASE_URL, api_token=API_TOKEN) assert isinstance(api.auth, httpx.BasicAuth) + + def test_sword_api_can_authenticate(self): + BASE_URL = os.getenv("BASE_URL") + API_TOKEN = os.getenv("API_TOKEN") + api = SwordApi(BASE_URL, api_token=API_TOKEN) + response = api.get_service_document() + assert response.status_code == 200 + + def test_sword_api_cannot_authenticate_without_token(self): + BASE_URL = os.getenv("BASE_URL") + api = SwordApi(BASE_URL) + with pytest.raises(ApiAuthorizationError): + api.get_service_document()