diff --git a/prometheus_client/metrics.py b/prometheus_client/metrics.py index b34ca817..95770ebd 100644 --- a/prometheus_client/metrics.py +++ b/prometheus_client/metrics.py @@ -27,12 +27,12 @@ def _build_full_name(metric_type, name, namespace, subsystem, unit): if subsystem: full_name += subsystem + '_' full_name += name + if metric_type == 'counter' and full_name.endswith('_total'): + full_name = full_name[:-6] # Munge to OpenMetrics. if unit and not full_name.endswith("_" + unit): full_name += "_" + unit if unit and metric_type in ('info', 'stateset'): raise ValueError('Metric name is of a type that cannot have a unit: ' + full_name) - if metric_type == 'counter' and full_name.endswith('_total'): - full_name = full_name[:-6] # Munge to OpenMetrics. return full_name diff --git a/tests/test_asgi.py b/tests/test_asgi.py index b2d9a70f..e31a3b6e 100644 --- a/tests/test_asgi.py +++ b/tests/test_asgi.py @@ -80,11 +80,11 @@ def get_all_output(self): break return outputs - def validate_metrics(self, metric_name, help_text, increments): + def validate_metrics(self, metric_name, help_text, increments, unit=''): """ ASGI app serves the metrics from the provided registry. """ - c = Counter(metric_name, help_text, registry=self.registry) + c = Counter(metric_name, help_text, unit=unit, registry=self.registry) for _ in range(increments): c.inc() # Create and run ASGI app diff --git a/tests/test_core.py b/tests/test_core.py index f0b856a5..b14e340b 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -527,6 +527,11 @@ def test_no_units_for_info_enum(self): self.assertRaises(ValueError, Info, 'foo', 'help', unit="x") self.assertRaises(ValueError, Enum, 'foo', 'help', unit="x") + def test_name_cleanup_before_unit_append(self): + self.assertEqual(self.counter._name, 'c') + self.c = Counter('c_total', 'help', unit="total", labelnames=['l'], registry=self.registry) + self.assertEqual(self.c._name, 'c_total') + class TestMetricFamilies(unittest.TestCase): def setUp(self): diff --git a/tests/test_exposition.py b/tests/test_exposition.py index 47c200f3..21b3f59f 100644 --- a/tests/test_exposition.py +++ b/tests/test_exposition.py @@ -59,6 +59,17 @@ def test_counter(self): # HELP cc_created A counter # TYPE cc_created gauge cc_created 123.456 +""", generate_latest(self.registry)) + + def test_counter_name_unit_append(self): + c = Counter('requests', 'Request counter', unit="total", registry=self.registry) + c.inc() + self.assertEqual(b"""# HELP requests_total_total Request counter +# TYPE requests_total_total counter +requests_total_total 1.0 +# HELP requests_total_created Request counter +# TYPE requests_total_created gauge +requests_total_created 123.456 """, generate_latest(self.registry)) def test_counter_total(self):