userver: /data/code/userver/testsuite/pytest_plugins/pytest_userver/metrics.py Source File
Loading...
Searching...
No Matches
metrics.py
1"""
2Python module that provides helpers for functional testing of metrics with
3testsuite; see
4@ref scripts/docs/en/userver/functional_testing.md for an introduction.
5
6@ingroup userver_testsuite
7"""
8
9import dataclasses
10import enum
11import itertools
12import json
13import math
14import random
15import typing
16
17
18# @cond
19class MetricType(str, enum.Enum):
20 """
21 The type of individual metric.
22
23 `UNSPECIFIED` compares equal to all `MetricType`s.
24 To disable this behavior, use `is` for comparisons.
25 """
26
27 UNSPECIFIED = 'UNSPECIFIED'
28 GAUGE = 'GAUGE'
29 RATE = 'RATE'
30 HIST_RATE = 'HIST_RATE'
31 # @endcond
32
33
34@dataclasses.dataclass
36 """
37 Represents the value of a HIST_RATE (a.k.a. Histogram) metric.
38
39 Usage example:
40 @snippet testsuite/tests/test_metrics.py histogram
41
42 Normally obtained from MetricsSnapshot
43 """
44
45 bounds: typing.List[float]
46 buckets: typing.List[int]
47 inf: int
48
49 def count(self) -> int:
50 return sum(self.bucketsbuckets) + self.inf
51
52 def percentile(self, percent: float) -> float:
53 return _do_compute_percentile(self, percent)
54
55 # @cond
56 def __post_init__(self):
57 assert len(self.bounds) == len(self.bucketsbuckets)
58 assert sorted(self.bounds) == self.bounds
59 if self.bounds:
60 assert self.bounds[0] > 0
61 assert self.bounds[-1] != math.inf
62
63 # @endcond
64
65
66MetricValue = typing.Union[float, Histogram]
67
68
69@dataclasses.dataclass(frozen=True)
70class Metric:
71 """
72 Metric type that contains the `labels: typing.Dict[str, str]` and
73 `value: int`.
74
75 The type is hashable and comparable:
76 @snippet testsuite/tests/test_metrics.py values set
77
78 @ingroup userver_testsuite
79 """
80
81 labels: typing.Dict[str, str]
82 value: MetricValue
83
84 # @cond
85 # Should not be specified explicitly, for internal use only.
86 _type: MetricType = MetricType.UNSPECIFIED
87 # @endcond
88
89 def __eq__(self, other: typing.Any) -> bool:
90 if not isinstance(other, Metric):
91 return NotImplemented
92 return (
93 self.labelslabels == other.labels
94 and self.valuevalue == other.value
95 and _type_eq(self._type, other._type)
96 )
97
98 def __hash__(self) -> int:
99 return hash(_get_labels_tuple(self))
100
101 # @cond
102 def __post_init__(self):
103 if isinstance(self.valuevalue, Histogram):
104 assert (
105 self._type == MetricType.HIST_RATE
106 or self._type == MetricType.UNSPECIFIED
107 )
108 else:
109 assert self._type is not MetricType.HIST_RATE
110
111 # For internal use only.
112 def type(self) -> MetricType:
113 return self._type
114
115 # @endcond
116
117
118class _MetricsJSONEncoder(json.JSONEncoder):
119 def default(self, o): # pylint: disable=method-hidden
120 if isinstance(o, Metric):
121 result = {'labels': o.labels, 'value': o.value}
122 if o.type() is not MetricType.UNSPECIFIED:
123 result['type'] = o.type()
124 return result
125 elif isinstance(o, Histogram):
126 return dataclasses.asdict(o)
127 if isinstance(o, set):
128 return list(o)
129 return super().default(o)
130
131
133 """
134 Snapshot of captured metrics that mimics the dict interface. Metrics have
135 the 'Dict[str(path), Set[Metric]]' format.
136
137 @snippet samples/testsuite-support/tests/test_metrics.py metrics labels
138
139 @ingroup userver_testsuite
140 """
141
142 def __init__(self, values: typing.Mapping[str, typing.Set[Metric]]):
143 self._values = values
144
145 def __getitem__(self, path: str) -> typing.Set[Metric]:
146 """Returns a list of metrics by specified path"""
147 return self._values[path]
148
149 def __len__(self) -> int:
150 """Returns count of metrics paths"""
151 return len(self._values)
152
153 def __iter__(self):
154 """Returns a (path, list) iterable over the metrics"""
155 return self._values.__iter__()
156
157 def __contains__(self, path: str) -> bool:
158 """
159 Returns True if metric with specified path is in the snapshot,
160 False otherwise.
161 """
162 return path in self._values
163
164 def __eq__(self, other: object) -> bool:
165 """
166 Compares the snapshot with a dict of metrics or with
167 another snapshot
168 """
169 return self._values == other
170
171 def __repr__(self) -> str:
172 return self._values.__repr__()
173
174 def __str__(self) -> str:
175 return self.pretty_print()
176
177 def get(self, path: str, default=None):
178 """
179 Returns an list of metrics by path or default if there's no
180 such path
181 """
182 return self._values.get(path, default)
183
184 def items(self):
185 """Returns a (path, list) iterable over the metrics"""
186 return self._values.items()
187
188 def keys(self):
189 """Returns an iterable over paths of metrics"""
190 return self._values.keys()
191
192 def values(self):
193 """Returns an iterable over lists of metrics"""
194 return self._values.values()
195
197 self,
198 path: str,
199 labels: typing.Optional[typing.Dict] = None,
200 *,
201 default: typing.Optional[MetricValue] = None,
202 ) -> MetricValue:
203 """
204 Returns a single metric value at specified path. If a dict of labels
205 is provided, does en exact match of labels (i.e. {} stands for no
206 labels; {'a': 'b', 'c': 'd'} matches only {'a': 'b', 'c': 'd'} or
207 {'c': 'd', 'a': 'b'} but neither match {'a': 'b'} nor
208 {'a': 'b', 'c': 'd', 'e': 'f'}).
209
210 @throws AssertionError if not one metric by path
211 """
212 entry = self.get(path, set())
213 assert (
214 entry or default is not None
215 ), f'No metrics found by path "{path}"'
216
217 if labels is not None:
218 entry = {x for x in entry if x.labels == labels}
219 assert (
220 entry or default is not None
221 ), f'No metrics found by path "{path}" and labels {labels}'
222 assert len(entry) <= 1, (
223 f'Multiple metrics found by path "{path}" and labels {labels}:'
224 f' {entry}'
225 )
226 else:
227 assert (
228 len(entry) <= 1
229 ), f'Multiple metrics found by path "{path}": {entry}'
230
231 if default is not None and not entry:
232 return default
233 return next(iter(entry)).value
234
236 self, path: str, require_labels: typing.Optional[typing.Dict] = None,
237 ) -> typing.List[Metric]:
238 """
239 Metrics path must exactly equal the given `path`.
240 A required subset of labels is specified by `require_labels`
241 Example:
242 require_labels={'a':'b', 'c':'d'}
243 { 'a':'b', 'c':'d'} - exact match
244 { 'a':'b', 'c':'d', 'e': 'f', 'h':'k'} - match
245 { 'a':'x', 'c':'d'} - no match, incorrect value for label 'a'
246 { 'a' : 'b'} - required label not found
247 Usage:
248 @code
249 for m in metrics_with_labels(path='something.something.sensor',
250 require_labels={ 'label1': 'value1' }):
251 assert m.value > 0
252 @endcode
253 """
254 entry = self.get(path, set())
255
256 def _is_labels_subset(require_labels, target_labels) -> bool:
257 for req_key, req_val in require_labels.items():
258 if target_labels.get(req_key, None) != req_val:
259 # required label is missing or its value is different
260 return False
261 return True
262
263 if require_labels is not None:
264 return list(
265 filter(
266 lambda x: _is_labels_subset(
267 require_labels=require_labels, target_labels=x.labels,
268 ),
269 entry,
270 ),
271 )
272 else:
273 return list(entry)
274
275 def has_metrics_at(
276 self, path: str, require_labels: typing.Optional[typing.Dict] = None,
277 ) -> bool:
278 # metrics_with_labels returns list, and pythonic way to check if list
279 # is empty is like this:
280 return bool(self.metrics_at(path, require_labels))
281
283 self,
284 other: typing.Mapping[str, typing.Set[Metric]],
285 *,
286 ignore_zeros: bool = False,
287 ) -> None:
288 """
289 Compares the snapshot with a dict of metrics or with
290 another snapshot, displaying a nice diff on mismatch
291 """
292 lhs = _flatten_snapshot(self, ignore_zeros=ignore_zeros)
293 rhs = _flatten_snapshot(other, ignore_zeros=ignore_zeros)
294 assert lhs == rhs, _diff_metric_snapshots(lhs, rhs, ignore_zeros)
295
296 def pretty_print(self) -> str:
297 """
298 Multiline linear print:
299 path: (label=value),(label=value) TYPE VALUE
300 path: (label=value),(label=value) TYPE VALUE
301 Usage:
302 @code
303 assert 'some.thing.sensor' in metric, metric.pretty_print()
304 @endcode
305 """
306
307 def _iterate_over_mset(path, mset):
308 """print (pretty) one metrics set - for given path"""
309 result = []
310 for metric in sorted(mset, key=lambda x: _get_labels_tuple(x)):
311 result.append(
312 '{}: {} {} {}'.format(
313 path,
314 # labels in form (key=value)
315 ','.join([
316 '({}={})'.format(k, v)
317 for k, v in _get_labels_tuple(metric)
318 ]),
319 metric._type.value,
320 metric.value,
321 ),
322 )
323 return result
324
325 # list of lists [ [ string1, string2, string3],
326 # [string4, string5, string6] ]
327 data_for_every_path = [
328 _iterate_over_mset(path, mset)
329 for path, mset in self._values.items()
330 ]
331 # use itertools.chain to flatten list
332 # [ string1, string2, string3, string4, string5, string6 ]
333 # and join to convert it to one multiline string
334 return '\n'.join(itertools.chain(*data_for_every_path))
335
336 @staticmethod
337 def from_json(json_str: str) -> 'MetricsSnapshot':
338 """
339 Construct MetricsSnapshot from a JSON string
340 """
341 json_data = {
342 str(path): {
343 Metric(
344 labels=element['labels'],
345 value=_parse_metric_value(element['value']),
346 _type=MetricType[element.get('type', 'UNSPECIFIED')],
347 )
348 for element in metrics_list
349 }
350 for path, metrics_list in json.loads(json_str).items()
351 }
352 return MetricsSnapshot(json_data)
353
354 def to_json(self) -> str:
355 """
356 Serialize to a JSON string
357 """
358 return json.dumps(
359 # Shuffle to disallow depending on the received metrics order.
360 {
361 path: random.sample(list(metrics), len(metrics))
362 for path, metrics in self._values.items()
363 },
364 cls=_MetricsJSONEncoder,
365 )
366
367
368def _type_eq(lhs: MetricType, rhs: MetricType) -> bool:
369 return (
370 lhs == rhs
371 or lhs == MetricType.UNSPECIFIED
372 or rhs == MetricType.UNSPECIFIED
373 )
374
375
376def _get_labels_tuple(metric: Metric) -> typing.Tuple:
377 """Returns labels as a tuple of sorted items"""
378 return tuple(sorted(metric.labels.items()))
379
380
381def _do_compute_percentile(hist: Histogram, percent: float) -> float:
382 # This implementation is O(hist.count()), which is less than perfect.
383 # So far, this was not a big enough pain to rewrite it.
384 value_lists = [
385 [bound] * bucket for (bucket, bound) in zip(hist.buckets, hist.bounds)
386 ] + [[math.inf] * hist.inf]
387 values = [item for sublist in value_lists for item in sublist]
388
389 # Implementation taken from:
390 # https://stackoverflow.com/a/2753343/5173839
391 if not values:
392 return 0
393 pivot = (len(values) - 1) * percent
394 floor = math.floor(pivot)
395 ceil = math.ceil(pivot)
396 if floor == ceil:
397 return values[int(pivot)]
398 part1 = values[int(floor)] * (ceil - pivot)
399 part2 = values[int(ceil)] * (pivot - floor)
400 return part1 + part2
401
402
403def _parse_metric_value(value: typing.Any) -> MetricValue:
404 if isinstance(value, dict):
405 return Histogram(
406 bounds=value['bounds'], buckets=value['buckets'], inf=value['inf'],
407 )
408 elif isinstance(value, float):
409 return value
410 elif isinstance(value, int):
411 return value
412 else:
413 raise Exception(f'Failed to parse metric value from {value!r}')
414
415
416_FlattenedSnapshot = typing.Set[typing.Tuple[str, Metric]]
417
418
419def _flatten_snapshot(values, ignore_zeros: bool) -> _FlattenedSnapshot:
420 return set(
421 (path, metric)
422 for path, metrics in values.items()
423 for metric in metrics
424 if metric.value != 0 or not ignore_zeros
425 )
426
427
428def _diff_metric_snapshots(
429 lhs: _FlattenedSnapshot, rhs: _FlattenedSnapshot, ignore_zeros: bool,
430) -> str:
431 def extra_metrics_message(extra, base):
432 return [
433 f' path={path!r} labels={metric.labels!r} value={metric.value}'
434 for path, metric in sorted(extra, key=lambda pair: pair[0])
435 if (path, metric) not in base
436 ]
437
438 if ignore_zeros:
439 lines = ['left.assert_equals(right, ignore_zeros=True) failed']
440 else:
441 lines = ['left.assert_equals(right) failed']
442 actual_extra = extra_metrics_message(lhs, rhs)
443 if actual_extra:
444 lines.append(' extra in left:')
445 lines += actual_extra
446
447 actual_gt = extra_metrics_message(rhs, lhs)
448 if actual_gt:
449 lines.append(' missing in left:')
450 lines += actual_gt
451
452 return '\n'.join(lines)