Skip to content

Commit

Permalink
Add SWORD tests and make them pass
Browse files Browse the repository at this point in the history
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 gdcc#201.
  • Loading branch information
shoeffner committed Aug 24, 2024
1 parent 5601c4a commit c3b7a67
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
9 changes: 7 additions & 2 deletions pyDataverse/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions tests/api/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

0 comments on commit c3b7a67

Please sign in to comment.