Skip to content

Commit 6e40d86

Browse files
committed
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.
1 parent 4c4131e commit 6e40d86

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

pyDataverse/api.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -411,9 +411,14 @@ def _sync_request(
411411
kwargs = self._filter_kwargs(kwargs)
412412

413413
try:
414-
resp = method(**kwargs, auth=self.auth, follow_redirects=True, timeout=None)
414+
resp: httpx.Response = method(
415+
**kwargs, auth=self.auth, follow_redirects=True, timeout=None
416+
)
415417
if resp.status_code == 401:
416-
error_msg = resp.json()["message"]
418+
try:
419+
error_msg = resp.json()["message"]
420+
except json.JSONDecodeError:
421+
error_msg = resp.reason_phrase
417422
raise ApiAuthorizationError(
418423
"ERROR: HTTP 401 - Authorization error {0}. MSG: {1}".format(
419424
kwargs["url"], error_msg

tests/api/test_api.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,3 +217,16 @@ def test_sword_api_requires_http_basic_auth(self):
217217
API_TOKEN = os.getenv("API_TOKEN")
218218
api = SwordApi(BASE_URL, api_token=API_TOKEN)
219219
assert isinstance(api.auth, httpx.BasicAuth)
220+
221+
def test_sword_api_can_authenticate(self):
222+
BASE_URL = os.getenv("BASE_URL")
223+
API_TOKEN = os.getenv("API_TOKEN")
224+
api = SwordApi(BASE_URL, api_token=API_TOKEN)
225+
response = api.get_service_document()
226+
assert response.status_code == 200
227+
228+
def test_sword_api_cannot_authenticate_without_token(self):
229+
BASE_URL = os.getenv("BASE_URL")
230+
api = SwordApi(BASE_URL)
231+
with pytest.raises(ApiAuthorizationError):
232+
api.get_service_document()

0 commit comments

Comments
 (0)