Skip to content

Commit 5906fc9

Browse files
committed
Fix handling 204 No Content responses from Grafana HTTP API
Those kinds of responses are yielded, for example, when deleting alert provisioning rules.
1 parent cf906a9 commit 5906fc9

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

grafana_client/client.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,12 @@ def __request_runner(url, json=None, data=None, headers=None):
158158
response,
159159
"Client Error {0}: {1}".format(r.status_code, message),
160160
)
161+
162+
# `204 No Content` responses have an empty response body,
163+
# so it doesn't decode well from JSON.
164+
if r.status_code == 204:
165+
return None
166+
161167
# The "Tempo" data source responds with text/plain.
162168
if r.headers.get("Content-Type", "").startswith("text/"):
163169
return r.text

test/test_grafana_client.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,10 @@
1313

1414

1515
class MockResponse:
16-
def __init__(self, json_data, status_code, headers=None):
17-
self.json_data = json_data
16+
def __init__(self, status_code, headers=None, json_data=None):
1817
self.status_code = status_code
1918
self.headers = headers or {"Content-Type": "application/json"}
19+
self.json_data = json_data
2020

2121
def json(self):
2222
return self.json_data
@@ -63,15 +63,15 @@ def test_grafana_client_no_verify(self):
6363
)
6464
grafana.client.s.get = Mock(name="get")
6565
grafana.client.s.get.return_value = MockResponse(
66-
{
66+
status_code=200,
67+
json_data={
6768
"email": "[email protected]",
6869
"name": "admin",
6970
"login": "admin",
7071
"theme": "light",
7172
"orgId": 1,
7273
"isGrafanaAdmin": True,
7374
},
74-
200,
7575
)
7676

7777
basic_auth = requests.auth.HTTPBasicAuth("admin", "admin")
@@ -147,3 +147,12 @@ def test_grafana_client_version(self, mock_get):
147147
def test_grafana_client_non_json_response(self):
148148
grafana = GrafanaApi.from_url("https://httpbin.org/html")
149149
self.assertRaises(GrafanaClientError, lambda: grafana.connect())
150+
151+
def test_grafana_client_204_no_content_response(self):
152+
grafana = GrafanaApi.from_url()
153+
grafana.client.s.delete = Mock(name="get")
154+
grafana.client.s.delete.return_value = MockResponse(
155+
status_code=204,
156+
)
157+
response = grafana.alertingprovisioning.delete_alertrule("foobar")
158+
assert response is None

0 commit comments

Comments
 (0)