Skip to content

Commit

Permalink
Merge pull request #864 from jezekra1/fix-asgi-app-openmetrics-encodi…
Browse files Browse the repository at this point in the history
…ng-content-type

Fix wrong encoder used with `application/openmetrics-text` accept header
  • Loading branch information
csmarchbanks committed Dec 6, 2022
2 parents 89552cd + bab1f3b commit 1dfc910
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
2 changes: 1 addition & 1 deletion prometheus_client/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ async def prometheus_app(scope, receive, send):
assert scope.get("type") == "http"
# Prepare parameters
params = parse_qs(scope.get('query_string', b''))
accept_header = "Accept: " + ",".join([
accept_header = ",".join([
value.decode("utf8") for (name, value) in scope.get('headers')
if name.decode("utf8").lower() == 'accept'
])
Expand Down
32 changes: 32 additions & 0 deletions tests/test_asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,19 @@ def get_all_output(self):
break
return outputs

def get_all_response_headers(self):
outputs = self.get_all_output()
response_start = next(o for o in outputs if o["type"] == "http.response.start")
return response_start["headers"]

def get_response_header_value(self, header_name):
response_headers = self.get_all_response_headers()
return next(
value.decode("utf-8")
for name, value in response_headers
if name.decode("utf-8") == header_name
)

def increment_metrics(self, metric_name, help_text, increments):
c = Counter(metric_name, help_text, registry=self.registry)
for _ in range(increments):
Expand Down Expand Up @@ -158,3 +171,22 @@ def test_gzip_disabled(self):
# Assert outputs are not compressed.
outputs = self.get_all_output()
self.assert_outputs(outputs, metric_name, help_text, increments, compressed=False)

def test_openmetrics_encoding(self):
"""Response content type is application/openmetrics-text when appropriate Accept header is in request"""
app = make_asgi_app(self.registry)
self.seed_app(app)
self.scope["headers"] = [(b"Accept", b"application/openmetrics-text")]
self.send_input({"type": "http.request", "body": b""})

content_type = self.get_response_header_value('Content-Type').split(";")[0]
assert content_type == "application/openmetrics-text"

def test_plaintext_encoding(self):
"""Response content type is text/plain when Accept header is missing in request"""
app = make_asgi_app(self.registry)
self.seed_app(app)
self.send_input({"type": "http.request", "body": b""})

content_type = self.get_response_header_value('Content-Type').split(";")[0]
assert content_type == "text/plain"

0 comments on commit 1dfc910

Please sign in to comment.