8000 Coerce label values to strings. · gdvalle/client_python@7265112 · GitHub
[go: up one dir, main page]

Skip to content

Commit 7265112

Browse files
committed
Coerce label values to strings.
Make __all__ work with unicode_literals
1 parent f6bf14e commit 7265112

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

prometheus_client/__init__.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,14 @@
1212
from BaseHTTPServer import BaseHTTPRequestHandler
1313
except ImportError:
1414
# Python 3
15+
unicode = str
1516
from http.server import BaseHTTPRequestHandler
1617
from functools import wraps
1718
from threading import Lock
1819

1920
__all__ = ['Counter', 'Gauge', 'Summary', 'Histogram']
21+
# http://stackoverflow.com/questions/19913653/no-unicode-in-all-for-a-packages-init
22+
__all__ = [n.encode('ascii') for n in __all__]
2023

2124
_METRIC_NAME_RE = re.compile(r'^[a-zA-Z_:][a-zA-Z0-9_:]*$')
2225
_METRIC_LABEL_NAME_RE = re.compile(r'^[a-zA-Z_:][a-zA-Z0-9_:]*$')
@@ -108,7 +111,7 @@ def labels(self, *labelvalues):
108111
'''Return the child for the given labelset.'''
109112
if len(labelvalues) != len(self._labelnames):
110113
raise ValueError('Incorrect label count')
111-
labelvalues = tuple(labelvalues)
114+
labelvalues = tuple([unicode(l) for l in labelvalues])
112115
with self._lock:
113116
if labelvalues not in self._metrics:
114117
self._metrics[labelvalues] = self._wrappedClass(**self._kwargs)
@@ -118,7 +121,7 @@ def remove(self, *labelvalues):
118121
'''Remove the given labelset from the metric.'''
119122
if len(labelvalues) != len(self._labelnames):
120123
raise ValueError('Incorrect label count')
121-
labelvalues = tuple(labelvalues)
124+
labelvalues = tuple([unicode(l) for l in labelvalues])
122125
with self._lock:
123126
del self._metrics[labelvalues]
124127

tests/test_client.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,18 @@ def test_incorrect_label_count_raises(self):
223223
self.assertRaises(ValueError, self.counter.remove)
224224
self.assertRaises(ValueError, self.counter.remove, 'a', 'b')
225225

226+
def test_labels_coerced_to_string(self):
227+
self.counter.labels(None).inc()
228+
self.assertEqual(1, self.registry.get_sample_value('c', {'l': 'None'}))
229+
230+
self.counter.remove(None)
231+
self.assertEqual(None, self.registry.get_sample_value('c', {'l': 'None'}))
232+
233+
def test_non_string_labels_raises(self):
234+
class Test(object):
235+
__str__ = None
236+
self.assertRaises(TypeError, self.counter.labels, Test())
237+
226238
def test_namespace_subsystem_concatenated(self):
227239
c = Counter('c', 'help', namespace='a', subsystem='b', registry=self.registry)
228240
c.inc()

0 commit comments

Comments
 (0)
0