|
1 | 1 | """Unit tests for Prometheus metric recording helpers.""" |
2 | 2 |
|
3 | | -from pytest_mock import MockerFixture |
| 3 | +from collections.abc import Callable |
| 4 | +from dataclasses import dataclass |
| 5 | + |
| 6 | +import pytest |
| 7 | +from pytest_mock import MockerFixture, MockType |
4 | 8 |
|
5 | 9 | from metrics import recording |
6 | 10 |
|
7 | 11 |
|
| 12 | +@dataclass(frozen=True) |
| 13 | +class HistogramRecorderCase: |
| 14 | + """Expected behavior for a histogram-style metric recorder.""" |
| 15 | + |
| 16 | + metric_path: str |
| 17 | + recorder: Callable[..., None] |
| 18 | + args: tuple[object, ...] |
| 19 | + labels: tuple[object, ...] |
| 20 | + duration: float |
| 21 | + warning_message: str |
| 22 | + |
| 23 | + |
8 | 24 | def test_measure_response_duration_records_timer(mocker: MockerFixture) -> None: |
9 | 25 | """Test that response duration measurement uses the path label timer.""" |
10 | 26 | mock_timer = mocker.MagicMock() |
@@ -159,3 +175,44 @@ def test_record_llm_token_usage_logs_metric_errors(mocker: MockerFixture) -> Non |
159 | 175 | mock_logger.warning.assert_called_once_with( |
160 | 176 | "Failed to update token metrics", exc_info=True |
161 | 177 | ) |
| 178 | + |
| 179 | + |
| 180 | +@pytest.fixture(name="recording_logger") |
| 181 | +def recording_logger_fixture(mocker: MockerFixture) -> MockType: |
| 182 | + """Patch the metric recording logger for failure assertions.""" |
| 183 | + return mocker.patch("metrics.recording.logger") |
| 184 | + |
| 185 | + |
| 186 | +@pytest.mark.parametrize( |
| 187 | + "case", |
| 188 | + [ |
| 189 | + HistogramRecorderCase( |
| 190 | + metric_path="metrics.recording.metrics.llm_inference_duration_seconds", |
| 191 | + recorder=recording.record_llm_inference_duration, |
| 192 | + args=("vertexai", "gemini", "/v1/responses", "success", 1.5), |
| 193 | + labels=("vertexai", "gemini", "/v1/responses", "success"), |
| 194 | + duration=1.5, |
| 195 | + warning_message="Failed to update LLM inference duration metric", |
| 196 | + ), |
| 197 | + ], |
| 198 | +) |
| 199 | +def test_histogram_recorders_observe_metrics_and_log_errors( |
| 200 | + mocker: MockerFixture, |
| 201 | + recording_logger: MockType, |
| 202 | + case: HistogramRecorderCase, |
| 203 | +) -> None: |
| 204 | + """Test new histogram helpers with shared success and failure coverage.""" |
| 205 | + mock_metric = mocker.patch(case.metric_path) |
| 206 | + |
| 207 | + case.recorder(*case.args) |
| 208 | + |
| 209 | + mock_metric.labels.assert_called_once_with(*case.labels) |
| 210 | + mock_metric.labels.return_value.observe.assert_called_once_with(case.duration) |
| 211 | + |
| 212 | + mock_metric.reset_mock() |
| 213 | + mock_metric.labels.return_value.observe.side_effect = TypeError("bad") |
| 214 | + case.recorder(*case.args) |
| 215 | + |
| 216 | + recording_logger.warning.assert_called_once_with( |
| 217 | + case.warning_message, exc_info=True |
| 218 | + ) |
0 commit comments