#!/usr/bin/env python3 # -*- coding: utf-8 -*- """作业 8 · 解析自测(不连外网)。""" from __future__ import annotations import sys import _bootstrap # noqa: F401 from 作业8_sla_metrics import ( SLA_TARGETS, collect_sla, kb_accuracy_ratio, mttr_minutes, percentile, ) def test_percentile() -> None: assert percentile([1.0, 2.0, 3.0, 4.0, 5.0], 99) == 4.96 assert percentile([], 99) is None def test_kb_and_mttr_defaults() -> None: kb = kb_accuracy_ratio() assert kb["value"] >= SLA_TARGETS["kb_accuracy_ratio"] mttr = mttr_minutes() assert mttr["value"] <= SLA_TARGETS["mttr_minutes"] def test_collect_with_mock_http() -> None: def fake_get(url: str) -> str: if "traces" in url: return '{"data":[{"id":"t1","latency":3.5}]}' if "observations" in url: return '{"data":[{"type":"GENERATION","startTime":"2026-01-01T00:00:00Z","completionStartTime":"2026-01-01T00:00:01Z","endTime":"2026-01-01T00:00:03Z"}]}' return "{}" snap = collect_sla(http_get=fake_get) assert snap["first_token_p99_seconds"] <= SLA_TARGETS["first_token_p99_seconds"] assert snap["full_response_p99_seconds"] <= SLA_TARGETS["full_response_p99_seconds"] assert snap["sla_pass"]["kb_accuracy"] is True def test_format_metrics() -> None: from 作业8_sla_exporter import format_metrics body = format_metrics( { "availability_ratio": 0.9995, "first_token_p99_seconds": 1.2, "full_response_p99_seconds": 6.0, "kb_accuracy_ratio": 0.875, "mttr_minutes": 18, "health": {"dify": True, "vllm": True}, "latency_meta": {"source": "simulated"}, "sla_pass": {"availability": True}, } ) assert "ai_platform_availability_ratio" in body assert "ai_sla_first_token_latency_p99_seconds" in body assert 'name="Dify"' in body assert 'name="vLLM"' in body def main() -> int: test_percentile() test_kb_and_mttr_defaults() test_collect_with_mock_http() test_format_metrics() print("[PASS] 作业8 解析自测") return 0 if __name__ == "__main__": sys.exit(main())