:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(ci): recover missing pytest ownership paths (#84237)
Paul D'Ambra564468b2ec85
diff --git a/.github/scripts/report_test_timings.py b/.github/scripts/report_test_timings.pyindex 336ec498f235..fb4df0a9b6f1 100644--- a/.github/scripts/report_test_timings.py+++ b/.github/scripts/report_test_timings.py@@ -69,6 +69,16 @@ from posthog_owners import OwnersResolverlogger = logging.getLogger("report_test_timings")++def find_repo_root(path: Path) -> Path:+ """Find the checkout root without depending on this script's directory depth."""+ for parent in path.resolve().parents:+ if (parent / "owners.yaml").is_file() and (parent / ".github").is_dir():+ return parent+ raise RuntimeError(f"Could not find the repository root from {path}")+++REPO_ROOT = find_repo_root(Path(__file__))DEFAULT_OTLP_ENDPOINT = "https://us.i.posthog.com/i/v1/traces"Runner = Literal["pytest", "jest"]@@ -92,8 +102,9 @@ class TestCase:end: datetimeoutcome: str # passed | failed | error | skipped | xfailed | rerun_passedattempts: int # 1 + number of pytest-rerunfailures retries before final outcome- file: str # normalized repo-relative test file; '' when JUnit omitted or escaped the repo- selector: str # runnable runner-specific selector; '' when JUnit omitted the file+ file: str # normalized repo-relative test file; '' when no checked-in file can be found+ file_source: Literal["junit", "inferred", "missing"]+ selector: str # runnable runner-specific selector; '' when the file cannot be found@dataclass(frozen=True)@@ -281,15 +292,41 @@ def normalize_jest_file(file: str) -> str:return normalized-def test_identity(runner: Runner, file: str, classname: str, name: str) -> tuple[str, str, str]:- """Return normalized (file, stable id, runnable selector) for one runner's JUnit shape."""+def infer_pytest_file(classname: str) -> str:+ """Find a safe pytest file path from a JUnit classname."""+ parts = classname.split(".")+ if not parts or any(not part or "/" in part or "\\" in part for part in parts):+ return ""++ for module_length in range(len(parts), 0, -1):+ candidate = REPO_ROOT.joinpath(*parts[:module_length]).with_suffix(".py")+ if candidate.is_file():+ return candidate.relative_to(REPO_ROOT).as_posix()++ for module_length, part in enumerate(parts, start=1):+ if part.startswith("test_") or part.endswith("_test"):+ return Path(*parts[:module_length]).with_suffix(".py").as_posix()+ return ""+++def test_identity(+ runner: Runner, file: str, classname: str, name: str+) -> tuple[str, str, str, Literal["junit", "inferred", "missing"]]:+ """Return normalized file, stable id, selector, and file source for one runner's JUnit shape."""if runner == "jest":normalized_file = normalize_jest_file(file)selector = f"{normalized_file}::{name}" if normalized_file and name else ""- return normalized_file, selector or name, selector- # Products run pytest with `--rootdir ../..`, so `file`/`classname` are already- # repo-relative (`products/<name>/...`) — no prefixing needed here.- return file, to_pytest_nodeid(classname, name), to_pytest_selector(file, classname, name)+ file_source: Literal["junit", "inferred", "missing"] = "junit" if normalized_file else "missing"+ return normalized_file, selector or name, selector, file_source++ normalized_file = file or infer_pytest_file(classname)+ file_source = "junit" if file else "inferred" if normalized_file else "missing"+ return (+ normalized_file,+ to_pytest_nodeid(classname, name),+ to_pytest_selector(normalized_file, classname, name),+ file_source,+ )def product_name(junit_filename: str) -> str:@@ -432,7 +469,7 @@ def parse_shard(for tc in suite_elem.iter("testcase"):classname = tc.get("classname", "")name = tc.get("name", "")- file, nodeid, selector = test_identity(runner, tc.get("file", ""), classname, name)+ file, nodeid, selector, file_source = test_identity(runner, tc.get("file", ""), classname, name)outcome, attempts = classify_testcase(tc)if outcome == "passed" and nodeid in quarantined_test_ids:outcome = "xfailed"@@ -455,6 +492,7 @@ def parse_shard(classname=classname,name=name,file=file,+ file_source=file_source,selector=selector,duration_seconds=duration,start=test_start,@@ -760,6 +798,9 @@ def _emit_shard_span(test_span.set_attribute("test.attempts", test.attempts)test_span.set_attribute("test.classname", test.classname)test_span.set_attribute("test.name", test.name)+ if test.file:+ test_span.set_attribute("test.file", test.file)+ test_span.set_attribute("test.file_source", test.file_source)if test.selector:test_span.set_attribute("test.selector", test.selector)owner_team = owner_of(test.file)diff --git a/.github/scripts/test_report_test_timings.py b/.github/scripts/test_report_test_timings.pyindex dc73a00c4232..9e9d3fdb5f70 100644--- a/.github/scripts/test_report_test_timings.py+++ b/.github/scripts/test_report_test_timings.py@@ -37,6 +37,7 @@ def _testcase(classname="m",name=name,file=file,+ file_source="junit",selector=f"m.py::{name}",duration_seconds=duration,start=test_start,@@ -69,6 +70,80 @@ def test_to_pytest_selector(file: str, classname: str, name: str, expected: str)assert report_test_timings.to_pytest_selector(file, classname, name) == expected+def test_find_repo_root_walks_to_repository_markers(tmp_path: Path) -> None:+ repo_root = tmp_path / "repo"+ script = repo_root / ".github/scripts/report_test_timings.py"+ script.parent.mkdir(parents=True)+ script.touch()+ (repo_root / "owners.yaml").touch()++ assert report_test_timings.find_repo_root(script) == repo_root+++def test_test_identity_infers_existing_pytest_file_when_junit_omits_it(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ test_file = tmp_path / "products/approvals/backend/tests/test_approvals_api.py"+ test_file.parent.mkdir(parents=True)+ test_file.touch()+ monkeypatch.setattr(report_test_timings, "REPO_ROOT", tmp_path)++ file, nodeid, selector, file_source = report_test_timings.test_identity(+ "pytest",+ "",+ "products.approvals.backend.tests.test_approvals_api.TestApprovalsFeatureGating",+ "test_accessible",+ )++ assert file == "products/approvals/backend/tests/test_approvals_api.py"+ assert nodeid == "products/approvals/backend/tests/test_approvals_api/TestApprovalsFeatureGating::test_accessible"+ assert (+ selector+ == "products/approvals/backend/tests/test_approvals_api.py::TestApprovalsFeatureGating::test_accessible"+ )+ assert file_source == "inferred"+++ "classname,file_exists,expected",+ [+ (+ "products.logs.skills.authoring-log-alerts.tests.test_baseline_stats.TestBaselineStats",+ True,+ "products/logs/skills/authoring-log-alerts/tests/test_baseline_stats.py",+ ),+ (+ "products.approvals.backend.tests.test_new_api.TestNewAPI",+ False,+ "products/approvals/backend/tests/test_new_api.py",+ ),+ ],+)+def test_infer_pytest_file_supports_safe_test_paths(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ classname: str,+ file_exists: bool,+ expected: str,+) -> None:+ monkeypatch.setattr(report_test_timings, "REPO_ROOT", tmp_path)+ if file_exists:+ test_file = tmp_path / expected+ test_file.parent.mkdir(parents=True)+ test_file.touch()++ assert report_test_timings.infer_pytest_file(classname) == expected+++def test_infer_pytest_file_rejects_path_traversal(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ repo_root = tmp_path / "repo"+ repo_root.mkdir()+ (tmp_path / "secret.py").touch()+ monkeypatch.setattr(report_test_timings, "REPO_ROOT", repo_root)++ assert report_test_timings.infer_pytest_file("products/../../secret") == ""++# ---------- artifact name parsing ----------@@ -675,7 +750,11 @@ def test_emit_shard_span_stamps_owner_team_only_for_owned_files(monkeypatch: pytowners = {"products/x/test_a.py": "team-devex"}report_test_timings._emit_shard_span(tracer, shard, "Backend CI / core (1)", lambda f: owners.get(f, ""))+ assert tracer.spans[1].attributes["test.file"] == "products/x/test_a.py"+ assert tracer.spans[1].attributes["test.file_source"] == "junit"assert tracer.spans[1].attributes["test.owner_team"] == "team-devex"+ assert tracer.spans[2].attributes["test.file"] == "stray/test_b.py"+ assert tracer.spans[2].attributes["test.file_source"] == "junit"assert "test.owner_team" not in tracer.spans[2].attributes