The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
refactor(e2e): replace bespoke result reporter with standard JUnit report (#33758)
Yassin Kortam71e02513415d
diff --git a/tests/e2e/conftest.py b/tests/e2e/conftest.pyindex 3aec104c861..22b248b24da 100644--- a/tests/e2e/conftest.py+++ b/tests/e2e/conftest.py@@ -15,14 +15,14 @@ shared fixtures build on it.import functoolsimport sys-from collections.abc import Generator, Iterator+from collections.abc import Iteratorfrom pathlib import Pathimport pytestimport requestsfrom e2e_config import CONTROL_PLANE_BASE_URL, PROXY_BASE_URL-from e2e_result_reporter import covers_from_item, format_e2e_result_line, result_from_pytest+from junit_properties import attach_result_propertiesfrom lifecycle import GatewayProvider, ResourceManager@@ -40,6 +40,17 @@ def pytest_configure(config: pytest.Config) -> None:)+def pytest_collection_modifyitems(items: list[pytest.Item]) -> None:+ """Attach the two custom signals (suite package and covered cell ids) to every+ test's user_properties so the standard JUnit report (`--junitxml`) records them+ as `<property>` entries, on every outcome including skips and setup errors.+ Downstream (Loki/Grafana) reads outcome and duration from the standard report+ and these properties for package rollups and coverage drill-down. See+ junit_properties.py."""+ for item in items:+ attach_result_properties(item)++def _liveness_reason(label: str, base_url: str) -> str | None:"""None if `base_url` answers its liveness probe, else a failure reason."""try:@@ -86,30 +97,6 @@ def pytest_runtest_call(item: pytest.Item) -> None:item.session.stash[_E2E_TEST_RAN] = True[email protected](wrapper=True, tryfirst=True)-def pytest_runtest_makereport(- item: pytest.Item, call: pytest.CallInfo[object]-) -> Generator[None, pytest.TestReport, pytest.TestReport]:- """Emit one structured E2E_RESULT line per finished test for Loki/Grafana.-- Status-history panels should aggregate by package (and optional covers), not- scrape pytest progress basenames. See e2e_result_reporter.py.- """- report = yield- result = result_from_pytest(- nodeid=str(report.nodeid),- when=str(report.when),- failed=bool(report.failed),- skipped=bool(report.skipped),- passed=bool(report.passed),- duration_seconds=float(report.duration),- covers=covers_from_item(item),- )- if result is not None:- print(format_e2e_result_line(result), flush=True)- return report--def pytest_sessionfinish(session: pytest.Session, exitstatus: int) -> None:"""Once the whole e2e session is done (all suites), truncate the spend logs sothe DB doesn't accumulate test rows. Sessions where no e2e test body ran leavediff --git a/tests/e2e/e2e_result_reporter.py b/tests/e2e/e2e_result_reporter.pydeleted file mode 100644index 22f7581818f..00000000000--- a/tests/e2e/e2e_result_reporter.py+++ /dev/null@@ -1,144 +0,0 @@-"""Structured e2e result lines for Loki / Grafana status history.--Pytest progress lines are a bad dashboard source: they only expose file basenames,-break under quiet modes, and force status-history rows to explode with suite growth.--Each finished test emits one logfmt line:-- E2E_RESULT package=logging file=test_langfuse_e2e.py outcome=failed- duration_ms=1234 node_id=logging/test_langfuse_e2e.py::TestX::test_y- covers=logging.langfuse.team.success--Grafana package status-history queries max(fail) by package over E2E_RESULT lines.-Drill-down uses node_id / covers in Explore, not status-history cardinality.-"""--from __future__ import annotations--from collections.abc import Iterable, Sequence-from dataclasses import dataclass-from pathlib import Path-from typing import Literal, Protocol, runtime_checkable--Outcome = Literal["passed", "failed", "error", "skipped"]---@dataclass(frozen=True, slots=True)-class E2EResult:- package: str- file: str- outcome: Outcome- duration_ms: int- node_id: str- covers: tuple[str, ...]---@runtime_checkable-class _MarkerArgs(Protocol):- args: Sequence[object]---@runtime_checkable-class _ItemWithCovers(Protocol):- def iter_markers(self, name: str) -> Iterable[object]: ...---def package_from_nodeid(nodeid: str) -> str:- """Top-level suite package under tests/e2e/, or 'root' for top-level files.-- Pytest nodeids are relative to the invocation cwd. Repo-root runs look like- `tests/e2e/logging/...`; suite-cwd runs look like `logging/...`. Strip the- `tests/e2e` prefix so package is the suite dir either way.- """- path_part = nodeid.split("::", 1)[0].replace("\\", "/")- parts = tuple(p for p in path_part.split("/") if p and p != ".")- if len(parts) >= 3 and parts[0] == "tests" and parts[1] == "e2e":- parts = parts[2:]- if len(parts) <= 1:- return "root"- return parts[0]---def file_from_nodeid(nodeid: str) -> str:- path_part = nodeid.split("::", 1)[0].replace("\\", "/")- return Path(path_part).name---def covers_from_item(item: object) -> tuple[str, ...]:- """Read @pytest.mark.covers cell ids from a pytest Item."""- if not isinstance(item, _ItemWithCovers):- return ()- return tuple(- dict.fromkeys(- arg- for marker in item.iter_markers(name="covers")- if isinstance(marker, _MarkerArgs)- for arg in marker.args- if isinstance(arg, str) and arg- )- )---def outcome_from_report(when: str, failed: bool, skipped: bool, passed: bool) -> Outcome | None:- """Map pytest TestReport fields to a terminal outcome. None if not final."""- if when == "setup" and skipped:- return "skipped"- if when == "setup" and failed:- return "error"- if when != "call":- return None- if skipped:- return "skipped"- if failed:- return "failed"- if passed:- return "passed"- return "failed"---def _logfmt_escape(value: str) -> str:- if value == "":- return '""'- needs_quote = any(ch.isspace() or ch in "\"=\\" for ch in value)- if not needs_quote:- return value- escaped = value.replace("\\", "\\\\").replace('"', '\\"')- return f'"{escaped}"'---def format_e2e_result_line(result: E2EResult) -> str:- covers = ",".join(result.covers)- fields = (- ("package", result.package),- ("file", result.file),- ("outcome", result.outcome),- ("duration_ms", str(result.duration_ms)),- ("node_id", result.node_id),- ("covers", covers),- )- body = " ".join(f"{key}={_logfmt_escape(value)}" for key, value in fields)- return f"E2E_RESULT {body}"---def result_from_pytest(- *,- nodeid: str,- when: str,- failed: bool,- skipped: bool,- passed: bool,- duration_seconds: float,- covers: tuple[str, ...] = (),-) -> E2EResult | None:- outcome = outcome_from_report(when=when, failed=failed, skipped=skipped, passed=passed)- if outcome is None:- return None- duration_ms = max(0, int(round(duration_seconds * 1000)))- return E2EResult(- package=package_from_nodeid(nodeid),- file=file_from_nodeid(nodeid),- outcome=outcome,- duration_ms=duration_ms,- node_id=nodeid,- covers=covers,- )diff --git a/tests/e2e/junit_properties.py b/tests/e2e/junit_properties.pynew file mode 100644index 00000000000..e4f59f5c4d2--- /dev/null+++ b/tests/e2e/junit_properties.py@@ -0,0 +1,59 @@+"""Custom per-test signals for the standard JUnit reporter.++The e2e suite ships results to Loki/Grafana from a standard pytest JUnit report+(`--junitxml=e2e-report.xml`), not a bespoke log line. JUnit already records+outcome, duration, and node id for every `<testcase>`; the only signals it cannot+derive on its own are the normalized suite package and the coverage-registry cell+ids a test covers. Those ride along as JUnit `<property>` entries via each item's+`user_properties`, attached in `conftest.py::pytest_collection_modifyitems`.+"""++from __future__ import annotations++from collections.abc import Iterable++import pytest+++def package_from_nodeid(nodeid: str) -> str:+ """Top-level suite package under tests/e2e/, or 'root' for top-level files.++ Pytest nodeids are relative to the invocation cwd. Repo-root runs look like+ `tests/e2e/logging/...`; suite-cwd runs look like `logging/...`. Strip the+ `tests/e2e` prefix so package is the suite dir either way.+ """+ path_part = nodeid.split("::", 1)[0].replace("\\", "/")+ raw = tuple(p for p in path_part.split("/") if p and p != ".")+ parts = raw[2:] if len(raw) >= 3 and raw[0] == "tests" and raw[1] == "e2e" else raw+ if len(parts) <= 1:+ return "root"+ return parts[0]+++def dedupe_covers(marker_args: Iterable[tuple[object, ...]]) -> tuple[str, ...]:+ """Flatten @pytest.mark.covers arg lists into unique, order-preserving cell+ ids, dropping anything that is not a non-empty string."""+ return tuple(dict.fromkeys(arg for args in marker_args for arg in args if isinstance(arg, str) and arg))+++def covers_from_item(item: pytest.Item) -> tuple[str, ...]:+ """Read @pytest.mark.covers cell ids off a pytest Item, order-preserving."""+ return dedupe_covers(marker.args for marker in item.iter_markers(name="covers"))+++def result_properties(item: pytest.Item) -> tuple[tuple[str, str], ...]:+ """The custom signals a standard reporter cannot derive: the normalized suite+ package and the comma-joined coverage-registry cell ids this test covers."""+ return (+ ("package", package_from_nodeid(item.nodeid)),+ ("covers", ",".join(covers_from_item(item))),+ )+++def attach_result_properties(item: pytest.Item) -> None:+ """Attach result_properties to an item's user_properties, idempotently: a+ second call is a no-op, so a collection that runs the hook more than once+ never emits duplicate <property> entries."""+ if any(name == "package" for name, _ in item.user_properties):+ return+ item.user_properties.extend(result_properties(item))