Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix wrong encoder used with application/openmetrics-text accept header #864

Merged
merged 1 commit into from
Dec 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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"