From 7401b697265c72e6c166142ac9acf4e7b90120a4 Mon Sep 17 00:00:00 2001 From: Aryan Date: Wed, 21 Oct 2026 23:26:48 +0530 Subject: [PATCH] Preserve unit metadata in restricted registries Keep the original unit when creating a metric snapshot with selected samples. Cover the restricted registry object and the OpenMetrics WSGI response for name[] filtering. Assisted-by: OpenAI Codex Signed-off-by: Aryan --- prometheus_client/metrics_core.py | 2 +- tests/test_core.py | 8 ++++++++ tests/test_wsgi.py | 20 ++++++++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/prometheus_client/metrics_core.py b/prometheus_client/metrics_core.py index 27d1712d..1e84c4ad 100644 --- a/prometheus_client/metrics_core.py +++ b/prometheus_client/metrics_core.py @@ -59,7 +59,7 @@ def _restricted_metric(self, names): """Build a snapshot of a metric with samples restricted to a given set of names.""" samples = [s for s in self.samples if s[0] in names] if samples: - m = Metric(self.name, self.documentation, self.type) + m = Metric(self.name, self.documentation, self.type, self.unit) m.samples = samples return m return None diff --git a/tests/test_core.py b/tests/test_core.py index 2c29f79a..50d390c3 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -1115,6 +1115,14 @@ def test_restricted_registry_adds_new_metrics(self): self.assertEqual([m], list(restricted_registry.collect())) + def test_restricted_registry_preserves_unit(self): + registry = CollectorRegistry() + Summary('s', 'help', unit='seconds', registry=registry).observe(7) + + m = Metric('s_seconds', 'help', 'summary', unit='seconds') + m.samples = [Sample('s_seconds_sum', {}, 7)] + self.assertEqual([m], list(registry.restricted_registry(['s_seconds_sum']).collect())) + def test_target_info_injected(self): registry = CollectorRegistry(target_info={'foo': 'bar'}) self.assertEqual(1, registry.get_sample_value('target_info', {'foo': 'bar'})) diff --git a/tests/test_wsgi.py b/tests/test_wsgi.py index 3c12fc69..5f8b94ce 100644 --- a/tests/test_wsgi.py +++ b/tests/test_wsgi.py @@ -57,6 +57,26 @@ def validate_metrics(self, metric_name, help_text, increments): def test_report_metrics_1(self): self.validate_metrics("counter", "A counter", 2) + def test_filtered_openmetrics_preserves_unit(self): + counter = Counter('response_size', 'Response size', unit='bytes', registry=self.registry) + counter.inc(7) + self.environ['HTTP_ACCEPT'] = 'application/openmetrics-text; version=1.0.0' + self.environ['QUERY_STRING'] = 'name[]=response_size_bytes_total' + + output = make_wsgi_app(self.registry)(self.environ, self.capture) + + self.assertEqual(self.captured_status, '200 OK') + self.assertEqual( + output, + [ + b'# HELP response_size_bytes Response size\n' + b'# TYPE response_size_bytes counter\n' + b'# UNIT response_size_bytes bytes\n' + b'response_size_bytes_total 7.0\n' + b'# EOF\n' + ], + ) + def test_report_metrics_2(self): self.validate_metrics("counter", "Another counter", 3)