2Python module that provides helpers for functional testing of metrics with
4@ref scripts/docs/en/userver/functional_testing.md for an introduction.
6@ingroup userver_testsuite
19class MetricType(str, enum.Enum):
21 The type of individual metric.
23 `UNSPECIFIED` compares equal to all `MetricType`s.
24 To disable this behavior, use `is` for comparisons.
27 UNSPECIFIED =
'UNSPECIFIED'
30 HIST_RATE =
'HIST_RATE'
37 Represents the value of a HIST_RATE (a.k.a. Histogram) metric.
40 @snippet testsuite/tests/test_metrics.py histogram
42 Normally obtained from MetricsSnapshot
45 bounds: typing.List[float]
46 buckets: typing.List[int]
49 def count(self) -> int:
52 def percentile(self, percent: float) -> float:
53 return _do_compute_percentile(self, percent)
56 def __post_init__(self):
61 assert self.
bounds[-1] != math.inf
66MetricValue = typing.Union[float, Histogram]
69@dataclasses.dataclass(frozen=True)
72 Metric type that contains the `labels: typing.Dict[str, str]` and
75 The type is hashable and comparable:
76 @snippet testsuite/tests/test_metrics.py values set
78 @ingroup userver_testsuite
81 labels: typing.Dict[str, str]
86 _type: MetricType = MetricType.UNSPECIFIED
89 def __eq__(self, other: typing.Any) -> bool:
90 if not isinstance(other, Metric):
92 return self.
labelslabels == other.labels
and self.
value == other.value
and _type_eq(self._type, other._type)
94 def __hash__(self) -> int:
98 def __post_init__(self):
99 if isinstance(self.
value, Histogram):
100 assert self._type == MetricType.HIST_RATE
or self._type == MetricType.UNSPECIFIED
102 assert self._type
is not MetricType.HIST_RATE
105 def type(self) -> MetricType:
112 def default(self, o):
113 if isinstance(o, Metric):
114 result = {
'labels': o.labels,
'value': o.value}
115 if o.type()
is not MetricType.UNSPECIFIED:
116 result[
'type'] = o.type()
118 elif isinstance(o, Histogram):
119 return dataclasses.asdict(o)
120 if isinstance(o, set):
122 return super().default(o)
127 Snapshot of captured metrics that mimics the dict interface. Metrics have
128 the 'Dict[str(path), Set[Metric]]' format.
130 @snippet samples/testsuite-support/tests/test_metrics.py metrics labels
132 @ingroup userver_testsuite
135 def __init__(self, values: typing.Mapping[str, typing.Set[Metric]]):
139 """Returns a list of metrics by specified path"""
143 """Returns count of metrics paths"""
147 """Returns a (path, list) iterable over the metrics"""
152 Returns True if metric with specified path is in the snapshot,
159 Compares the snapshot with a dict of metrics or with
164 def __repr__(self) -> str:
167 def __str__(self) -> str:
170 def get(self, path: str, default=
None):
172 Returns an list of metrics by path or default if there's no
178 """Returns a (path, list) iterable over the metrics"""
182 """Returns an iterable over paths of metrics"""
186 """Returns an iterable over lists of metrics"""
192 labels: typing.Optional[typing.Dict] =
None,
194 default: typing.Optional[MetricValue] =
None,
197 Returns a single metric value at specified path. If a dict of labels
198 is provided, does en exact match of labels (i.e. {} stands for no
199 labels; {'a': 'b', 'c': 'd'} matches only {'a': 'b', 'c': 'd'} or
200 {'c': 'd', 'a': 'b'} but neither match {'a': 'b'} nor
201 {'a': 'b', 'c': 'd', 'e': 'f'}).
203 @throws AssertionError if not one metric by path
205 entry = self.
get(path, set())
206 assert entry
or default
is not None, f
'No metrics found by path "{path}"'
208 if labels
is not None:
209 entry = {x
for x
in entry
if x.labels == labels}
210 assert entry
or default
is not None, f
'No metrics found by path "{path}" and labels {labels}'
211 assert len(entry) <= 1, f
'Multiple metrics found by path "{path}" and labels {labels}: {entry}'
213 assert len(entry) <= 1, f
'Multiple metrics found by path "{path}": {entry}'
215 if default
is not None and not entry:
217 return next(iter(entry)).value
222 require_labels: typing.Optional[typing.Dict] =
None,
223 ) -> typing.List[Metric]:
225 Metrics path must exactly equal the given `path`.
226 A required subset of labels is specified by `require_labels`
228 require_labels={'a':'b', 'c':'d'}
229 { 'a':'b', 'c':'d'} - exact match
230 { 'a':'b', 'c':'d', 'e': 'f', 'h':'k'} - match
231 { 'a':'x', 'c':'d'} - no match, incorrect value for label 'a'
232 { 'a' : 'b'} - required label not found
235 for m in metrics_with_labels(path='something.something.sensor',
236 require_labels={ 'label1': 'value1' }):
240 entry = self.
get(path, set())
242 def _is_labels_subset(require_labels, target_labels) -> bool:
243 for req_key, req_val
in require_labels.items():
244 if target_labels.get(req_key,
None) != req_val:
249 if require_labels
is not None:
252 lambda x: _is_labels_subset(
253 require_labels=require_labels,
254 target_labels=x.labels,
265 require_labels: typing.Optional[typing.Dict] =
None,
269 return bool(self.
metrics_at(path, require_labels))
273 other: typing.Mapping[str, typing.Set[Metric]],
275 ignore_zeros: bool =
False,
278 Compares the snapshot with a dict of metrics or with
279 another snapshot, displaying a nice diff on mismatch
281 lhs = _flatten_snapshot(self, ignore_zeros=ignore_zeros)
282 rhs = _flatten_snapshot(other, ignore_zeros=ignore_zeros)
283 assert lhs == rhs, _diff_metric_snapshots(lhs, rhs, ignore_zeros)
287 Multiline linear print:
288 path: (label=value),(label=value) TYPE VALUE
289 path: (label=value),(label=value) TYPE VALUE
292 assert 'some.thing.sensor' in metric, metric.pretty_print()
296 def _iterate_over_mset(path, mset):
297 """print (pretty) one metrics set - for given path"""
301 '{}: {} {} {}'.format(
313 data_for_every_path = [_iterate_over_mset(path, mset)
for path, mset
in self.
_values.
items()]
317 return '\n'.join(itertools.chain(*data_for_every_path))
322 Construct MetricsSnapshot from a JSON string
327 labels=element[
'labels'],
328 value=_parse_metric_value(element[
'value']),
329 _type=MetricType[element.get(
'type',
'UNSPECIFIED')],
331 for element
in metrics_list
333 for path, metrics_list
in json.loads(json_str).
items()
339 Serialize to a JSON string
343 {path: random.sample(list(metrics), len(metrics))
for path, metrics
in self.
_values.
items()},
344 cls=_MetricsJSONEncoder,
348def _type_eq(lhs: MetricType, rhs: MetricType) -> bool:
349 return lhs == rhs
or lhs == MetricType.UNSPECIFIED
or rhs == MetricType.UNSPECIFIED
353 """Returns labels as a tuple of sorted items"""
354 return tuple(sorted(metric.labels.items()))
357def _do_compute_percentile(hist: Histogram, percent: float) -> float:
360 value_lists = [[bound] * bucket
for (bucket, bound)
in zip(hist.buckets, hist.bounds)] + [[math.inf] * hist.inf]
361 values = [item
for sublist
in value_lists
for item
in sublist]
367 pivot = (len(values) - 1) * percent
368 floor = math.floor(pivot)
369 ceil = math.ceil(pivot)
371 return values[int(pivot)]
372 part1 = values[int(floor)] * (ceil - pivot)
373 part2 = values[int(ceil)] * (pivot - floor)
377def _parse_metric_value(value: typing.Any) -> MetricValue:
378 if isinstance(value, dict):
380 bounds=value[
'bounds'],
381 buckets=value[
'buckets'],
384 elif isinstance(value, float):
386 elif isinstance(value, int):
389 raise Exception(f
'Failed to parse metric value from {value!r}')
392_FlattenedSnapshot = typing.Set[typing.Tuple[str, Metric]]
395def _flatten_snapshot(values, ignore_zeros: bool) -> _FlattenedSnapshot:
398 for path, metrics
in values.items()
399 for metric
in metrics
400 if metric.value != 0
or not ignore_zeros
404def _diff_metric_snapshots(
405 lhs: _FlattenedSnapshot,
406 rhs: _FlattenedSnapshot,
409 def extra_metrics_message(extra, base):
411 f
' path={path!r} labels={metric.labels!r} value={metric.value}'
412 for path, metric
in sorted(extra, key=
lambda pair: pair[0])
413 if (path, metric)
not in base
417 lines = [
'left.assert_equals(right, ignore_zeros=True) failed']
419 lines = [
'left.assert_equals(right) failed']
420 actual_extra = extra_metrics_message(lhs, rhs)
422 lines.append(
' extra in left:')
423 lines += actual_extra
425 actual_gt = extra_metrics_message(rhs, lhs)
427 lines.append(
' missing in left:')
430 return '\n'.join(lines)