|
10 | 10 | import asyncio |
11 | 11 | import contextlib |
12 | 12 | import logging |
| 13 | +import re |
13 | 14 | import socket |
| 15 | +from collections.abc import Iterator |
14 | 16 | from typing import Any, cast |
15 | 17 | from unittest.mock import MagicMock |
16 | 18 |
|
17 | 19 | import pytest |
18 | 20 | from deadline_budget import DeadlineExceededError |
19 | 21 | from fastapi import APIRouter, FastAPI, HTTPException |
20 | 22 | from fastapi.testclient import TestClient |
21 | | -from prometheus_client import CollectorRegistry |
| 23 | +from prometheus_client import REGISTRY, CollectorRegistry |
22 | 24 | from prometheus_fastapi_instrumentator import metrics |
23 | 25 |
|
24 | 26 | from servicewright import ( |
@@ -764,6 +766,17 @@ class MyMiddleware(BaseHTTPMiddleware): |
764 | 766 | # --------------------------------------------------------------------------- # |
765 | 767 | # Metrics |
766 | 768 | # --------------------------------------------------------------------------- # |
| 769 | +@pytest.fixture |
| 770 | +def default_registry() -> Iterator[None]: |
| 771 | + # metrics=True instruments into the process-wide REGISTRY, where a second |
| 772 | + # instrumented app would collide on the same series: drop what the test added. |
| 773 | + registered_before = set(REGISTRY._collector_to_names) |
| 774 | + yield |
| 775 | + for collector in set(REGISTRY._collector_to_names) - registered_before: |
| 776 | + REGISTRY.unregister(collector) |
| 777 | + |
| 778 | + |
| 779 | +@pytest.mark.usefixtures("default_registry") |
767 | 780 | async def test__metrics_endpoint__enabled__is_exposed() -> None: |
768 | 781 | ep = FastApiEntrypoint(config=HttpConfig(port=0), metrics=True) |
769 | 782 | client = await _build_client(ep, _make_service_ctx(FakeContainer())) |
@@ -811,20 +824,81 @@ def _private_registry_config(registry: CollectorRegistry, **fields: Any) -> Metr |
811 | 824 | ) |
812 | 825 |
|
813 | 826 |
|
814 | | -async def _build_instrumented_client(config: MetricsInstrumentatorConfig) -> TestClient: |
| 827 | +def _ping_router() -> APIRouter: |
815 | 828 | router = APIRouter() |
816 | 829 |
|
817 | 830 | @router.get("/ping") |
818 | 831 | async def ping() -> dict[str, str]: |
819 | 832 | return {"pong": "ok"} |
820 | 833 |
|
| 834 | + return router |
| 835 | + |
| 836 | + |
| 837 | +async def _build_instrumented_client(config: MetricsInstrumentatorConfig) -> TestClient: |
821 | 838 | def configure(app: FastAPI, ctx: ServiceContext) -> None: |
822 | 839 | setup_metrics_instrumentator(app, config=config) |
823 | 840 |
|
824 | | - ep = FastApiEntrypoint(config=HttpConfig(port=0), routers=(router,), configure_app=configure) |
| 841 | + ep = FastApiEntrypoint(config=HttpConfig(port=0), routers=(_ping_router(),), configure_app=configure) |
825 | 842 | return await _build_client(ep, _make_service_ctx(FakeContainer())) |
826 | 843 |
|
827 | 844 |
|
| 845 | +async def _metrics_after_one_ping(ep: FastApiEntrypoint) -> str: |
| 846 | + client = await _build_client(ep, _make_service_ctx(FakeContainer())) |
| 847 | + client.get("/ping") |
| 848 | + return client.get("/system/metrics").text |
| 849 | + |
| 850 | + |
| 851 | +def _ping_latency_buckets(metrics_body: str) -> list[str]: |
| 852 | + return re.findall( |
| 853 | + r'^http_request_duration_seconds_bucket\{handler="/ping",le="([^"]+)",method="GET"\}', |
| 854 | + metrics_body, |
| 855 | + re.MULTILINE, |
| 856 | + ) |
| 857 | + |
| 858 | + |
| 859 | +@pytest.fixture |
| 860 | +def long_request_metrics(metrics_registry: CollectorRegistry) -> MetricsInstrumentatorConfig: |
| 861 | + return _private_registry_config(metrics_registry, instrument_kwargs={"latency_lowr_buckets": (1, 60, 600)}) |
| 862 | + |
| 863 | + |
| 864 | +async def test__metrics_endpoint__instrumentator_config_given__uses_its_latency_buckets( |
| 865 | + long_request_metrics: MetricsInstrumentatorConfig, |
| 866 | +) -> None: |
| 867 | + # Arrange |
| 868 | + ep = FastApiEntrypoint(config=HttpConfig(port=0), routers=(_ping_router(),), metrics=long_request_metrics) |
| 869 | + |
| 870 | + # Act |
| 871 | + body = await _metrics_after_one_ping(ep) |
| 872 | + |
| 873 | + # Assert |
| 874 | + assert _ping_latency_buckets(body) == ["1.0", "60.0", "600.0", "+Inf"] |
| 875 | + |
| 876 | + |
| 877 | +async def test__fastapi_plugin__instrumentator_config_given__forwards_it_to_the_entrypoint( |
| 878 | + long_request_metrics: MetricsInstrumentatorConfig, |
| 879 | +) -> None: |
| 880 | + # Arrange |
| 881 | + plugin = FastApiPlugin(config=HttpConfig(port=0), routers=(_ping_router(),), metrics=long_request_metrics) |
| 882 | + |
| 883 | + # Act |
| 884 | + body = await _metrics_after_one_ping(plugin.entrypoint) |
| 885 | + |
| 886 | + # Assert |
| 887 | + assert _ping_latency_buckets(body) == ["1.0", "60.0", "600.0", "+Inf"] |
| 888 | + |
| 889 | + |
| 890 | +@pytest.mark.usefixtures("default_registry") |
| 891 | +async def test__metrics_endpoint__enabled__keeps_the_default_latency_buckets() -> None: |
| 892 | + # Arrange |
| 893 | + ep = FastApiEntrypoint(config=HttpConfig(port=0), routers=(_ping_router(),), metrics=True) |
| 894 | + |
| 895 | + # Act |
| 896 | + body = await _metrics_after_one_ping(ep) |
| 897 | + |
| 898 | + # Assert |
| 899 | + assert _ping_latency_buckets(body) == ["0.1", "0.5", "1.0", "+Inf"] |
| 900 | + |
| 901 | + |
828 | 902 | async def test__metrics_instrumentator__instrumentations_configured__emit_their_series( |
829 | 903 | metrics_registry: CollectorRegistry, |
830 | 904 | ) -> None: |
|
0 commit comments