Skip to content

Commit 160b2a8

Browse files
authored
Merge pull request #104 from GitGuardian/agateau/improve-error-handling
Improve error handling
2 parents e737d98 + b728238 commit 160b2a8

File tree

3 files changed

+41
-3
lines changed

3 files changed

+41
-3
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
### Fixed
2+
3+
- GGClient no longer crashes when it receives an odd server response, like a response with no Content-Type header.

pygitguardian/client.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ def load_detail(resp: Response) -> Detail:
8282
:return: detail object of response
8383
:rtype: Detail
8484
"""
85-
if resp.headers["content-type"] == "application/json":
85+
if resp.headers.get("content-type") == "application/json":
8686
data = resp.json()
8787
else:
8888
data = {"detail": resp.text}
@@ -96,7 +96,7 @@ def is_ok(resp: Response) -> bool:
9696
and the content type is JSON.
9797
"""
9898
return (
99-
resp.headers["content-type"] == "application/json"
99+
resp.headers.get("content-type") == "application/json"
100100
and resp.status_code == codes.ok
101101
)
102102

@@ -107,7 +107,7 @@ def is_create_ok(resp: Response) -> bool:
107107
and the content type is JSON.
108108
"""
109109
return (
110-
resp.headers["content-type"] == "application/json"
110+
resp.headers.get("content-type") == "application/json"
111111
and resp.status_code == codes.created
112112
)
113113

tests/test_client.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1113,3 +1113,38 @@ def test_sca_client_scan_diff_with_params(client: GGClient):
11131113

11141114
assert vyper_vulns is not None
11151115
assert all(vuln.severity in ("high", "critical") for vuln in vyper_vulns.vulns)
1116+
1117+
1118+
def test_is_ok_bad_response():
1119+
"""
1120+
GIVEN a 500 response with no content-type header
1121+
WHEN is_ok() is called
1122+
THEN it does not fail
1123+
AND returns false
1124+
"""
1125+
resp = Mock()
1126+
resp.headers = {}
1127+
resp.status_code = 500
1128+
resp.text = "Failed"
1129+
1130+
assert not is_ok(resp)
1131+
1132+
1133+
@responses.activate
1134+
def test_read_metadata_bad_response(client: GGClient):
1135+
"""
1136+
GIVEN a /metadata endpoint that returns a 500 error with no content-type
1137+
THEN a call to read_metadata() does not fail
1138+
AND returns a valid Detail instance
1139+
"""
1140+
mock_response = responses.get(
1141+
url=client._url_from_endpoint("metadata", "v1"),
1142+
status=500,
1143+
body="Failed",
1144+
)
1145+
1146+
detail = client.read_metadata()
1147+
1148+
assert mock_response.call_count == 1
1149+
assert detail.status_code == 500
1150+
assert detail.detail == "Failed"

0 commit comments

Comments
 (0)