atlasbot/scripts/publish_test_metrics.py

60 lines
1.7 KiB
Python

import os
import time
import xml.etree.ElementTree as ET
import httpx
VM_URL = os.getenv("VM_PUSH_URL", "http://victoria-metrics-single-server.monitoring.svc.cluster.local:8428/api/v1/import/prometheus")
JUNIT_PATH = os.getenv("JUNIT_PATH", "build/junit.xml")
COVERAGE_PATH = os.getenv("COVERAGE_PATH", "build/coverage.json")
JOB = os.getenv("TEST_JOB", "atlasbot-tests")
def _load_junit(path: str) -> dict[str, float]:
tree = ET.parse(path)
root = tree.getroot()
tests = int(root.attrib.get("tests", "0"))
failures = int(root.attrib.get("failures", "0"))
errors = int(root.attrib.get("errors", "0"))
time_sec = float(root.attrib.get("time", "0"))
return {
"tests": tests,
"failures": failures,
"errors": errors,
"time": time_sec,
}
def _load_coverage(path: str) -> float:
try:
import json
data = json.load(open(path))
total = data.get("summary", {}).get("percent_covered", 0)
return float(total) / 100.0
except Exception:
return 0.0
def _format_metric(name: str, value: float) -> str:
return f"{name}{{job=\"{JOB}\"}} {value} {int(time.time())}"
def main() -> None:
junit = _load_junit(JUNIT_PATH)
coverage = _load_coverage(COVERAGE_PATH)
lines = [
_format_metric("atlasbot_tests_total", junit["tests"]),
_format_metric("atlasbot_tests_failed", junit["failures"]),
_format_metric("atlasbot_tests_errors", junit["errors"]),
_format_metric("atlasbot_tests_time_seconds", junit["time"]),
_format_metric("atlasbot_coverage_ratio", coverage),
]
body = "\n".join(lines) + "\n"
httpx.post(VM_URL, content=body, timeout=10.0)
print("metrics push complete")
if __name__ == "__main__":
main()