Testsuite exposes userver metrics written via utils::statistics::Writer and utils::statistics::MetricTag through monitor_client. Configure the monitor listener as in the metrics tutorial and Retrieving Service Statistics and Metrics (Prometheus/Graphite/...) and Default Metrics Description.
For gtest and utils::statistics::Snapshot, see Statistics and Metrics — How to test metrics in testsuite and gtest.
The API docstrings are the source of truth: pytest_userver.client.ClientMonitor and pytest_userver.metrics.MetricsSnapshot.
Choose the method according to what the test checks:
Use metrics(path=...) to retrieve all metrics at one exact path.
Metric paths and labels come from utils::statistics::Writer and the metric's DumpMetric implementation. Indexing a writer appends path components; utils::statistics::Writer::ValueWithLabels attaches labels. Nested path components do not become labels automatically.
For example, utils::statistics::MinMaxAvg emits min, max, and avg as path components, while utils::statistics::Percentile emits a percentile label such as p50.
To inspect the actual paths, labels, types, and values, use pytest_userver.metrics.MetricsSnapshot.pretty_print or include the snapshot in an assertion's failure message.
Metric tag definition and usage:
Checking metrics with a diff:
Retrieve one metric, or allow it to be absent:
Metrics with labels:
The Metric type is hashable and comparable:
Prefer metrics_diff() to resetting shared service state. Resetting is available for metrics with a ResetMetric implementation:
MetricsSnapshot behaves like a mapping from metric paths to sets of Metric objects. Prefer plain equality — pytest shows a useful diff.
The following example constructs expected data and checks several values after slicing:
For from_layered_dict():
A path mapped to an empty set and an absent path compare equal. For a completely empty result, prefer assert not snapshot over comparison with MetricsSnapshot.from_layered_dict({}).
For individual metrics with many labels, direct construction or exact value_at() checks may be clearer.
Large expected snapshots can live in JSON fixtures loaded by the load_json fixture and passed to pytest_userver.metrics.MetricsSnapshot.from_layered_dict. Testsuite looks for these JSON files in static/ directories.
For example, a layered JSON fixture can contain paths with different label structures:
Use complete snapshot equality when unexpected extra metrics should fail the test. Do not weaken such a comparison into a few selected-value checks. Conversely, a test for selected values need not compare every metric in the snapshot.
pytest_userver.metrics.MetricsSnapshot.value_at uses exact matching when labels is supplied: the metric must have exactly those labels combined with any common labels accumulated by slicing. Pass {} to require a metric with only the common labels, or without labels if none were accumulated. If labels is omitted, any labels are accepted, but the path must identify at most one metric. With default, a missing metric returns that value (which may be None); multiple matches still fail.
pytest_userver.metrics.MetricsSnapshot.metrics_at and pytest_userver.metrics.MetricsSnapshot.has_metrics_at use subset matching via require_labels: a metric may have additional labels. The monitor client's labels filter also uses subset matching, including in single_metric() and single_metric_optional(). Both single-metric methods fail if multiple metrics match.
An empty snapshot and a value of zero are different: assert not snapshot proves no matching metrics exist; value_at(path, labels, default=0) == 0 accepts absence or an explicit zero. Choose according to what the test must prove.
Use path='worker.processed' for one exact path. Use prefix='worker.' for a subtree.
prefix is a literal string prefix at the monitor endpoint. A trailing dot establishes a path-segment boundary: prefix='worker.job' can also match worker.jobs, while prefix='worker.job.' selects descendants of worker.job.
To assert that a complete subtree is absent, fetch it with metrics(prefix=...) and use assert not snapshot. Checking only one leaf with single_metric_optional() would miss unexpected sibling metrics.
A broad prefix can include unrelated metrics. Narrow the prefix or fetch once and assert only selected values.
Use pytest_userver.client.ClientMonitor.metrics_diff to isolate the effect of an action from values left by previous tests. The context manager captures the baseline on entry and the current snapshot on exit. Put unrelated setup before the context.
For RATE counters, the diff is the current value minus the baseline. HIST_RATE histograms are subtracted per bucket. By default, GAUGE metrics keep their current absolute values. Pass diff_gauge=True only when gauge subtraction is meaningful.
To check the complete result, compare differ.diff with an expected pytest_userver.metrics.MetricsSnapshot using assert differ.diff == expected. For example, suppose an action processes one request from the primary queue without new errors. The number of active requests after the action is two. With metrics_diff(prefix='worker.') and its default sliced=True, the expected diff includes all these metrics:
| Path in the diff | Labels | Baseline | Current | Diff |
|---|---|---|---|---|
| processed | queue=primary | 3 | 4 | 1 |
| processed | queue=retry | 1 | 1 | 0 |
| errors | queue=retry, reason=timeout | 1 | 1 | 0 |
| active | none | 2 | 2 | 2 |
Here processed and errors are RATE counters; active is a GAUGE. Include the unchanged counters and the current gauge value when comparing the whole diff.
Use pytest_userver.client.MetricsDiffer.fetch_current for intermediate checkpoints. For a lifecycle that does not fit one context, call pytest_userver.client.MetricsDiffer.fetch_baseline before the action and fetch_current() after it. Multiple context managers can measure an action across unrelated metric paths without fetching all metrics.
The diff contains the metrics present in the current snapshot, including unchanged metrics with zero counter deltas. A metric absent from the baseline keeps its current value; a metric absent from the current snapshot is absent from the diff. Use default=0 only when a missing metric should mean zero. To omit zero counters and empty histograms in a snapshot comparison, use pytest_userver.metrics.MetricsSnapshot.without_zero_rates.
Slicing keeps matching metrics and shortens their paths by whole dot-separated segments. It preserves each Metric object, including its full labels, and remembers common labels so subsequent lookups can omit them. Chained calls narrow the snapshot further. pytest_userver.metrics.MetricsSnapshot.unsliced restores full paths for the remaining metrics; it does not restore filtered-out metrics.
metrics(..., sliced=True) slices by the requested path or prefix (with trailing dots removed) and labels. Unlike the endpoint's literal prefix filter, slicing does not match a partial path segment. An exact path becomes ''. When calling snapshot.sliced(prefix, labels) directly, pass a prefix without a trailing dot, such as 'worker'.
metrics_diff() defaults to sliced=True; metrics() defaults to False. This applies to differ.value_at() and to differ.baseline, differ.current, and differ.diff. Pass sliced=False when full paths are clearer. Use slicing when it reduces repetition; a single lookup usually does not need it.
When comparing a sliced snapshot with ==, include the common labels in the expected snapshot too. Use common_labels in pytest_userver.metrics.MetricsSnapshot.from_layered_dict to avoid repeating them.
Some tests call a custom HTTP endpoint instead of monitor_client. If it supports format=json, parse with MetricsSnapshot.from_dict() or from_json(). For Solomon JSON, assert on the flat metrics list (including the sensor label) without changing production behavior. Prefer monitor_client.metrics() when the standard monitor endpoint is available.
Prefer import pytest_userver.metrics and qualified names such as pytest_userver.metrics.MetricsSnapshot. This leaves metrics available for local snapshot variables. from pytest_userver import metrics binds that name to the module, so a local variable named metrics would hide the module.
For metric calls and assertions:
Avoid comments that merely restate the assertion.
Different monitoring systems impose different limits. server::handlers::TestsControl exposes a portability check:
Call pytest_userver.client.Client.metrics_portability and assert that the returned warnings are empty.
Warnings are grouped by type; filter selectively: