| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- import asyncio
- import httpx
- import pytest
- from prometheus_client.parser import text_string_to_metric_families
- from test_after_sales import scenario # noqa: F401
- from zhifu.core.telemetry import heartbeat
- from zhifu.monitoring.api import app
- pytestmark = pytest.mark.integration
- def samples(payload):
- return [
- sample for family in text_string_to_metric_families(payload) for sample in family.samples
- ]
- async def test_http_metric_templates_exclude_identity(scenario): # noqa: F811
- for _ in range(3):
- response = await scenario["call"]("GET", f"/openapi/v1/orders?store_id={scenario['store']}")
- assert response.status_code == 200
- response = await scenario["client"].get("/metrics")
- assert response.status_code == 200
- counters = [
- sample
- for sample in samples(response.text)
- if sample.name == "http_requests_total"
- and sample.labels.get("handler") == "/openapi/v1/orders"
- ]
- assert len(counters) == 1 and counters[0].value == 3
- assert str(scenario["tenant"]) not in response.text
- assert str(scenario["store"]) not in response.text
- assert scenario["headers"]["customer"]["Authorization"] not in response.text
- @pytest.mark.parametrize("role", ["agent", "channel-delivery"])
- async def test_heartbeat_and_real_database_metrics(scenario, role): # noqa: F811
- async with app.router.lifespan_context(app):
- async with httpx.AsyncClient(
- transport=httpx.ASGITransport(app=app), base_url="http://monitor"
- ) as client:
- initial = await client.get("/metrics")
- assert initial.status_code == 200
- before = next(
- sample.value for sample in samples(initial.text)
- if sample.name == "zhifu_workers_alive" and sample.labels == {"role": role}
- )
- async with heartbeat(role):
- response = await client.get("/metrics")
- assert response.status_code == 200, response.text
- values = samples(response.text)
- live = [
- sample.value
- for sample in values
- if sample.name == "zhifu_workers_alive" and sample.labels == {"role": role}
- ]
- assert live == [before + 1]
- assert any(
- sample.name == "zhifu_pending_jobs"
- and sample.labels == {"kind": "outbox"}
- and sample.value > 0
- for sample in values
- )
- await asyncio.sleep(0)
- response = await client.get("/metrics")
- values = samples(response.text)
- assert any(
- sample.name == "zhifu_workers_alive"
- and sample.labels == {"role": role}
- and sample.value == before
- for sample in values
- )
|