Skip to content

Commit c3b7a67

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 5601c4a commit c3b7a67

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
@@ -447,9 +447,14 @@ def _sync_request(
447447
kwargs = self._filter_kwargs(kwargs)
448448

449449
try:
450-
resp = method(**kwargs, auth=self.auth, follow_redirects=True, timeout=None)
450+
resp: httpx.Response = method(
451+
**kwargs, auth=self.auth, follow_redirects=True, timeout=None
452+
)
451453
if resp.status_code == 401:
452-
error_msg = resp.json()["message"]
454+
try:
455+
error_msg = resp.json()["message"]
456+
except json.JSONDecodeError:
457+
error_msg = resp.reason_phrase
453458
raise ApiAuthorizationError(
454459
"ERROR: HTTP 401 - Authorization error {0}. MSG: {1}".format(
455460
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)