Skip to content

: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.

chore(eng-analytics): harden and trim test suites (#83054)

Raúl Negrón-Oteroe50f8d245ccf
diff --git a/products/engineering_analytics/backend/tests/_github_fixtures.py b/products/engineering_analytics/backend/tests/_github_fixtures.py
index b82da0950510..d915190b465c 100644
--- a/products/engineering_analytics/backend/tests/_github_fixtures.py
+++ b/products/engineering_analytics/backend/tests/_github_fixtures.py
@@ -1,8 +1,11 @@
"""GitHub source and warehouse-table fixtures shared across this product's test files."""
+import os
import json
import zlib
import tempfile
+from collections.abc import Iterator
+from contextlib import contextmanager
from pathlib import Path
from typing import Any
@@ -30,6 +33,18 @@ TEST_BUCKET = "test_storage_bucket-posthog.products.engineering_analytics.github
GITHUB_SOURCE_PREFIX = "myprefix"
+@contextmanager
+def seeding_object_storage(test: BaseTest) -> Iterator[None]:
+ # Skipping locally keeps the suite usable without the dev stack; skipping in CI would drop every
+ # warehouse-backed assertion behind a green job, so there it raises.
+ try:
+ yield
+ except PermissionError as err:
+ if os.environ.get("CI"):
+ raise
+ test.skipTest(f"object storage unavailable: {err}")
+
+
def create_github_source(
team: Team, *, prefix: str = GITHUB_SOURCE_PREFIX, source_id: str = "gh-source", repository: str = ""
) -> ExternalDataSource:
@@ -219,14 +234,13 @@ def _run_row(
def create_github_warehouse_table(test: BaseTest, base_name: str, columns: dict, rows: list[dict[str, Any]]) -> str:
# Returns the real table name (prefixed), which the builder is then told to read,
- # proving build_query honors the resolved name instead of a hardcoded one. Skips the
- # calling test when object storage is unreachable so the suite runs without the dev stack.
+ # proving build_query honors the resolved name instead of a hardcoded one.
df = pd.DataFrame(rows, columns=list(columns.keys()))
tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False)
df.to_csv(tmp.name, index=False)
tmp.close()
test.addCleanup(Path(tmp.name).unlink, missing_ok=True)
- try:
+ with seeding_object_storage(test):
table, _source, _credential, _df, cleanup = create_data_warehouse_table_from_csv(
csv_path=Path(tmp.name),
table_name=base_name,
@@ -235,7 +249,5 @@ def create_github_warehouse_table(test: BaseTest, base_name: str, columns: dict,
team=test.team,
source_prefix=GITHUB_SOURCE_PREFIX,
)
- except PermissionError as err:
- test.skipTest(f"object storage unavailable: {err}")
test.addCleanup(cleanup)
return table.name
diff --git a/products/engineering_analytics/backend/tests/_logic_helpers.py b/products/engineering_analytics/backend/tests/_logic_helpers.py
index ed8546bb3abf..4ad7e0cda3f3 100644
--- a/products/engineering_analytics/backend/tests/_logic_helpers.py
+++ b/products/engineering_analytics/backend/tests/_logic_helpers.py
@@ -22,6 +22,7 @@ from products.engineering_analytics.backend.tests._github_fixtures import (
_run_row,
create_github_source,
link_schema,
+ seeding_object_storage,
)
from products.warehouse_sources.backend.facade.models import ExternalDataSource
from products.warehouse_sources.backend.test.utils import create_data_warehouse_table_from_csv
@@ -157,8 +158,7 @@ def _header(
class _WarehouseMixin(ClickhouseTestMixin, BaseTest):
"""Seeds warehouse tables behind a connected GitHub source with a non-default prefix,
so the full resolve -> build -> query path runs end to end against `myprefixgithub_*`
- tables. Skips when object storage is unreachable so the suite still runs without the
- dev stack."""
+ tables."""
def setUp(self) -> None:
super().setUp()
@@ -184,7 +184,7 @@ class _WarehouseMixin(ClickhouseTestMixin, BaseTest):
df.to_csv(tmp.name, index=False)
tmp.close()
self.addCleanup(Path(tmp.name).unlink, missing_ok=True)
- try:
+ with seeding_object_storage(self):
table, _source, _credential, _df, cleanup = create_data_warehouse_table_from_csv(
csv_path=Path(tmp.name),
table_name=base_name,
@@ -194,8 +194,6 @@ class _WarehouseMixin(ClickhouseTestMixin, BaseTest):
source=source,
source_prefix=prefix,
)
- except PermissionError as err:
- self.skipTest(f"object storage unavailable: {err}")
self.addCleanup(cleanup)
# base_name is "github_<endpoint>"; the synced schema/endpoint is its suffix.
link_schema(self.team, source, name=base_name.removeprefix("github_"), table=table)
@@ -203,8 +201,7 @@ class _WarehouseMixin(ClickhouseTestMixin, BaseTest):
class _EndpointsWarehouseMixin(_WarehouseMixin):
"""End-to-end aggregates over real warehouse tables. Seeds dates relative to
- real time (HogQL now() is server-side). Skips when object storage is
- unreachable."""
+ real time (HogQL now() is server-side)."""
def _seed(self) -> None:
self._create_table(
diff --git a/products/engineering_analytics/backend/tests/test_broken_tests.py b/products/engineering_analytics/backend/tests/test_broken_tests.py
index 654e9ffd90f1..19933aa1b9fe 100644
--- a/products/engineering_analytics/backend/tests/test_broken_tests.py
+++ b/products/engineering_analytics/backend/tests/test_broken_tests.py
@@ -61,17 +61,17 @@ from products.engineering_analytics.backend.logic.sources import GitHubTables
],
)
def test_classify_states(
- master_hits,
- queue_hits,
- pr_hits,
- age_hours,
- span_hours,
- branches,
- latest_conclusion,
- last_master_hit_age,
- latest_completed_age,
- expected,
-):
+ master_hits: int,
+ queue_hits: int,
+ pr_hits: int,
+ age_hours: int,
+ span_hours: int,
+ branches: int,
+ latest_conclusion: str | None,
+ last_master_hit_age: int,
+ latest_completed_age: int | None,
+ expected: BrokenTestState,
+) -> None:
assert (
_classify(
master_hits=master_hits,
@@ -272,7 +272,6 @@ def test_build_query_embeds_the_failures_view():
# Guards the private read path: the fingerprint scan reads the ci_failures builder as a subquery,
# not the registered warehouse view by name (keeps the product off the global catalog).
assert "engineering_analytics_ci_failures" not in module._FINGERPRINTS_SELECT
- assert "FAILED" in module.ci_failures.build_query()
class TestBrokenTestsQueryOverClickHouse(ClickhouseTestMixin, BaseTest):
diff --git a/products/engineering_analytics/backend/tests/test_ci_signals.py b/products/engineering_analytics/backend/tests/test_ci_signals.py
index 2f8a8ee7c273..ab6d1e601390 100644
--- a/products/engineering_analytics/backend/tests/test_ci_signals.py
+++ b/products/engineering_analytics/backend/tests/test_ci_signals.py
@@ -5,6 +5,7 @@ from pathlib import Path
from typing import Any
import pytest
+from freezegun import freeze_time
from posthog.test.base import BaseTest, ClickhouseTestMixin
from unittest import mock
@@ -26,7 +27,7 @@ from products.engineering_analytics.backend.logic.ci_signals_config import (
update_ci_signals_config,
)
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
-from products.engineering_analytics.backend.logic.queries.workflow_flakiness import BY_DESIGN_FAILURES
+from products.engineering_analytics.backend.logic.queries.workflow_flakiness import BY_DESIGN_FAILURES, FlakyJobRun
from products.engineering_analytics.backend.logic.signals.contracts import (
SOURCE_PRODUCT,
SOURCE_TYPE_BROKEN_DEFAULT_BRANCH,
@@ -59,6 +60,7 @@ from products.engineering_analytics.backend.tests._github_fixtures import (
_pr_row,
create_github_source,
create_warehouse_table_row,
+ seeding_object_storage,
)
from products.signals.backend.contracts import SIGNAL_VARIANT_LOOKUP, SignalRemediation
from products.signals.backend.enums import ReportPriority
@@ -203,6 +205,82 @@ def test_detect_all_raises_when_every_detector_fails() -> None:
assert detect_all(curated) == []
+def _flaky_row(job_name: str, run_id: int, *, workflow_name: str = "CI", head_sha: str = "sha") -> FlakyJobRun:
+ return FlakyJobRun(
+ repo_owner="PostHog",
+ repo_name="posthog",
+ workflow_name=workflow_name,
+ job_name=job_name,
+ run_id=run_id,
+ head_sha=head_sha,
+ failed_attempt=1,
+ passed_attempt=2,
+ )
+
+
+def _detect_flaky_over(rows: list[FlakyJobRun], *, min_flaky_runs: int) -> list[CISignalFinding]:
+ # Grouping runs in Python after this query returns; TestCISignalDetectors covers the SQL row shape.
+ with mock.patch(f"{_DETECTORS}.query_workflow_flakiness", return_value=rows):
+ return detect_flaky_checks(mock.Mock(), min_flaky_runs=min_flaky_runs)
+
+
+def test_flaky_source_ids_are_collision_free_and_bounded() -> None:
+ # (workflow='build', job='test:linux') and (workflow='build:test', job='linux') would share
+ # a ledger key with naive ':' joins, letting one condition suppress the other's emission;
+ # an oversized name would exceed the ledger column, fail to record after emit, and re-emit
+ # every sweep.
+ rows = [
+ _flaky_row("test:linux", 1, workflow_name="build"),
+ _flaky_row("linux", 1, workflow_name="build:test"),
+ _flaky_row("j" * 400, 1),
+ ]
+ ids = [finding.source_id for finding in _detect_flaky_over(rows, min_flaky_runs=1)]
+ assert len(ids) == 3
+ assert len(set(ids)) == 3
+ assert max(len(source_id) for source_id in ids) <= 200
+
+
+def test_flaky_check_emits_one_signal_per_job_per_week_not_per_rerun() -> None:
+ # The sweep re-reads a rolling window hourly. Keying a recurring flake per rerun turned 51
+ # flaky jobs into 905 signals against real PostHog/posthog data: one card per occurrence.
+ rows = [_flaky_row("flaky-job", run_id, head_sha=f"sha{run_id}") for run_id in (1, 2, 3)]
+ findings = _detect_flaky_over(rows, min_flaky_runs=3)
+ assert len(findings) == 1
+ assert findings[0].extra["flaky_count"] == 3
+ assert findings[0].extra["run_id"] == 3
+ _assert_emittable(findings[0])
+
+
+def test_flaky_check_groups_a_sharded_job_under_one_signal() -> None:
+ # Real rendered names with the shard label mid-name: an end-anchored match still splits
+ # this job, and per-shard keys each miss min_flaky_runs, so 3 recoveries report nothing.
+ shards = [
+ "Product tests (warehouse-sources (1/4), events schema legacy)",
+ "Product tests (warehouse-sources (1/5), events schema legacy)",
+ "Product tests (warehouse-sources (1/6), events schema legacy)",
+ ]
+ rows = [_flaky_row(shard, run_id, head_sha=f"shaS{run_id}") for run_id, shard in enumerate(shards, start=1)]
+ findings = _detect_flaky_over(rows, min_flaky_runs=3)
+ assert len(findings) == 1
+ # extra keeps the worked example's real job name so warehouse investigation queries match.
+ assert "CI job 'Product tests (warehouse-sources, events schema legacy)'" in findings[0].description
+ assert findings[0].extra["job_name"] == "Product tests (warehouse-sources (1/6), events schema legacy)"
+ assert findings[0].extra["flaky_count"] == 3
+ assert "Product tests (warehouse-sources (1/6), events schema legacy)" in findings[0].description
+ # `(1/4)`..`(1/6)` are all shard slot 1, so no multi-shard spread is claimed.
+ assert "spread over" not in findings[0].description
+ _assert_emittable(findings[0])
+
+
+def test_flaky_check_counts_runs_not_shard_recoveries() -> None:
+ # One run recovering on three shards is one flaky run: counting query rows would let a
+ # single bad run clear min_flaky_runs on its own.
+ rows = [
+ _flaky_row(f"Product tests (warehouse-sources ({index}/6), events schema legacy)", 1) for index in (1, 2, 3)
+ ]
+ assert _detect_flaky_over(rows, min_flaky_runs=3) == []
+
+
class TestDetectForSourceMultiRepo(BaseTest):
def test_multi_repo_source_snapshots_one_authorized_target(self) -> None:
# One roster entry per configured repo must not become duplicate sweep targets:
@@ -539,7 +617,7 @@ class TestSyncStatus(BaseTest):
class TestCISignalDetectors(ClickhouseTestMixin, BaseTest):
"""Detectors run over a real seeded github_workflow_runs warehouse table. Each test seeds both a
should-fire and a should-not-fire workflow and asserts the detected set, so it catches both
- missed conditions and false positives. Skips when object storage is unreachable (no dev stack)."""
+ missed conditions and false positives."""
def _seed_table(
self,
@@ -555,7 +633,7 @@ class TestCISignalDetectors(ClickhouseTestMixin, BaseTest):
df.to_csv(tmp.name, index=False)
tmp.close()
self.addCleanup(Path(tmp.name).unlink, missing_ok=True)
- try:
+ with seeding_object_storage(self):
table, out_source, out_credential, _df, cleanup = create_data_warehouse_table_from_csv(
csv_path=Path(tmp.name),
table_name=table_name,
@@ -566,8 +644,6 @@ class TestCISignalDetectors(ClickhouseTestMixin, BaseTest):
credential=credential,
source_prefix=GITHUB_SOURCE_PREFIX,
)
- except PermissionError as err:
- self.skipTest(f"object storage unavailable: {err}")
self.addCleanup(cleanup)
return table, out_source, out_credential
@@ -624,120 +700,27 @@ class TestCISignalDetectors(ClickhouseTestMixin, BaseTest):
assert findings[0].source_id.endswith(":flaky")
_assert_emittable(findings[0])
- def test_flaky_source_ids_are_collision_free_and_bounded(self) -> None:
- # (workflow='build', job='test:linux') and (workflow='build:test', job='linux') would share
- # a ledger key with naive ':' joins, letting one condition suppress the other's emission;
- # an oversized name would exceed the ledger column, fail to record after emit, and re-emit
- # every sweep.
- now = datetime.now(UTC).replace(tzinfo=None)
- rows = [_run_row(1, "CI", "shaC", "success", now - timedelta(hours=19), 60, run_attempt=2)]
- jobs = []
- for offset, (workflow, job) in enumerate([("build", "test:linux"), ("build:test", "linux"), ("CI", "j" * 400)]):
- failed = _job_row(200 + offset * 2, 1, job, "shaC", "failure", now - timedelta(hours=20), run_attempt=1)
- passed = _job_row(201 + offset * 2, 1, job, "shaC", "success", now - timedelta(hours=19), run_attempt=2)
- failed["workflow_name"] = workflow
- passed["workflow_name"] = workflow
- jobs.extend([failed, passed])
- findings = detect_flaky_checks(self._curated_over_runs(rows, jobs), min_flaky_runs=1)
- ids = [finding.source_id for finding in findings]
- assert len(ids) == 3
- assert len(set(ids)) == 3
- assert max(len(source_id) for source_id in ids) <= 200
-
- def test_flaky_check_emits_one_signal_per_job_per_week_not_per_rerun(self) -> None:
- # The sweep re-reads a rolling window hourly. Keying a recurring flake per rerun turned 51
- # flaky jobs into 905 signals against real PostHog/posthog data: one card per occurrence.
+ def test_flaky_query_keeps_same_commit_reruns_as_distinct_runs(self) -> None:
+ # Three separate runs of one job on one commit must come back as three rows. Grouping that
+ # drops run_id still compiles if run_id is wrapped in an aggregate, and then collapses them
+ # into one row, so flaky_count reads 1 and nothing clears min_flaky_runs. Only a multi-run
+ # seed on a shared head_sha catches that; the mocked detector tests supply the row shape
+ # rather than proving the SQL produces it.
now = datetime.now(UTC).replace(tzinfo=None)
rows = [
- _run_row(run_id, "CI", f"sha{run_id}", "success", now - timedelta(hours=run_id), 60, run_attempt=2)
+ _run_row(run_id, "CI", "shaR", "success", now - timedelta(hours=run_id + 1), 60, run_attempt=2)
for run_id in (1, 2, 3)
]
jobs = []
for run_id in (1, 2, 3):
- jobs.append(
- _job_row(
- run_id * 10,
- run_id,
- "flaky-job",
- f"sha{run_id}",
- "failure",
- now - timedelta(hours=run_id),
- run_attempt=1,
- )
- )
- jobs.append(
- _job_row(
- run_id * 10 + 1,
- run_id,
- "flaky-job",
- f"sha{run_id}",
- "success",
- now - timedelta(hours=run_id),
- run_attempt=2,
- )
- )
- findings = detect_flaky_checks(self._curated_over_runs(rows, jobs), min_flaky_runs=3)
- assert len(findings) == 1
- assert findings[0].extra["flaky_count"] == 3
- # The most recent sighting is the worked example; the rest survive as the count.
- assert findings[0].extra["run_id"] == 3
- _assert_emittable(findings[0])
+ started = now - timedelta(hours=run_id + 1)
+ jobs.append(_job_row(run_id * 10, run_id, "flaky-job", "shaR", "failure", started, run_attempt=1))
+ jobs.append(_job_row(run_id * 10 + 1, run_id, "flaky-job", "shaR", "success", started, run_attempt=2))
- def test_flaky_check_groups_a_sharded_job_under_one_signal(self) -> None:
- # Real rendered names with the shard label mid-name: an end-anchored match still splits
- # this job, and per-shard keys each miss min_flaky_runs, so 3 recoveries report nothing.
- now = datetime.now(UTC).replace(tzinfo=None)
- shards = [
- "Product tests (warehouse-sources (1/4), events schema legacy)",
- "Product tests (warehouse-sources (1/5), events schema legacy)",
- "Product tests (warehouse-sources (1/6), events schema legacy)",
- ]
- rows = []
- jobs = []
- for run_id, shard in enumerate(shards, start=1):
- rows.append(
- _run_row(run_id, "CI", f"shaS{run_id}", "success", now - timedelta(hours=run_id), 60, run_attempt=2)
- )
- jobs.append(
- _job_row(
- run_id * 10, run_id, shard, f"shaS{run_id}", "failure", now - timedelta(hours=run_id), run_attempt=1
- )
- )
- jobs.append(
- _job_row(
- run_id * 10 + 1,
- run_id,
- shard,
- f"shaS{run_id}",
- "success",
- now - timedelta(hours=run_id),
- run_attempt=2,
- )
- )
findings = detect_flaky_checks(self._curated_over_runs(rows, jobs), min_flaky_runs=3)
+
assert len(findings) == 1
- # The key and description group on the base name; extra keeps the worked example's real
- # job name so investigation queries on the warehouse still match.
- assert "CI job 'Product tests (warehouse-sources, events schema legacy)'" in findings[0].description
- assert findings[0].extra["job_name"] == "Product tests (warehouse-sources (1/6), events schema legacy)"
assert findings[0].extra["flaky_count"] == 3
- # The shard the worked example came from is evidence, so it survives outside the key.
- assert "Product tests (warehouse-sources (1/6), events schema legacy)" in findings[0].description
- # `(1/4)`..`(1/6)` are all shard slot 1, so no multi-shard spread is claimed.
- assert "spread over" not in findings[0].description
- _assert_emittable(findings[0])
-
- def test_flaky_check_counts_runs_not_shard_recoveries(self) -> None:
- # One run recovering on three shards is one flaky run: counting query rows would let a
- # single bad run clear min_flaky_runs on its own.
- now = datetime.now(UTC).replace(tzinfo=None)
- rows = [_run_row(1, "CI", "shaQ", "success", now - timedelta(hours=1), 60, run_attempt=2)]
- jobs = []
- for index in range(1, 4):
- shard = f"Product tests (warehouse-sources ({index}/6), events schema legacy)"
- jobs.append(_job_row(index * 10, 1, shard, "shaQ", "failure", now - timedelta(hours=1), run_attempt=1))
- jobs.append(_job_row(index * 10 + 1, 1, shard, "shaQ", "success", now - timedelta(hours=1), run_attempt=2))
- assert detect_flaky_checks(self._curated_over_runs(rows, jobs), min_flaky_runs=3) == []
@parameterized.expand(
[
@@ -778,9 +761,10 @@ class TestCISignalDetectors(ClickhouseTestMixin, BaseTest):
findings = detect_flaky_checks(self._curated_over_runs(rows, jobs), min_flaky_runs=1)
assert {f.extra["job_name"] for f in findings} == {"real-test-job"}
- @parameterized.expand([(name,) for name in _BY_DESIGN_JOB_NAMES])
- def test_flaky_check_reports_by_design_job_names_in_another_repo(self, job_name: str) -> None:
+ def test_flaky_check_reports_by_design_job_names_in_another_repo(self) -> None:
# Every team runs this detector over its own repos, so the repo qualifier has to hold.
+ # The qualifier lives once in the SQL, so one by-design name proves it for the list.
+ job_name = _BY_DESIGN_JOB_NAMES[0]
now = datetime.now(UTC).replace(tzinfo=None)
rows = [
_run_row(1, "CI", "shaS", "success", now - timedelta(hours=2), 60, run_attempt=2, repository="acme/webapp")
@@ -807,17 +791,20 @@ class TestCISignalDetectors(ClickhouseTestMixin, BaseTest):
_default_branch_pr_row(1, now - timedelta(days=30), default_branch="master"),
_default_branch_pr_row(2, now - timedelta(days=1), default_branch="trunk"),
]
- findings = detect_broken_default_branch(self._curated_over_runs(rows, pr_rows=prs), min_runs=2)
- assert {f.extra["workflow_name"] for f in findings} == {"red-ci"}
- assert findings[0].source_type == SOURCE_TYPE_BROKEN_DEFAULT_BRANCH
- assert findings[0].extra["branch"] == "trunk"
- _assert_emittable(findings[0])
-
- # A still-red branch must dedupe against one weekly key: a new completed run changing the
- # source_id would re-emit the same standing condition on every hourly sweep.
- rows.append(_run_row(6, "red-ci", "s6", "failure", now - timedelta(hours=1), 30, head_branch="trunk"))
- refreshed = detect_broken_default_branch(self._curated_over_runs(rows, pr_rows=prs), min_runs=2)
- assert refreshed[0].source_id == findings[0].source_id
+ # Both detector calls must read one clock: each keys its source_id on the observation
+ # week, so two real-clock reads straddling Monday 00:00 UTC would fail the equality below.
+ with freeze_time(now):
+ findings = detect_broken_default_branch(self._curated_over_runs(rows, pr_rows=prs), min_runs=2)
+ assert {f.extra["workflow_name"] for f in findings} == {"red-ci"}
+ assert findings[0].source_type == SOURCE_TYPE_BROKEN_DEFAULT_BRANCH
+ assert findings[0].extra["branch"] == "trunk"
+ _assert_emittable(findings[0])
+
+ # A still-red branch must dedupe against one weekly key: a new completed run changing the
+ # source_id would re-emit the same standing condition on every hourly sweep.
+ rows.append(_run_row(6, "red-ci", "s6", "failure", now - timedelta(hours=1), 30, head_branch="trunk"))
+ refreshed = detect_broken_default_branch(self._curated_over_runs(rows, pr_rows=prs), min_runs=2)
+ assert refreshed[0].source_id == findings[0].source_id
def test_broken_default_branch_without_pr_evidence_never_guesses(self) -> None:
# With no PR row for this repo its default branch is unknown, and a fallback guess of
diff --git a/products/engineering_analytics/backend/tests/test_ci_views.py b/products/engineering_analytics/backend/tests/test_ci_views.py
index 2462d57a93b4..8183afc9379d 100644
--- a/products/engineering_analytics/backend/tests/test_ci_views.py
+++ b/products/engineering_analytics/backend/tests/test_ci_views.py
@@ -19,7 +19,11 @@ from products.engineering_analytics.backend.logic.views.source_schema import (
WORKFLOW_JOBS_COLUMNS,
WORKFLOW_RUNS_COLUMNS,
)
-from products.engineering_analytics.backend.tests._github_fixtures import pr_association_entry, repo_id
+from products.engineering_analytics.backend.tests._github_fixtures import (
+ pr_association_entry,
+ repo_id,
+ seeding_object_storage,
+)
from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSource
from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
from products.warehouse_sources.backend.test.utils import create_data_warehouse_table_from_csv
@@ -92,7 +96,7 @@ class TestCIJobHistoryView(ClickhouseTestMixin, BaseTest):
df.to_csv(tmp.name, index=False)
tmp.close()
self.addCleanup(Path(tmp.name).unlink, missing_ok=True)
- try:
+ with seeding_object_storage(self):
table, _source, _credential, _df, cleanup = create_data_warehouse_table_from_csv(
csv_path=Path(tmp.name),
table_name=base_name,
@@ -101,8 +105,6 @@ class TestCIJobHistoryView(ClickhouseTestMixin, BaseTest):
team=self.team,
source_prefix=GITHUB_SOURCE_PREFIX,
)
- except PermissionError as err:
- self.skipTest(f"object storage unavailable: {err}")
self.addCleanup(cleanup)
return table.name
diff --git a/products/engineering_analytics/backend/tests/test_job_costs.py b/products/engineering_analytics/backend/tests/test_job_costs.py
index e22bd141ae10..9f2c435f31eb 100644
--- a/products/engineering_analytics/backend/tests/test_job_costs.py
+++ b/products/engineering_analytics/backend/tests/test_job_costs.py
@@ -22,6 +22,7 @@ from products.engineering_analytics.backend.logic.views.source_schema import (
WORKFLOW_JOBS_COLUMNS,
WORKFLOW_RUNS_COLUMNS,
)
+from products.engineering_analytics.backend.tests._github_fixtures import seeding_object_storage
from products.warehouse_sources.backend.test.utils import create_data_warehouse_table_from_csv
TEST_BUCKET = "test_storage_bucket-posthog.products.engineering_analytics.job_costs"
@@ -92,12 +93,9 @@ def _job_row(job_id: int, labels: list[str], started: str, completed: str | None
class TestJobCostsViewParity(ClickhouseTestMixin, BaseTest):
- """The generated view SQL must produce exactly what the Python cost model produces.
-
- This is the drift guard for the single-source-of-truth contract: the view is rendered from the
- same constants as logic.cost, so any change to one side that isn't matched on the other shows up
- here. Skips when object storage is unreachable so the suite still runs without the dev stack.
- """
+ # The drift guard for the single-source-of-truth contract: the view is rendered from the same
+ # constants as logic.cost, so any change to one side that isn't matched on the other shows up
+ # here.
def _create_table(self, base_name: str, columns: dict, rows: list[dict[str, Any]]) -> str:
df = pd.DataFrame(rows, columns=list(columns.keys()))
@@ -105,7 +103,7 @@ class TestJobCostsViewParity(ClickhouseTestMixin, BaseTest):
df.to_csv(tmp.name, index=False)
tmp.close()
self.addCleanup(Path(tmp.name).unlink, missing_ok=True)
- try:
+ with seeding_object_storage(self):
table, _source, _credential, _df, cleanup = create_data_warehouse_table_from_csv(
csv_path=Path(tmp.name),
table_name=base_name,
@@ -114,8 +112,6 @@ class TestJobCostsViewParity(ClickhouseTestMixin, BaseTest):
team=self.team,
source_prefix=GITHUB_SOURCE_PREFIX,
)
- except PermissionError as err:
- self.skipTest(f"object storage unavailable: {err}")
self.addCleanup(cleanup)
return table.name
diff --git a/products/engineering_analytics/backend/tests/test_logic_pull_requests.py b/products/engineering_analytics/backend/tests/test_logic_pull_requests.py
index ad4043ad10d6..058c697af46d 100644
--- a/products/engineering_analytics/backend/tests/test_logic_pull_requests.py
+++ b/products/engineering_analytics/backend/tests/test_logic_pull_requests.py
@@ -322,54 +322,47 @@ class TestPullRequestEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
[_job_row(94000, 9400, "build", "success", labels='["depot-ubuntu-22.04-4"]')],
)
item = next(i for i in api.list_pull_requests(team=self.team).items if i.number == 70)
- assert item.estimated_cost_usd is not None and item.estimated_cost_usd > 0
- assert item.billable_minutes is not None and item.billable_minutes > 0
+ # One 120s job on a 4-vCPU tier: 2 min x $0.004 x 2.
+ assert item.estimated_cost_usd == pytest.approx(0.016)
+ assert item.billable_minutes == pytest.approx(2.0)
def test_ready_to_merge_semantics(self) -> None:
# PR 20: only the LAST ready counts. PR 21: no transitions, whole life inside the window ->
# open-to-merge fallback. PR 22: created pre-window -> NULL. PR 23: re-drafted -> NULL.
# PR 24: same-second flip, the event id breaks the tie -> the higher-id ready wins.
# PR 25: merged past the window end (events not synced yet) -> NULL, never a wrong number.
- # One clock base for every row: _ago re-reads the clock per call, so the seconds-exact
- # dateDiff assertions below would drift by 1 whenever table-creation I/O straddles a
- # second boundary between the PR seed and the events seed.
- base = timezone.now()
-
- def ago(days: int) -> str:
- return (base - timedelta(days=days)).strftime("%Y-%m-%d %H:%M:%S")
-
self._create_table(
"github_pull_requests",
PULL_REQUESTS_COLUMNS,
[
- _pr_row(20, "alice", "closed", 0, ago(10), merged_at=ago(1), head_sha="sha20"),
- _pr_row(21, "alice", "closed", 0, ago(5), merged_at=ago(1), head_sha="sha21"),
- _pr_row(22, "alice", "closed", 0, ago(40), merged_at=ago(1), head_sha="sha22"),
- _pr_row(23, "alice", "open", 1, ago(6), head_sha="sha23"),
- _pr_row(24, "alice", "closed", 0, ago(10), merged_at=ago(1), head_sha="sha24"),
- _pr_row(25, "alice", "closed", 0, ago(5), merged_at=ago(0), head_sha="sha25"),
+ _pr_row(20, "alice", "closed", 0, _ago(10), merged_at=_ago(1), head_sha="sha20"),
+ _pr_row(21, "alice", "closed", 0, _ago(5), merged_at=_ago(1), head_sha="sha21"),
+ _pr_row(22, "alice", "closed", 0, _ago(40), merged_at=_ago(1), head_sha="sha22"),
+ _pr_row(23, "alice", "open", 1, _ago(6), head_sha="sha23"),
+ _pr_row(24, "alice", "closed", 0, _ago(10), merged_at=_ago(1), head_sha="sha24"),
+ _pr_row(25, "alice", "closed", 0, _ago(5), merged_at=_ago(0), head_sha="sha25"),
],
)
self._create_table(
"github_workflow_runs",
WORKFLOW_RUNS_COLUMNS,
- [_run_row(9500, "CI", "sha20", "completed", "success", ago(1), ago(1), pr_number=20)],
+ [_run_row(9500, "CI", "sha20", "completed", "success", _ago(1), _ago(1), pr_number=20)],
)
self._create_table(
"github_issue_events",
ISSUE_EVENTS_COLUMNS,
[
# The window must come from the WHOLE table, not the filtered transitions view.
- _issue_event_row(5000, "labeled", 20, ago(20)),
- _issue_event_row(5001, "ready_for_review", 20, ago(9)),
- _issue_event_row(5002, "convert_to_draft", 20, ago(8)),
- _issue_event_row(5003, "ready_for_review", 20, ago(2)),
- _issue_event_row(5004, "ready_for_review", 23, ago(4)),
- _issue_event_row(5005, "convert_to_draft", 23, ago(3)),
- _issue_event_row(5006, "convert_to_draft", 24, ago(2)),
- _issue_event_row(5007, "ready_for_review", 24, ago(2)),
+ _issue_event_row(5000, "labeled", 20, _ago(20)),
+ _issue_event_row(5001, "ready_for_review", 20, _ago(9)),
+ _issue_event_row(5002, "convert_to_draft", 20, _ago(8)),
+ _issue_event_row(5003, "ready_for_review", 20, _ago(2)),
+ _issue_event_row(5004, "ready_for_review", 23, _ago(4)),
+ _issue_event_row(5005, "convert_to_draft", 23, _ago(3)),
+ _issue_event_row(5006, "convert_to_draft", 24, _ago(2)),
+ _issue_event_row(5007, "ready_for_review", 24, _ago(2)),
# PR 21's merge event: proves the window covers its merge, arming the fallback.
- _issue_event_row(5008, "merged", 21, ago(1)),
+ _issue_event_row(5008, "merged", 21, _ago(1)),
],
)
by_number = {item.number: item for item in api.list_pull_requests(team=self.team).items}
@@ -619,7 +612,7 @@ class TestPullRequestEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
class TestPRLLMSpendWarehouse(_WarehouseMixin, BaseTest):
"""LLM token spend attributed to a PR by git branch, over a real warehouse PR row plus
- $ai_generation events. Skips when object storage is unreachable."""
+ $ai_generation events."""
def _generation(
self,
@@ -852,8 +845,7 @@ class TestPRLLMSpendWarehouse(_WarehouseMixin, BaseTest):
class TestRecentlyMergedPullRequests(_WarehouseMixin, BaseTest):
"""The recently-merged discovery seam over real warehouse tables: only PRs merged at or after
- `since` in the scoped repo surface, each with its branch-tip head SHA. Skips when object storage
- is unreachable."""
+ `since` in the scoped repo surface, each with its branch-tip head SHA."""
def test_returns_merged_prs_since_cutoff_scoped_to_repo(self) -> None:
self._create_table(
diff --git a/products/engineering_analytics/backend/tests/test_logic_sources.py b/products/engineering_analytics/backend/tests/test_logic_sources.py
index 601350572d40..84587db674e3 100644
--- a/products/engineering_analytics/backend/tests/test_logic_sources.py
+++ b/products/engineering_analytics/backend/tests/test_logic_sources.py
@@ -466,7 +466,7 @@ class TestMultiRepoGitHubResolution(BaseTest):
class TestMultiSourceResolutionWarehouse(_WarehouseMixin, BaseTest):
"""A team with one GitHub source per repository: a repo-scoped read must resolve the source
- connected for that repo, not the oldest one. Skips when object storage is unreachable."""
+ connected for that repo, not the oldest one."""
def _connect_source(self, *, source_id: str, prefix: str, repository: str) -> ExternalDataSource:
return ExternalDataSource.objects.create(
diff --git a/products/engineering_analytics/backend/tests/test_logic_workflows.py b/products/engineering_analytics/backend/tests/test_logic_workflows.py
index d28fea74f4fb..e6c37cae9222 100644
--- a/products/engineering_analytics/backend/tests/test_logic_workflows.py
+++ b/products/engineering_analytics/backend/tests/test_logic_workflows.py
@@ -1,4 +1,4 @@
-from datetime import UTC, datetime, timedelta
+from datetime import datetime, timedelta
from itertools import count
from types import SimpleNamespace
from typing import Any
@@ -35,6 +35,7 @@ from products.engineering_analytics.backend.tests._logic_helpers import (
_EndpointsWarehouseMixin,
_job_row,
_resp,
+ _seed_now,
)
@@ -98,7 +99,7 @@ class TestWorkflowEndpointMapping(BaseTest):
]
# A -30d window buckets by day. Must land inside the window (relative to now). Columns:
# owner, name, workflow, bucket_start, run_count, completed, successes, failures.
- bucket_rows = [("PostHog", "posthog", "CI", datetime.now(tz=UTC) - timedelta(days=1), 10, 8, 7, 1)]
+ bucket_rows = [("PostHog", "posthog", "CI", _seed_now() - timedelta(days=1), 10, 8, 7, 1)]
# Third response: the previous-window success rate (the Δ baseline); Deploy had no prior runs.
prev_rows = [("PostHog", "posthog", "CI", 0.95)]
with mock.patch(_RUN_QUERY, side_effect=[_resp(rows), _resp(bucket_rows), _resp(prev_rows)]):
@@ -519,8 +520,9 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
[_job_row(95000, 9500, "build", "success", labels='["depot-ubuntu-22.04-4"]')],
)
ci = next(i for i in api.list_workflow_health(team=self.team, date_from="-30d") if i.workflow_name == "CI")
- assert ci.estimated_cost_usd is not None and ci.estimated_cost_usd > 0
- assert ci.billable_minutes is not None and ci.billable_minutes > 0
+ # One 120s job on a 4-vCPU tier: 2 min x $0.004 x 2.
+ assert ci.estimated_cost_usd == pytest.approx(0.016)
+ assert ci.billable_minutes == pytest.approx(2.0)
def test_workflow_runner_costs_breaks_down_by_tier(self) -> None:
# The single-workflow breakdown splits a workflow's spend across runner tiers.
diff --git a/products/engineering_analytics/backend/tests/test_models.py b/products/engineering_analytics/backend/tests/test_models.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.py
index 1c37d960fb03..3c7c1307bf11 100644
--- a/products/engineering_analytics/backend/tests/test_presentation.py
+++ b/products/engineering_analytics/backend/tests/test_presentation.py
@@ -191,12 +191,14 @@ def _workflow_job() -> contracts.WorkflowJob:
class TestEngineeringAnalyticsAPI(APIBaseTest):
- def setUp(self) -> None:
- super().setUp()
+ @classmethod
+ def setUpTestData(cls) -> None:
+ super().setUpTestData()
# Source resolution precedes input validation, so the non-mocked bad-input tests below
# (window too large, malformed repo) need a connected source for those errors to surface
# rather than the no-source error. The mocked tests bypass resolution entirely.
- connect_github_source_without_data(self.team, prefix="presentation")
+ # Class-level: no test mutates the source, so per-test creation is redundant writes.
+ connect_github_source_without_data(cls.team, prefix="presentation")
def _url(self, action: str) -> str:
return f"/api/projects/{self.team.id}/engineering_analytics/{action}/"
@@ -394,17 +396,6 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
assert response.status_code == status.HTTP_404_NOT_FOUND
- def test_pr_lifecycle_400_when_pr_number_invalid(self) -> None:
- response = self.client.get(self._url("pr_lifecycle"), {"pr_number": "not-a-number"})
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST
-
- def test_pr_lifecycle_400_when_repo_missing(self) -> None:
- # repo is required (a PR number is repo-scoped), consistent with pr_runs/pr_cost.
- response = self.client.get(self._url("pr_lifecycle"), {"pr_number": "10"})
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST
-
def test_resolve_branch_serializes(self) -> None:
matches = [
contracts.BranchPRMatch(repo="PostHog/posthog", number=42, title="Fix bug", state="merged"),
@@ -422,12 +413,6 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
assert resolve.call_args.kwargs["branch"] == "feat/x"
assert resolve.call_args.kwargs["repo"] == "PostHog/posthog"
- def test_resolve_branch_400_when_branch_missing(self) -> None:
- # Validation lives in the facade; a request with no branch surfaces as a 400 (source connected in setUp).
- response = self.client.get(self._url("resolve_branch"))
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST
-
def test_workflow_run_serializes(self) -> None:
with mock.patch(f"{_VIEWS}.get_workflow_run", return_value=_workflow_run()) as get:
response = self.client.get(self._url("workflow_run"), {"run_id": "7777"})
@@ -447,11 +432,6 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
assert response.status_code == status.HTTP_404_NOT_FOUND
- def test_workflow_run_400_when_run_id_invalid(self) -> None:
- response = self.client.get(self._url("workflow_run"), {"run_id": "not-a-number"})
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST
-
def test_workflow_runs_serializes(self) -> None:
with mock.patch(f"{_VIEWS}.list_workflow_runs", return_value=[_workflow_run()]) as listing:
response = self.client.get(
@@ -467,11 +447,6 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
# The detail page's branch scope must reach the read layer, or the runs list widens to all branches.
assert listing.call_args.kwargs["branch"] == "main"
- def test_workflow_runs_400_when_params_missing(self) -> None:
- response = self.client.get(self._url("workflow_runs"), {"workflow_name": "CI"})
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST
-
def test_workflow_runner_costs_passes_branch_through(self) -> None:
# The cost breakdown shares the detail page's branch scope, so the branch must reach the read layer.
with mock.patch(f"{_VIEWS}.get_workflow_runner_costs", return_value=[]) as get_costs:
@@ -493,11 +468,6 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
assert listing.call_args.kwargs["pr_number"] == 9100
assert listing.call_args.kwargs["repo"] == "PostHog/posthog"
- def test_pr_runs_400_when_params_missing(self) -> None:
- response = self.client.get(self._url("pr_runs"), {"pr_number": "10"})
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST
-
def test_pr_cost_serializes(self) -> None:
summary = contracts.PRCostSummary(
jobs_available=True,
@@ -537,11 +507,6 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
assert getter.call_args.kwargs["pr_number"] == 10
assert getter.call_args.kwargs["repo"] == "PostHog/posthog"
- def test_pr_cost_400_when_params_missing(self) -> None:
- response = self.client.get(self._url("pr_cost"), {"pr_number": "10"})
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST
-
def test_workflow_jobs_serializes(self) -> None:
with mock.patch(f"{_VIEWS}.list_workflow_jobs", return_value=[_workflow_job()]) as listing:
response = self.client.get(self._url("workflow_jobs"), {"run_id": "9100"})
@@ -553,14 +518,24 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
assert body[0]["runner_label"] == "16-core"
assert listing.call_args.kwargs["run_id"] == 9100
- def test_workflow_jobs_400_when_run_id_invalid(self) -> None:
- response = self.client.get(self._url("workflow_jobs"), {"run_id": "nope"})
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST
-
- def test_pr_lifecycle_400_on_malformed_repo(self) -> None:
- # Bare org (no '/name') would otherwise silently match the wrong repo.
- response = self.client.get(self._url("pr_lifecycle"), {"pr_number": "10", "repo": "PostHog"})
+ @parameterized.expand(
+ [
+ ("pr_lifecycle_pr_number_invalid", "pr_lifecycle", {"pr_number": "not-a-number"}),
+ # repo is required (a PR number is repo-scoped), consistent with pr_runs/pr_cost.
+ ("pr_lifecycle_repo_missing", "pr_lifecycle", {"pr_number": "10"}),
+ # Bare org (no '/name') would otherwise silently match the wrong repo.
+ ("pr_lifecycle_repo_malformed", "pr_lifecycle", {"pr_number": "10", "repo": "PostHog"}),
+ ("resolve_branch_branch_missing", "resolve_branch", {}),
+ ("workflow_run_run_id_invalid", "workflow_run", {"run_id": "not-a-number"}),
+ ("workflow_runs_repo_missing", "workflow_runs", {"workflow_name": "CI"}),
+ ("pr_runs_repo_missing", "pr_runs", {"pr_number": "10"}),
+ ("pr_cost_repo_missing", "pr_cost", {"pr_number": "10"}),
+ ("workflow_jobs_run_id_invalid", "workflow_jobs", {"run_id": "nope"}),
+ ]
+ )
+ def test_bad_params_400(self, _name: str, action: str, params: dict[str, str]) -> None:
+ # Each action carries its own ValueError guard, so every action keeps a row here.
+ response = self.client.get(self._url(action), params)
assert response.status_code == status.HTTP_400_BAD_REQUEST
@@ -577,10 +552,10 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "run_scope must be one of" in response.json()["detail"]
- @parameterized.expand(
- ["sources", "ci-signals-config", "ci_cards", "pull_requests", "workflow_health", "pr_lifecycle", "quarantine"]
- )
+ @parameterized.expand(["sources", "quarantine"])
def test_requires_authentication(self, action: str) -> None:
+ # permission_classes live once on the shared viewset base and per-action scope drift is
+ # TestScopeEnrollment's job, so one read and one write action prove the wiring.
self.client.logout()
response = self.client.get(self._url(action))
diff --git a/products/engineering_analytics/backend/tests/test_quarantine.py b/products/engineering_analytics/backend/tests/test_quarantine.py
index 8b56a4f1408c..1a70052638bd 100644
--- a/products/engineering_analytics/backend/tests/test_quarantine.py
+++ b/products/engineering_analytics/backend/tests/test_quarantine.py
@@ -10,7 +10,8 @@ from posthog.test.base import APIBaseTest, BaseTest
from unittest import TestCase, mock
from django.core.cache import cache
-from django.test import override_settings
+from django.test import SimpleTestCase, override_settings
+from django.urls import resolve
import requests
from parameterized import parameterized
@@ -30,6 +31,7 @@ from products.engineering_analytics.backend.logic.quarantine import (
render_quarantine_file,
request_quarantine,
)
+from products.engineering_analytics.backend.presentation.serializers.suite_health import QuarantineRequestSerializer
_TODAY = date(2026, 6, 12)
_REQUESTS_GET = "products.engineering_analytics.backend.logic.quarantine.requests.get"
@@ -247,6 +249,7 @@ class TestQuarantineBuild(BaseTest):
"https://raw.githubusercontent.com/PostHog/posthog/HEAD/.test_quarantine.json", timeout=3, stream=True
)
+ @freeze_time("2026-06-12")
def test_404_means_unavailable_without_errors(self) -> None:
with mock.patch(_REQUESTS_GET, return_value=_response(404)):
result = build_quarantine(team=self.team, repo="PostHog/posthog")
@@ -262,6 +265,7 @@ class TestQuarantineBuild(BaseTest):
("server_error", 500),
]
)
+ @freeze_time("2026-06-12")
def test_fetch_failure_reported_as_single_parse_error(self, _name: str, failure: Exception | int) -> None:
kwargs: dict[str, Any] = (
{"side_effect": failure} if isinstance(failure, Exception) else {"return_value": _response(failure)}
@@ -273,6 +277,7 @@ class TestQuarantineBuild(BaseTest):
assert len(result.parse_errors) == 1 and "could not fetch" in result.parse_errors[0]
@parameterized.expand(["PostHog", "Post Hog/repo", "PostHog/po$thog", "-bad/repo", "a/b/c", "PostHog/"])
+ @freeze_time("2026-06-12")
def test_invalid_repo_rejected_before_fetch(self, repo: str) -> None:
with mock.patch(_REQUESTS_GET) as get:
result = build_quarantine(team=self.team, repo=repo)
@@ -281,6 +286,7 @@ class TestQuarantineBuild(BaseTest):
assert len(result.parse_errors) == 1 and "invalid repo" in result.parse_errors[0]
get.assert_not_called()
+ @freeze_time("2026-06-12")
def test_caches_fetched_text(self) -> None:
with mock.patch(_REQUESTS_GET, return_value=_response(200, _text(_entry()))) as get:
build_quarantine(team=self.team, repo="PostHog/posthog")
@@ -289,6 +295,7 @@ class TestQuarantineBuild(BaseTest):
assert get.call_count == 1
assert result.available is True and len(result.entries) == 1
+ @freeze_time("2026-06-12")
def test_oversized_streamed_body_rejected_and_not_cached(self) -> None:
# No Content-Length header: the cap must hold on the streamed bytes, and a
# hostile oversize response must not poison the cache for the next caller.
@@ -301,6 +308,7 @@ class TestQuarantineBuild(BaseTest):
assert second.available is False
assert get.call_count == 2
+ @freeze_time("2026-06-12")
def test_oversized_content_length_rejected_before_reading_body(self) -> None:
response = _response(200, _text(_entry()), headers={"Content-Length": str(10 * 1024 * 1024)})
with mock.patch(_REQUESTS_GET, return_value=response):
@@ -309,6 +317,7 @@ class TestQuarantineBuild(BaseTest):
assert result.available is False and "exceeds" in result.parse_errors[0]
response.iter_content.assert_not_called()
+ @freeze_time("2026-06-12")
def test_resolves_most_active_repo_from_workflow_runs(self) -> None:
source = _curated_source([("PostHog", "posthog.com")])
with (
@@ -320,6 +329,7 @@ class TestQuarantineBuild(BaseTest):
assert result.repo == contracts.RepoRef(provider="github", owner="PostHog", name="posthog.com")
assert source.run.call_args.kwargs["query_type"] == "engineering_analytics.quarantine_repo"
+ @freeze_time("2026-06-12")
def test_no_recent_runs_means_unavailable(self) -> None:
with (
mock.patch(_FOR_TEAM, return_value=_curated_source([])),
@@ -331,6 +341,7 @@ class TestQuarantineBuild(BaseTest):
assert len(result.parse_errors) == 1 and "could not determine a repository" in result.parse_errors[0]
get.assert_not_called()
+ @freeze_time("2026-06-12")
def test_no_connected_source_is_fail_open(self) -> None:
with (
mock.patch(_FOR_TEAM, side_effect=contracts.GitHubSourceNotConnectedError("no GitHub source connected")),
@@ -342,6 +353,7 @@ class TestQuarantineBuild(BaseTest):
assert "pass ?repo=owner/name" in result.parse_errors[0]
get.assert_not_called()
+ @freeze_time("2026-06-12")
def test_debug_reads_local_checkout(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
(Path(tmp) / QUARANTINE_FILENAME).write_text(_text(_entry()))
@@ -358,6 +370,9 @@ class TestQuarantineAPI(APIBaseTest):
def setUp(self) -> None:
super().setUp()
cache.clear()
+ # Warm the lazy API router before any frozen clock: the process's first resolution builds
+ # the view classes, and building them under freezegun raises a metaclass conflict.
+ resolve(self._url())
def _url(self) -> str:
return f"/api/projects/{self.team.id}/engineering_analytics/quarantine/"
@@ -380,15 +395,6 @@ class TestQuarantineAPI(APIBaseTest):
assert entry["days_until_expiry"] == 8
assert entry["expires"] == "2026-06-20"
- def test_quarantine_available_false_when_repo_has_no_file(self) -> None:
- with mock.patch(_REQUESTS_GET, return_value=_response(404)):
- response = self.client.get(self._url(), {"repo": "PostHog/no-quarantine"})
-
- assert response.status_code == status.HTTP_200_OK
- body = response.json()
- assert body["available"] is False
- assert body["entries"] == [] and body["parse_errors"] == []
-
def test_repo_param_passes_through_to_facade(self) -> None:
empty = contracts.QuarantineFile(
available=False,
@@ -554,19 +560,18 @@ class TestQuarantineRequest(BaseTest):
assert github.create_pull_request.call_args.args[3] == result.branch # head branch
assert github.create_pull_request.call_args.args[4] == "master" # base branch
+ @parameterized.expand(
+ [
+ ("skip_mode", {"mode": contracts.QuarantineMode.SKIP}, "mode", "skip"),
+ ("jest_runner", {"runner": contracts.QuarantineRunner.JEST}, "runner", "jest"),
+ ]
+ )
@freeze_time("2026-06-12")
- def test_skip_mode_is_persisted(self) -> None:
- github = self._install(_github_mock())
- request_quarantine(team=self.team, request=_request(mode=contracts.QuarantineMode.SKIP))
- entry = json.loads(github.update_file.call_args.args[2])["entries"][0]
- assert entry["mode"] == "skip"
-
- @freeze_time("2026-06-12")
- def test_jest_runner_is_persisted(self) -> None:
+ def test_request_field_is_persisted(self, _name: str, overrides: dict[str, Any], key: str, expected: str) -> None:
github = self._install(_github_mock())
- request_quarantine(team=self.team, request=_request(runner=contracts.QuarantineRunner.JEST))
+ request_quarantine(team=self.team, request=_request(**overrides))
entry = json.loads(github.update_file.call_args.args[2])["entries"][0]
- assert entry["runner"] == "jest"
+ assert entry[key] == expected
@freeze_time("2026-06-12")
def test_extend_reuses_existing_issue_and_files_no_new_one(self) -> None:
@@ -587,6 +592,7 @@ class TestQuarantineRequest(BaseTest):
assert entry["expires"] == "2026-06-25"
assert entry["issue"] == "https://github.com/PostHog/posthog/issues/7"
+ @freeze_time("2026-06-12")
def test_remove_drops_the_entry_without_an_issue(self) -> None:
github = self._install(_github_mock(get_file_contents={"content": _text(_entry()), "sha": "s"}))
result = request_quarantine(
@@ -597,6 +603,7 @@ class TestQuarantineRequest(BaseTest):
assert result.issue_url == "" and result.branch.startswith("unquarantine/")
assert json.loads(github.update_file.call_args.args[2])["entries"] == []
+ @freeze_time("2026-06-12")
def test_remove_of_absent_entry_is_a_clear_error(self) -> None:
github = self._install(_github_mock(get_file_contents={"content": _text(), "sha": "s"}))
with self.assertRaises(contracts.QuarantineWriteError):
@@ -606,16 +613,19 @@ class TestQuarantineRequest(BaseTest):
)
github.create_branch.assert_not_called()
+ @freeze_time("2026-06-12")
def test_no_github_integration_is_a_clear_error(self) -> None:
self._install(_github_mock(), has_integration=False)
with self.assertRaises(contracts.QuarantineWriteError):
request_quarantine(team=self.team, request=_request())
+ @freeze_time("2026-06-12")
def test_app_installed_on_wrong_org_is_rejected(self) -> None:
self._install(_github_mock(organization="SomeoneElse"))
with self.assertRaises(contracts.QuarantineWriteError):
request_quarantine(team=self.team, request=_request())
+ @freeze_time("2026-06-12")
def test_explicit_repo_outside_the_team_is_rejected_before_any_write(self) -> None:
# A client-supplied repo the team hasn't connected as a GitHub source must not get the
# App's write token, even when it sits in the install's org.
@@ -631,6 +641,7 @@ class TestQuarantineRequest(BaseTest):
("api_failure", Exception("Failed to get default branch: HTTP 404")),
]
)
+ @freeze_time("2026-06-12")
def test_github_failure_becomes_a_user_safe_error_not_a_500(self, _name: str, failure: Exception) -> None:
# get_default_branch raises plain ValueError/Exception, not QuarantineWriteError; without
# translation those escape as a 500 instead of the user-safe 400 the rest of the path gives.
@@ -640,6 +651,7 @@ class TestQuarantineRequest(BaseTest):
request_quarantine(team=self.team, request=_request())
github.create_branch.assert_not_called()
+ @freeze_time("2026-06-12")
def test_malformed_existing_file_aborts_without_writing(self) -> None:
github = self._install(_github_mock(get_file_contents={"content": "{ not json", "sha": "s"}))
with self.assertRaises(contracts.QuarantineWriteError):
@@ -722,22 +734,41 @@ class TestQuarantineRequestAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "not 'PostHog'" in response.json()["detail"]
+ def test_invalid_body_is_rejected(self) -> None:
+ # Proves the viewset runs the serializer at all; the case matrix lives in
+ # TestQuarantineRequestValidation, which needs no DB.
+ body = self._body()
+ body.pop("selector")
+ with mock.patch(f"{_VIEWS}.request_quarantine") as called:
+ response = self.client.post(self._url(), body, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ called.assert_not_called()
+
+
+class TestQuarantineRequestValidation(SimpleTestCase):
@parameterized.expand(
[
- ("missing_selector", {"selector": None}),
- ("missing_action", {"operation": None}),
- ("bad_action", {"operation": "nuke"}),
+ ("missing_selector", {"selector": None}, "selector", "required"),
+ ("missing_action", {"operation": None}, "operation", "required"),
+ ("bad_action", {"operation": "nuke"}, "operation", "invalid_choice"),
]
)
- def test_invalid_body_is_rejected(self, _name: str, overrides: dict[str, Any]) -> None:
- body = self._body()
+ def test_field_errors(self, _name: str, overrides: dict[str, Any], field: str, code: str) -> None:
+ body: dict[str, Any] = {
+ "operation": "quarantine",
+ "selector": "posthog/api/test/test_foo.py::TestFoo::test_bar",
+ "repo": "PostHog/posthog",
+ "reason": "flaky",
+ "owner": "@PostHog/team-foo",
+ }
for key, value in overrides.items():
if value is None:
body.pop(key, None)
else:
body[key] = value
- with mock.patch(f"{_VIEWS}.request_quarantine") as called:
- response = self.client.post(self._url(), body, format="json")
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- called.assert_not_called()
+ serializer = QuarantineRequestSerializer(data=body)
+
+ assert not serializer.is_valid()
+ assert serializer.errors[field][0].code == code
diff --git a/products/engineering_analytics/backend/tests/test_tasks.py b/products/engineering_analytics/backend/tests/test_tasks.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/products/engineering_analytics/backend/tests/test_team_ci_health.py b/products/engineering_analytics/backend/tests/test_team_ci_health.py
index 866294d704a4..79a10ef7be44 100644
--- a/products/engineering_analytics/backend/tests/test_team_ci_health.py
+++ b/products/engineering_analytics/backend/tests/test_team_ci_health.py
@@ -29,7 +29,7 @@ class TestTeamCIHealthAPI(ClickhouseTestMixin, APIBaseTest):
current_b: datetime
@classmethod
- def setUpTestData(cls):
+ def setUpTestData(cls) -> None:
super().setUpTestData()
connect_github_source_without_data(cls.team, prefix="teams", repository="PostHog/posthog")
sync_execute("DROP TABLE IF EXISTS trace_spans_distributed")
@@ -76,7 +76,7 @@ class TestTeamCIHealthAPI(ClickhouseTestMixin, APIBaseTest):
),
# Ownership re-stamp: prior-window failure stamped team-old, current stamped team-new.
# The latest stamp owns the whole test, in the roster and the drill-in alike.
- cls._span(15, T_RESTAMPED, "failed", ts=prior, owner="team-old", run="601", pr="601"),
+ cls._span(18, T_RESTAMPED, "failed", ts=prior, owner="team-old", run="601", pr="601"),
cls._span(16, T_RESTAMPED, "failed", ts=cls.current_b, owner="team-new", run="602", pr="602"),
# No owner stamp: buckets under the literal 'unowned'.
cls._span(12, T_UNOWNED, "rerun_passed", ts=cls.current_b, owner="", run="401", pr="401"),
@@ -104,7 +104,7 @@ class TestTeamCIHealthAPI(ClickhouseTestMixin, APIBaseTest):
)
@classmethod
- def tearDownClass(cls):
+ def tearDownClass(cls) -> None:
sync_execute("DROP TABLE IF EXISTS trace_spans_distributed")
sync_execute("DROP TABLE IF EXISTS trace_spans")
sync_execute(TRACE_SPANS_TABLE_SQL())
@@ -150,7 +150,7 @@ class TestTeamCIHealthAPI(ClickhouseTestMixin, APIBaseTest):
def _roster(self) -> dict[str, dict]:
return {item["owner_team"]: item for item in self._get("team_ci_health")["items"]}
- def test_roster_uses_the_same_flake_proof_as_the_queue(self):
+ def test_roster_uses_the_same_flake_proof_as_the_queue(self) -> None:
rows = self._roster()
# Only the pass-on-retry test is proven flaky. The 3-PR test failed with no recovery, so it
@@ -177,7 +177,7 @@ class TestTeamCIHealthAPI(ClickhouseTestMixin, APIBaseTest):
# A re-run pass that pairs with no failure is not evidence: no phantom all-zero team row.
assert "team-quiet" not in rows
- def test_restamped_test_lands_under_its_latest_owner_in_roster_and_drill_in(self):
+ def test_restamped_test_lands_under_its_latest_owner_in_roster_and_drill_in(self) -> None:
rows = self._roster()
# All evidence, prior window included, follows the latest stamp; the old team keeps nothing.
@@ -192,7 +192,7 @@ class TestTeamCIHealthAPI(ClickhouseTestMixin, APIBaseTest):
] == [(T_RESTAMPED, 1, 1)]
assert self._get("team_ci_activity", owner_team="team-old")["tests"] == []
- def test_activity_scopes_to_team_and_pairs_windows(self):
+ def test_activity_scopes_to_team_and_pairs_windows(self) -> None:
data = self._get("team_ci_activity", owner_team="team-replay")
assert data["owner_team"] == "team-replay"
@@ -203,10 +203,10 @@ class TestTeamCIHealthAPI(ClickhouseTestMixin, APIBaseTest):
]
assert not data["truncated_tests"]
- def test_activity_for_unknown_team_is_empty(self):
+ def test_activity_for_unknown_team_is_empty(self) -> None:
data = self._get("team_ci_activity", owner_team="team-nonexistent")
assert data["tests"] == []
- def test_activity_requires_owner_team(self):
+ def test_activity_requires_owner_team(self) -> None:
response = self.client.get(f"/api/projects/{self.team.id}/engineering_analytics/team_ci_activity/")
assert response.status_code == status.HTTP_400_BAD_REQUEST
diff --git a/products/engineering_analytics/backend/tests/test_views.py b/products/engineering_analytics/backend/tests/test_views.py
index a255785b0637..3bbaef68f226 100644
--- a/products/engineering_analytics/backend/tests/test_views.py
+++ b/products/engineering_analytics/backend/tests/test_views.py
@@ -65,8 +65,7 @@ class TestListGithubSourcesAccessControl(BaseTest):
class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
"""The curated query builders, exercised as inline subqueries over real
- warehouse tables. Skips when object storage is unreachable so the suite still
- runs without the dev stack."""
+ warehouse tables."""
def _create_table(self, base_name: str, columns: dict, rows: list[dict[str, Any]]) -> str:
return create_github_warehouse_table(self, base_name, columns, rows)
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
index f4924aeaf852..ab933559e55f 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
@@ -237,6 +237,7 @@ const SOURCES: GitHubSourceApi[] = [
describe('engineeringAnalyticsLogic', () => {
let logic: ReturnType<typeof engineeringAnalyticsLogic.build>
+ let extraUnmounts: (() => void)[] = []
beforeEach(() => {
initKeaTests()
@@ -257,6 +258,12 @@ describe('engineeringAnalyticsLogic', () => {
})
afterEach(() => {
+ // Unmount everything so a still-pending loader can't reject into a later, unsilenced test.
+ extraUnmounts.forEach((unmount) => unmount())
+ extraUnmounts = []
+ if (logic?.isMounted()) {
+ logic.unmount()
+ }
jest.restoreAllMocks()
resumeKeaLoadersErrors()
})
@@ -337,7 +344,7 @@ describe('engineeringAnalyticsLogic', () => {
// #62051 collapsed sceneLogic to single-scene state and stopped threading a tabId into
// scene logics. A tab-aware scene logic then throws "must have a tabId prop" on mount,
// sceneLogic's catch falls back to Error404, and every visit to the scene 404s.
- expect(() => engineeringAnalyticsSceneLogic().mount()).not.toThrow()
+ expect(() => extraUnmounts.push(engineeringAnalyticsSceneLogic().mount())).not.toThrow()
})
it('maps the three endpoints into typed rows and defaults to the open filter', async () => {
@@ -375,7 +382,7 @@ describe('engineeringAnalyticsLogic', () => {
logic = engineeringAnalyticsLogic()
logic.mount()
const filters = engineeringAnalyticsFiltersLogic()
- filters.mount()
+ extraUnmounts.push(filters.mount())
await expectLogic(logic).toDispatchActions(['loadWorkflowHealthSuccess'])
expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-7d' })
@@ -394,7 +401,7 @@ describe('engineeringAnalyticsLogic', () => {
logic = engineeringAnalyticsLogic()
logic.mount()
const filters = engineeringAnalyticsFiltersLogic()
- filters.mount()
+ extraUnmounts.push(filters.mount())
await expectLogic(logic).toDispatchActions(['loadWorkflowHealthSuccess'])
expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-7d' })
@@ -429,25 +436,13 @@ describe('engineeringAnalyticsLogic', () => {
expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-90d' })
})
- it('exposes source options and the multi-source flag only when more than one source exists', async () => {
- mockSources.mockResolvedValue(SOURCES)
- logic = engineeringAnalyticsLogic()
- logic.mount()
- await expectLogic(logic).toDispatchActions(['loadGithubSourcesSuccess'])
-
- expect(logic.values.hasMultipleSources).toBe(true)
- // The option value encodes (source, repo) so a multi-repo source's repos stay distinct.
- expect(logic.values.sourceOptions).toEqual([
- { value: 'src-older::posthog/posthog', label: 'posthog/posthog' },
- { value: 'src-newer::posthog/posthog.com', label: 'posthog/posthog.com' },
- ])
- })
-
- it('lists one option per configured repo of a multi-repo source and scopes to the picked repo', async () => {
- // One source syncing two repos → two distinct picker entries; picking one scopes source_id + repo.
+ it('lists one option per (source, repo) pair and scopes to the picked repo', async () => {
+ // The option value encodes (source, repo) so a multi-repo source's repos stay distinct;
+ // two distinct sources and one source syncing two repos produce the same option shape.
mockSources.mockResolvedValue([
{ id: 'src-multi', repo: 'posthog/posthog', prefix: 'multi', synced: true },
{ id: 'src-multi', repo: 'posthog/posthog.com', prefix: 'multi', synced: true },
+ { id: 'src-other', repo: 'posthog/posthog.js', prefix: 'js', synced: true },
])
logic = engineeringAnalyticsLogic()
logic.mount()
@@ -457,6 +452,7 @@ describe('engineeringAnalyticsLogic', () => {
expect(logic.values.sourceOptions).toEqual([
{ value: 'src-multi::posthog/posthog', label: 'posthog/posthog' },
{ value: 'src-multi::posthog/posthog.com', label: 'posthog/posthog.com' },
+ { value: 'src-other::posthog/posthog.js', label: 'posthog/posthog.js' },
])
logic.actions.setScope('src-multi', 'posthog/posthog.com')
@@ -522,20 +518,6 @@ describe('engineeringAnalyticsLogic', () => {
).toEqual(expected)
})
- it('resetWorkflowFilters returns the workflow filters to defaults and clears hasActiveWorkflowFilters', () => {
- logic = engineeringAnalyticsLogic()
- logic.mount()
- expect(logic.values.hasActiveWorkflowFilters).toBe(false)
-
- logic.actions.setWorkflowSearch('e2e')
- logic.actions.setWorkflowStatusFilter('failing')
- expect(logic.values.hasActiveWorkflowFilters).toBe(true)
-
- logic.actions.resetWorkflowFilters()
- expect(logic.values.workflowFilters).toEqual(DEFAULT_WORKFLOW_FILTERS)
- expect(logic.values.hasActiveWorkflowFilters).toBe(false)
- })
-
it('workflowCostAvailable flips on once any row carries cost data', async () => {
logic = engineeringAnalyticsLogic()
logic.mount()
@@ -561,22 +543,62 @@ describe('engineeringAnalyticsLogic', () => {
expect(logic.values.scopeRepo).toBe('posthog/posthog.com')
})
- it('resetFilters returns every filter to defaults and clears hasActiveFilters', async () => {
- logic = engineeringAnalyticsLogic()
- logic.mount()
- expect(logic.values.hasActiveFilters).toBe(false)
-
- logic.actions.setStateFilter('all')
- logic.actions.setAuthor('alice')
- logic.actions.setRepo('posthog/posthog')
- logic.actions.setCiStatusFilter('failing')
- logic.actions.setSearch('fix')
- expect(logic.values.hasActiveFilters).toBe(true)
-
- logic.actions.resetFilters()
- expect(logic.values.filters).toEqual(DEFAULT_FILTERS)
- expect(logic.values.hasActiveFilters).toBe(false)
- })
+ it.each([
+ [
+ 'pull request',
+ [
+ ['setStateFilter', 'all'],
+ ['setAuthor', 'alice'],
+ ['setRepo', 'posthog/posthog'],
+ ['setCiStatusFilter', 'failing'],
+ ['setSearch', 'fix'],
+ ],
+ 'resetFilters',
+ 'hasActiveFilters',
+ 'filters',
+ DEFAULT_FILTERS,
+ ],
+ [
+ 'workflow',
+ [
+ ['setWorkflowSearch', 'e2e'],
+ ['setWorkflowStatusFilter', 'failing'],
+ ],
+ 'resetWorkflowFilters',
+ 'hasActiveWorkflowFilters',
+ 'workflowFilters',
+ DEFAULT_WORKFLOW_FILTERS,
+ ],
+ [
+ 'quarantine',
+ [
+ ['setQuarantineSearch', 'flake'],
+ ['setQuarantineLifecycleFilter', 'active'],
+ ['setQuarantineModeFilter', 'skip'],
+ ['setQuarantineOwner', '@team/x'],
+ ],
+ 'resetQuarantineFilters',
+ 'hasActiveQuarantineFilters',
+ 'quarantineFilters',
+ DEFAULT_QUARANTINE_FILTERS,
+ ],
+ ] as [string, [string, string][], string, string, string, object][])(
+ 'the %s reset returns filters to defaults and clears the active flag',
+ (_label, dirtyCalls, resetAction, activeKey, filtersKey, defaults) => {
+ logic = engineeringAnalyticsLogic()
+ logic.mount()
+ const actions = logic.actions as unknown as Record<string, (value: string) => void>
+ const values = logic.values as unknown as Record<string, unknown>
+ expect(values[activeKey]).toBe(false)
+
+ dirtyCalls.forEach(([action, value]) => actions[action](value))
+ expect(values[activeKey]).toBe(true)
+
+ ;(actions[resetAction] as unknown as () => void)()
+ expect(values[filtersKey]).toEqual(defaults)
+ expect(values[activeKey]).toBe(false)
+ }
+ )
it.each([
// Stacked bar: total height is completed (volume), the red portion is failures, so the red
@@ -720,55 +742,28 @@ describe('engineeringAnalyticsLogic', () => {
expect(groups[1].runs.map((r) => r.runId)).toEqual([1, 2])
})
- it('flags notConnected when no GitHub source is connected (cards 400s)', async () => {
- silenceKeaLoadersErrors() // the 400 loader failure is the scenario under test
- mockCiCards.mockRejectedValue(
- new ApiError('Connect a GitHub data warehouse source to use engineering analytics.', 400)
- )
- logic = engineeringAnalyticsLogic()
- logic.mount()
- await expectLogic(logic).toDispatchActions(['loadCardsFailure'])
-
- expect(logic.values.notConnected).toBe(true)
- expect(logic.values.pullRequestsLoadError).toBe(false)
- expect(logic.values.workflowHealthLoadError).toBe(false)
- })
-
- it('flags notConnected from the workflow-health loader too (the Workflows scene renders no cards)', async () => {
- silenceKeaLoadersErrors() // the 400 loader failure is the scenario under test
- // notConnected must react to any loader's 400, not cards alone — else the Workflows scene
- // could miss the connect prompt.
- mockWorkflowHealth.mockRejectedValue(new ApiError('Connect a GitHub data warehouse source.', 400))
- logic = engineeringAnalyticsLogic()
- logic.mount()
- await expectLogic(logic).toDispatchActions(['loadWorkflowHealthFailure'])
-
- expect(logic.values.notConnected).toBe(true)
- expect(logic.values.workflowHealthLoadError).toBe(false)
- })
-
- it('a cards/PR 500 errors the PR scene only — not the Workflows scene', async () => {
- silenceKeaLoadersErrors() // the 500 loader failure is the scenario under test
- mockCiCards.mockRejectedValue(new ApiError('Internal Server Error', 500))
- logic = engineeringAnalyticsLogic()
- logic.mount()
- await expectLogic(logic).toDispatchActions(['loadCardsFailure'])
-
- expect(logic.values.pullRequestsLoadError).toBe(true)
- expect(logic.values.workflowHealthLoadError).toBe(false)
- expect(logic.values.notConnected).toBe(false)
- })
-
- it('a workflow-health 500 errors the Workflows scene only — not the PR scene', async () => {
- silenceKeaLoadersErrors() // the 500 loader failure is the scenario under test
- mockWorkflowHealth.mockRejectedValue(new ApiError('Internal Server Error', 500))
+ it.each([
+ // A 400 means "connect a source" and must flag notConnected from any loader, else the
+ // Workflows scene (which renders no cards) misses the connect prompt. A 500 errors only
+ // its own scene, so the other keeps rendering.
+ ['cards', 400, { notConnected: true, pullRequestsLoadError: false, workflowHealthLoadError: false }],
+ ['workflow health', 400, { notConnected: true, pullRequestsLoadError: false, workflowHealthLoadError: false }],
+ ['cards', 500, { notConnected: false, pullRequestsLoadError: true, workflowHealthLoadError: false }],
+ ['workflow health', 500, { notConnected: false, pullRequestsLoadError: false, workflowHealthLoadError: true }],
+ ])('a %s loader %i sets exactly the right error flags', async (loader, statusCode, expected) => {
+ silenceKeaLoadersErrors() // the loader failure is the scenario under test
+ const failingMock = loader === 'cards' ? mockCiCards : mockWorkflowHealth
+ const failureAction = loader === 'cards' ? 'loadCardsFailure' : 'loadWorkflowHealthFailure'
+ failingMock.mockRejectedValue(new ApiError('Connect a GitHub data warehouse source.', statusCode))
logic = engineeringAnalyticsLogic()
logic.mount()
- await expectLogic(logic).toDispatchActions(['loadWorkflowHealthFailure'])
+ await expectLogic(logic).toDispatchActions([failureAction])
- expect(logic.values.workflowHealthLoadError).toBe(true)
- expect(logic.values.pullRequestsLoadError).toBe(false)
- expect(logic.values.notConnected).toBe(false)
+ expect({
+ notConnected: logic.values.notConnected,
+ pullRequestsLoadError: logic.values.pullRequestsLoadError,
+ workflowHealthLoadError: logic.values.workflowHealthLoadError,
+ }).toEqual(expected)
})
it.each([
@@ -854,22 +849,6 @@ describe('engineeringAnalyticsLogic', () => {
expect(logic.values.quarantineModeFilter).toBe('all')
})
- it('resetQuarantineFilters returns filters to defaults and clears hasActiveQuarantineFilters', async () => {
- logic = engineeringAnalyticsLogic()
- logic.mount()
- expect(logic.values.hasActiveQuarantineFilters).toBe(false)
-
- logic.actions.setQuarantineSearch('flake')
- logic.actions.setQuarantineLifecycleFilter('active')
- logic.actions.setQuarantineModeFilter('skip')
- logic.actions.setQuarantineOwner('@team/x')
- expect(logic.values.hasActiveQuarantineFilters).toBe(true)
-
- logic.actions.resetQuarantineFilters()
- expect(logic.values.quarantineFilters).toEqual(DEFAULT_QUARANTINE_FILTERS)
- expect(logic.values.hasActiveQuarantineFilters).toBe(false)
- })
-
it('flags quarantineLoadFailed when the quarantine endpoint 400s', async () => {
silenceKeaLoadersErrors() // the loader failure is the scenario under test
mockQuarantine.mockRejectedValue(
@@ -901,26 +880,6 @@ describe('engineeringAnalyticsLogic', () => {
expect(quarantineRequestErrorMessage(error)).toBe(expected)
})
- it('opens the quarantine modal with the given config', async () => {
- logic = engineeringAnalyticsLogic()
- logic.mount()
-
- logic.actions.openQuarantineModal({
- action: 'extend',
- selector: 'a/b.py::T::t',
- runner: 'pytest',
- reason: 'flaky',
- owner: '@team/x',
- issue: 'https://github.com/PostHog/posthog/issues/7',
- mode: 'run',
- })
- expect(logic.values.quarantineModal?.action).toBe('extend')
- expect(logic.values.quarantineModal?.selector).toBe('a/b.py::T::t')
-
- logic.actions.closeQuarantineModal()
- expect(logic.values.quarantineModal).toBeNull()
- })
-
it('a successful submit closes the modal and reloads the register', async () => {
logic = engineeringAnalyticsLogic()
logic.mount()
@@ -935,6 +894,7 @@ describe('engineeringAnalyticsLogic', () => {
issue: '',
mode: 'run',
})
+ expect(logic.values.quarantineModal?.selector).toBe('frontend/src/a.test.ts::renders')
logic.actions.submitQuarantine({
input: {
action: 'quarantine',
@@ -1013,5 +973,8 @@ describe('engineeringAnalyticsLogic', () => {
expect(logic.values.quarantineModal).not.toBeNull()
expect(logic.values.quarantineSubmitLoading).toBe(false)
+
+ logic.actions.closeQuarantineModal()
+ expect(logic.values.quarantineModal).toBeNull()
})
})
diff --git a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.test.ts b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.test.ts
index 69cd6c270b34..b32d6157239e 100644
--- a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.test.ts
+++ b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.test.ts
@@ -48,7 +48,11 @@ describe('workflowRunsLogic', () => {
mockJobAggregates.mockResolvedValue([])
})
+ let unmountFilters: (() => void) | undefined
+
afterEach(() => {
+ unmountFilters?.()
+ unmountFilters = undefined
logic?.unmount()
})
@@ -56,7 +60,7 @@ describe('workflowRunsLogic', () => {
logic = workflowRunsLogic({ repoOwner: 'PostHog', repoName: 'posthog', workflowName: 'CI', sourceId: null })
logic.mount()
const filters = engineeringAnalyticsFiltersLogic()
- filters.mount()
+ unmountFilters = filters.mount()
await expectLogic(logic).toDispatchActions([
'loadRunsSuccess',
'loadRunActivitySuccess',