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.

refactor(eng-analytics): co-locate scopes and shared fixtures (#72904)

Raúl Negrón-Otero0c106186f9ff
diff --git a/products/engineering_analytics/backend/logic/_shared.py b/products/engineering_analytics/backend/logic/_shared.py
index eca561419174..1f77e9529258 100644
--- a/products/engineering_analytics/backend/logic/_shared.py
+++ b/products/engineering_analytics/backend/logic/_shared.py
@@ -32,6 +32,14 @@ def _parse_window(
return parsed_from, parsed_to
+def _require_repo(repo: str | None) -> tuple[str, str]:
+ """`_split_repo` for builders whose repo argument is mandatory."""
+ owner, name = _split_repo(repo)
+ if not (owner and name):
+ raise ValueError("repo must be in 'owner/name' format")
+ return owner, name
+
+
def _split_repo(repo: str | None) -> tuple[str | None, str | None]:
if not repo:
return None, None
diff --git a/products/engineering_analytics/backend/logic/pull_requests.py b/products/engineering_analytics/backend/logic/pull_requests.py
index d1083369fc39..f1a29f773df7 100644
--- a/products/engineering_analytics/backend/logic/pull_requests.py
+++ b/products/engineering_analytics/backend/logic/pull_requests.py
@@ -19,6 +19,7 @@ from products.engineering_analytics.backend.logic._shared import (
_DEFAULT_WINDOW,
_parse_date,
_parse_window,
+ _require_repo,
_split_repo,
)
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
@@ -35,16 +36,12 @@ logger = structlog.get_logger(__name__)
def build_pr_lifecycle(*, curated: CuratedGitHubSource, pr_number: int, repo: str | None) -> PRLifecycle | None:
- owner, name = _split_repo(repo)
- if not (owner and name):
- raise ValueError("repo must be in 'owner/name' format")
+ owner, name = _require_repo(repo)
return query_pr_lifecycle(curated=curated, pr_number=pr_number, repo_owner=owner, repo_name=name)
def build_pr_runs(*, curated: CuratedGitHubSource, pr_number: int, repo: str | None) -> list[WorkflowRunDetail]:
- owner, name = _split_repo(repo)
- if not (owner and name):
- raise ValueError("repo must be in 'owner/name' format")
+ owner, name = _require_repo(repo)
return query_pr_runs(curated=curated, pr_number=pr_number, repo_owner=owner, repo_name=name)
@@ -63,16 +60,12 @@ def build_resolve_branch(
def build_ci_failure_logs(*, curated: CuratedGitHubSource, pr_number: int, repo: str | None) -> CIFailureLogs:
- owner, name = _split_repo(repo)
- if not (owner and name):
- raise ValueError("repo must be in 'owner/name' format")
+ owner, name = _require_repo(repo)
return query_ci_failure_logs(curated=curated, pr_number=pr_number, repo_owner=owner, repo_name=name)
def build_pr_cost(*, curated: CuratedGitHubSource, pr_number: int, repo: str | None) -> PRCostSummary:
- owner, name = _split_repo(repo)
- if not (owner and name):
- raise ValueError("repo must be in 'owner/name' format")
+ owner, name = _require_repo(repo)
# LLM token spend is an additive component joined by branch from the events table, merged onto the
# CI cost summary. Kept sequential: HogQL table resolution reads warehouse metadata through the
# request's DB connection, which worker threads don't share.
diff --git a/products/engineering_analytics/backend/logic/suite_health.py b/products/engineering_analytics/backend/logic/suite_health.py
index e4815133277a..77a9a28ce097 100644
--- a/products/engineering_analytics/backend/logic/suite_health.py
+++ b/products/engineering_analytics/backend/logic/suite_health.py
@@ -14,9 +14,9 @@ from products.engineering_analytics.backend.logic.queries.flaky_tests import que
# (per-test spans are high-volume and the short Traces retention makes older data spotty anyway).
# The signal thresholds double as the bar for the team CI health rollups.
_DEFAULT_FLAKY_WINDOW = "-7d"
-_MAX_FLAKY_WINDOW_DAYS = 30
-_DEFAULT_FLAKY_MIN_RERUN_PASSES = 1
-_DEFAULT_FLAKY_MIN_FAILED_PRS = 3
+MAX_FLAKY_WINDOW_DAYS = 30
+DEFAULT_FLAKY_MIN_RERUN_PASSES = 1
+DEFAULT_FLAKY_MIN_FAILED_PRS = 3
_DEFAULT_FLAKY_LIMIT = 50
_MAX_FLAKY_LIMIT = 200
@@ -37,10 +37,10 @@ def build_flaky_tests(
limit: int | None = None,
) -> FlakyTestList:
parsed_from, parsed_to = _parse_window(
- curated.team, date_from, date_to, default=_DEFAULT_FLAKY_WINDOW, max_days=_MAX_FLAKY_WINDOW_DAYS
+ curated.team, date_from, date_to, default=_DEFAULT_FLAKY_WINDOW, max_days=MAX_FLAKY_WINDOW_DAYS
)
- min_rerun_passes = min_rerun_passes if min_rerun_passes is not None else _DEFAULT_FLAKY_MIN_RERUN_PASSES
- min_failed_prs = min_failed_prs if min_failed_prs is not None else _DEFAULT_FLAKY_MIN_FAILED_PRS
+ min_rerun_passes = min_rerun_passes if min_rerun_passes is not None else DEFAULT_FLAKY_MIN_RERUN_PASSES
+ min_failed_prs = min_failed_prs if min_failed_prs is not None else DEFAULT_FLAKY_MIN_FAILED_PRS
# A zero threshold would make its HAVING arm trivially true and silently qualify every
# test with any signal span — require an explicit positive bar instead.
if min_rerun_passes < 1 or min_failed_prs < 1:
diff --git a/products/engineering_analytics/backend/logic/teams.py b/products/engineering_analytics/backend/logic/teams.py
index 3fe3fca32ad9..bae7aa3b4629 100644
--- a/products/engineering_analytics/backend/logic/teams.py
+++ b/products/engineering_analytics/backend/logic/teams.py
@@ -9,9 +9,9 @@ from products.engineering_analytics.backend.logic.queries.team_ci_health import
)
from products.engineering_analytics.backend.logic.queries.team_merge_trend import query_team_merge_trend
from products.engineering_analytics.backend.logic.suite_health import (
- _DEFAULT_FLAKY_MIN_FAILED_PRS,
- _DEFAULT_FLAKY_MIN_RERUN_PASSES,
- _MAX_FLAKY_WINDOW_DAYS,
+ DEFAULT_FLAKY_MIN_FAILED_PRS,
+ DEFAULT_FLAKY_MIN_RERUN_PASSES,
+ MAX_FLAKY_WINDOW_DAYS,
)
# Team CI health rollups scan the current window plus an equal-length prior twin, so the
@@ -34,10 +34,10 @@ def build_team_ci_health(
limit: int | None = None,
) -> TeamCIHealthList:
parsed_from, parsed_to = _parse_window(
- curated.team, date_from, date_to, default=_DEFAULT_TEAM_WINDOW, max_days=_MAX_FLAKY_WINDOW_DAYS
+ curated.team, date_from, date_to, default=_DEFAULT_TEAM_WINDOW, max_days=MAX_FLAKY_WINDOW_DAYS
)
- min_rerun_passes = min_rerun_passes if min_rerun_passes is not None else _DEFAULT_FLAKY_MIN_RERUN_PASSES
- min_failed_prs = min_failed_prs if min_failed_prs is not None else _DEFAULT_FLAKY_MIN_FAILED_PRS
+ min_rerun_passes = min_rerun_passes if min_rerun_passes is not None else DEFAULT_FLAKY_MIN_RERUN_PASSES
+ min_failed_prs = min_failed_prs if min_failed_prs is not None else DEFAULT_FLAKY_MIN_FAILED_PRS
# Same explicit-positive-bar rule as the flaky leaderboard: a zero threshold would
# silently qualify every test with any signal span.
if min_rerun_passes < 1 or min_failed_prs < 1:
@@ -67,7 +67,7 @@ def build_team_ci_activity(
if not normalized_team:
raise ValueError("owner_team is required")
parsed_from, parsed_to = _parse_window(
- curated.team, date_from, date_to, default=_DEFAULT_TEAM_WINDOW, max_days=_MAX_FLAKY_WINDOW_DAYS
+ curated.team, date_from, date_to, default=_DEFAULT_TEAM_WINDOW, max_days=MAX_FLAKY_WINDOW_DAYS
)
test_limit = test_limit if test_limit is not None else _DEFAULT_TEAM_TEST_LIMIT
if not 1 <= test_limit <= _MAX_TEAM_TEST_LIMIT:
@@ -92,7 +92,7 @@ def build_team_merge_trend(
if not normalized_team:
raise ValueError("owner_team is required")
parsed_from, parsed_to = _parse_window(
- curated.team, date_from, date_to, default=_DEFAULT_TEAM_WINDOW, max_days=_MAX_FLAKY_WINDOW_DAYS
+ curated.team, date_from, date_to, default=_DEFAULT_TEAM_WINDOW, max_days=MAX_FLAKY_WINDOW_DAYS
)
return query_team_merge_trend(
curated=curated,
diff --git a/products/engineering_analytics/backend/logic/workflows.py b/products/engineering_analytics/backend/logic/workflows.py
index f417a34ea609..fbdf2926d498 100644
--- a/products/engineering_analytics/backend/logic/workflows.py
+++ b/products/engineering_analytics/backend/logic/workflows.py
@@ -13,7 +13,7 @@ from products.engineering_analytics.backend.facade.contracts import (
WorkflowRunDetail,
WorkflowRunnerCost,
)
-from products.engineering_analytics.backend.logic._shared import _DEFAULT_WINDOW, _parse_window, _split_repo
+from products.engineering_analytics.backend.logic._shared import _DEFAULT_WINDOW, _parse_window, _require_repo
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
from products.engineering_analytics.backend.logic.queries.ci_failure_logs import query_run_failure_logs
from products.engineering_analytics.backend.logic.queries.current_branch_health import query_current_branch_health
@@ -57,9 +57,7 @@ def build_workflow_run_list(
date_to: str | None = None,
branch: str | None = None,
) -> list[WorkflowRunDetail]:
- owner, name = _split_repo(repo)
- if not (owner and name):
- raise ValueError("repo must be in 'owner/name' format")
+ owner, name = _require_repo(repo)
parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_WINDOW)
return query_workflow_run_list(
curated=curated,
@@ -81,9 +79,7 @@ def build_workflow_run_activity(
date_to: str | None = None,
branch: str | None = None,
) -> WorkflowRunActivity:
- owner, name = _split_repo(repo)
- if not (owner and name):
- raise ValueError("repo must be in 'owner/name' format")
+ owner, name = _require_repo(repo)
parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_WINDOW)
return query_workflow_run_activity(
curated=curated,
@@ -105,9 +101,7 @@ def build_workflow_runner_costs(
date_to: str | None = None,
branch: str | None = None,
) -> list[WorkflowRunnerCost]:
- owner, name = _split_repo(repo)
- if not (owner and name):
- raise ValueError("repo must be in 'owner/name' format")
+ owner, name = _require_repo(repo)
parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_WINDOW)
return query_workflow_runner_costs(
curated=curated,
diff --git a/products/engineering_analytics/backend/presentation/views/__init__.py b/products/engineering_analytics/backend/presentation/views/__init__.py
index 5de97c8b3c7e..daec83f07632 100644
--- a/products/engineering_analytics/backend/presentation/views/__init__.py
+++ b/products/engineering_analytics/backend/presentation/views/__init__.py
@@ -13,7 +13,7 @@ from products.engineering_analytics.backend.presentation.views._base import (
)
from products.engineering_analytics.backend.presentation.views.pull_requests import PullRequestActionsMixin
from products.engineering_analytics.backend.presentation.views.sources import SourcesMixin
-from products.engineering_analytics.backend.presentation.views.suite_health import TestHealthActionsMixin
+from products.engineering_analytics.backend.presentation.views.suite_health import SuiteHealthActionsMixin
from products.engineering_analytics.backend.presentation.views.teams import TeamActionsMixin
from products.engineering_analytics.backend.presentation.views.workflows import WorkflowActionsMixin
@@ -23,45 +23,19 @@ class EngineeringAnalyticsViewSet(
SourcesMixin,
PullRequestActionsMixin,
WorkflowActionsMixin,
- TestHealthActionsMixin,
+ SuiteHealthActionsMixin,
TeamActionsMixin,
EngineeringAnalyticsViewSetBase,
):
"""PR and CI lifecycle analytics over the GitHub warehouse data."""
- # Grouped by mixin; TestScopeEnrollment asserts this stays in lockstep with the actions.
+ # Personal API keys get 403 on any action not enrolled here. Each mixin declares its own
+ # actions; TestScopeEnrollment asserts the composition stays in lockstep with the @actions.
scope_object_read_actions = [
- # sources
- "sources",
- # pull_requests
- "ci_cards",
- "pull_requests",
- "pr_lifecycle",
- "resolve_branch",
- "pr_runs",
- "ci_failure_logs",
- "pr_cost",
- "author_workflow_costs",
- # workflows
- "workflow_health",
- "workflow_run",
- "workflow_runs",
- "workflow_run_activity",
- "workflow_runner_costs",
- "workflow_jobs",
- "repo_overview",
- "current_branch_health",
- "repo_run_activity",
- "master_failures",
- "run_failure_logs",
- "job_aggregates",
- # test_health
- "flaky_tests",
- "broken_tests",
- "quarantine",
- # teams
- "team_ci_health",
- "team_ci_activity",
- "team_merge_trend",
+ *SourcesMixin.READ_ACTIONS,
+ *PullRequestActionsMixin.READ_ACTIONS,
+ *WorkflowActionsMixin.READ_ACTIONS,
+ *SuiteHealthActionsMixin.READ_ACTIONS,
+ *TeamActionsMixin.READ_ACTIONS,
]
- scope_object_write_actions: list[str] = ["quarantine_request"]
+ scope_object_write_actions: list[str] = [*SuiteHealthActionsMixin.WRITE_ACTIONS]
diff --git a/products/engineering_analytics/backend/presentation/views/pull_requests.py b/products/engineering_analytics/backend/presentation/views/pull_requests.py
index 4180b658aff7..83d79ae5a60f 100644
--- a/products/engineering_analytics/backend/presentation/views/pull_requests.py
+++ b/products/engineering_analytics/backend/presentation/views/pull_requests.py
@@ -31,6 +31,17 @@ from products.engineering_analytics.backend.presentation.views._base import (
class PullRequestActionsMixin(EngineeringAnalyticsViewSetBase):
+ READ_ACTIONS = [
+ "ci_cards",
+ "pull_requests",
+ "pr_lifecycle",
+ "resolve_branch",
+ "pr_runs",
+ "ci_failure_logs",
+ "pr_cost",
+ "author_workflow_costs",
+ ]
+
@extend_schema(
operation_id="engineering_analytics_ci_cards",
parameters=[_SOURCE_ID, _REPO],
diff --git a/products/engineering_analytics/backend/presentation/views/sources.py b/products/engineering_analytics/backend/presentation/views/sources.py
index e880c64b2690..684fbbd87cb0 100644
--- a/products/engineering_analytics/backend/presentation/views/sources.py
+++ b/products/engineering_analytics/backend/presentation/views/sources.py
@@ -11,6 +11,8 @@ from products.engineering_analytics.backend.presentation.views._base import Engi
class SourcesMixin(EngineeringAnalyticsViewSetBase):
+ READ_ACTIONS = ["sources"]
+
@extend_schema(
operation_id="engineering_analytics_sources",
responses={200: GitHubSourceSerializer(many=True)},
diff --git a/products/engineering_analytics/backend/presentation/views/suite_health.py b/products/engineering_analytics/backend/presentation/views/suite_health.py
index 9532181d1a08..416490554073 100644
--- a/products/engineering_analytics/backend/presentation/views/suite_health.py
+++ b/products/engineering_analytics/backend/presentation/views/suite_health.py
@@ -28,7 +28,10 @@ from products.engineering_analytics.backend.presentation.views._base import (
)
-class TestHealthActionsMixin(EngineeringAnalyticsViewSetBase):
+class SuiteHealthActionsMixin(EngineeringAnalyticsViewSetBase):
+ READ_ACTIONS = ["flaky_tests", "broken_tests", "quarantine"]
+ WRITE_ACTIONS = ["quarantine_request"]
+
@extend_schema(
operation_id="engineering_analytics_flaky_tests",
parameters=[
diff --git a/products/engineering_analytics/backend/presentation/views/teams.py b/products/engineering_analytics/backend/presentation/views/teams.py
index 4d4cd4fb1f55..db354d689bba 100644
--- a/products/engineering_analytics/backend/presentation/views/teams.py
+++ b/products/engineering_analytics/backend/presentation/views/teams.py
@@ -23,6 +23,8 @@ from products.engineering_analytics.backend.presentation.views._base import (
class TeamActionsMixin(EngineeringAnalyticsViewSetBase):
+ READ_ACTIONS = ["team_ci_health", "team_ci_activity", "team_merge_trend"]
+
@extend_schema(
operation_id="engineering_analytics_team_ci_health",
parameters=[
diff --git a/products/engineering_analytics/backend/presentation/views/workflows.py b/products/engineering_analytics/backend/presentation/views/workflows.py
index 0c46ee0dddfe..baef8834a9bb 100644
--- a/products/engineering_analytics/backend/presentation/views/workflows.py
+++ b/products/engineering_analytics/backend/presentation/views/workflows.py
@@ -37,6 +37,21 @@ from products.engineering_analytics.backend.presentation.views._base import (
class WorkflowActionsMixin(EngineeringAnalyticsViewSetBase):
+ READ_ACTIONS = [
+ "workflow_health",
+ "workflow_run",
+ "workflow_runs",
+ "workflow_run_activity",
+ "workflow_runner_costs",
+ "workflow_jobs",
+ "repo_overview",
+ "current_branch_health",
+ "repo_run_activity",
+ "master_failures",
+ "run_failure_logs",
+ "job_aggregates",
+ ]
+
@extend_schema(
operation_id="engineering_analytics_workflow_health",
parameters=[_WORKFLOW_DATE_FROM, _DATE_TO, _BRANCH, _RUN_SCOPE, _SOURCE_ID, _REPO],
diff --git a/products/engineering_analytics/backend/tests/_github_fixtures.py b/products/engineering_analytics/backend/tests/_github_fixtures.py
new file mode 100644
index 000000000000..8522674c2409
--- /dev/null
+++ b/products/engineering_analytics/backend/tests/_github_fixtures.py
@@ -0,0 +1,181 @@
+"""GitHub source and warehouse-table fixtures shared across this product's test files."""
+
+import tempfile
+from pathlib import Path
+from typing import Any
+
+from posthog.test.base import BaseTest
+
+import pandas as pd
+
+from posthog.models.team import Team
+
+from products.engineering_analytics.backend.logic.sources import (
+ PULL_REQUESTS_SCHEMA,
+ WORKFLOW_RUNS_SCHEMA,
+ GitHubTables,
+)
+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
+
+TEST_BUCKET = "test_storage_bucket-posthog.products.engineering_analytics.github_fixtures"
+
+# Non-default prefix on purpose: every fixture below lands tables named
+# `myprefixgithub_*`, so the resolver and builders are proven against a name the old
+# hardcoded `github_*` constants would never have matched.
+GITHUB_SOURCE_PREFIX = "myprefix"
+
+
+def create_github_source(
+ team: Team, *, prefix: str = GITHUB_SOURCE_PREFIX, source_id: str = "gh-source", repository: str = ""
+) -> ExternalDataSource:
+ return ExternalDataSource.objects.create(
+ team=team,
+ source_id=source_id,
+ connection_id=source_id,
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type=ExternalDataSourceType.GITHUB,
+ prefix=prefix,
+ job_inputs={"repository": repository} if repository else {},
+ )
+
+
+def link_schema(
+ team: Team,
+ source: ExternalDataSource,
+ *,
+ name: str,
+ table: DataWarehouseTable | None,
+ should_sync: bool = True,
+) -> ExternalDataSchema:
+ return ExternalDataSchema.objects.create(team=team, source=source, name=name, table=table, should_sync=should_sync)
+
+
+def create_warehouse_table_row(
+ team: Team, *, name: str, source: ExternalDataSource | None = None
+) -> DataWarehouseTable:
+ # ORM-only table (no object storage); for resolver/mapping tests that mock the query.
+ return DataWarehouseTable.objects.create(
+ team=team,
+ name=name,
+ format=DataWarehouseTable.TableFormat.CSVWithNames,
+ url_pattern="",
+ external_data_source=source,
+ columns={},
+ )
+
+
+def connect_github_source_without_data(
+ team: Team, *, prefix: str = GITHUB_SOURCE_PREFIX, repository: str = ""
+) -> GitHubTables:
+ """A GitHub source with pull_requests/workflow_runs schemas over empty ORM tables.
+
+ The resolver finds these without touching object storage; pair with a mocked query
+ when only resolution (not real warehouse data) matters.
+ """
+ source = create_github_source(team, prefix=prefix, repository=repository)
+ pr_table = create_warehouse_table_row(team, name=f"{prefix}github_pull_requests", source=source)
+ run_table = create_warehouse_table_row(team, name=f"{prefix}github_workflow_runs", source=source)
+ link_schema(team, source, name=PULL_REQUESTS_SCHEMA, table=pr_table)
+ link_schema(team, source, name=WORKFLOW_RUNS_SCHEMA, table=run_table)
+ return GitHubTables(pull_requests=pr_table.name, workflow_runs=run_table.name, repository=repository)
+
+
+def _user(login: str) -> str:
+ return f'{{"login": "{login}", "avatar_url": "https://avatars/{login}"}}'
+
+
+def _base(full_name: str, ref: str = "") -> str:
+ return f'{{"ref": "{ref}", "repo": {{"full_name": "{full_name}"}}}}'
+
+
+def _labels(*names: str) -> str:
+ return "[" + ", ".join(f'{{"name": "{name}"}}' for name in names) + "]"
+
+
+def _pr_row(
+ number: int,
+ login: str,
+ state: str,
+ draft: int,
+ created_at: str,
+ *,
+ merged_at: str | None = None,
+ head_sha: str = "",
+ head_ref: str = "",
+ base_ref: str = "",
+ full_name: str = "PostHog/posthog",
+ labels: tuple[str, ...] = (),
+) -> dict[str, Any]:
+ return {
+ "id": 1000 + number,
+ "number": number,
+ "title": f"PR {number}",
+ "state": state,
+ "draft": draft,
+ "created_at": created_at,
+ "updated_at": merged_at or created_at,
+ "merged_at": merged_at,
+ "closed_at": merged_at,
+ "user": _user(login),
+ "head": f'{{"sha": "{head_sha}", "ref": "{head_ref}"}}',
+ "base": _base(full_name, base_ref),
+ "labels": _labels(*labels),
+ }
+
+
+def _run_row(
+ run_id: int,
+ name: str,
+ head_sha: str,
+ status: str,
+ conclusion: str | None,
+ run_started_at: str,
+ updated_at: str,
+ *,
+ full_name: str = "PostHog/posthog",
+ run_attempt: int = 1,
+ pr_number: int | None = None,
+ head_branch: str = "main",
+) -> dict[str, Any]:
+ return {
+ "id": run_id,
+ "name": name,
+ "head_sha": head_sha,
+ "head_branch": head_branch,
+ "status": status,
+ "conclusion": conclusion,
+ "created_at": run_started_at,
+ "run_started_at": run_started_at,
+ "updated_at": updated_at,
+ "run_attempt": run_attempt,
+ # Mirror the real Nullable(String) column: an unassociated run lands NULL, not "[]",
+ # so the builder's ifNull(pull_requests, '[]') guard is exercised on the real path.
+ "pull_requests": f'[{{"number": {pr_number}}}]' if pr_number is not None else None,
+ "repository": f'{{"full_name": "{full_name}"}}',
+ }
+
+
+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.
+ 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:
+ table, _source, _credential, _df, cleanup = create_data_warehouse_table_from_csv(
+ csv_path=Path(tmp.name),
+ table_name=base_name,
+ table_columns=columns,
+ test_bucket=TEST_BUCKET,
+ 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 96f48fd7cb6b..33f42bc0d48a 100644
--- a/products/engineering_analytics/backend/tests/_logic_helpers.py
+++ b/products/engineering_analytics/backend/tests/_logic_helpers.py
@@ -12,9 +12,11 @@ from django.utils import timezone
import pandas as pd
-from products.engineering_analytics.backend.tests.test_views import (
- _PULL_REQUESTS_COLUMNS,
- _WORKFLOW_RUNS_COLUMNS,
+from products.engineering_analytics.backend.logic.views.source_schema import (
+ PULL_REQUESTS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
+)
+from products.engineering_analytics.backend.tests._github_fixtures import (
GITHUB_SOURCE_PREFIX,
_pr_row,
_run_row,
@@ -179,7 +181,7 @@ class _EndpointsWarehouseMixin(_WarehouseMixin):
def _seed(self) -> None:
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[
# open, recent (<7d), human, failing CI on sha10
_pr_row(10, "alice", "open", 0, _ago(1), head_sha="sha10", labels=("bug",)),
@@ -199,7 +201,7 @@ class _EndpointsWarehouseMixin(_WarehouseMixin):
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[
_run_row(2001, "CI", "sha10", "completed", "failure", _ago(1), _ago(1), pr_number=10),
_run_row(2002, "CI", "sha11", "completed", "success", _ago(2), _ago(2), pr_number=11),
diff --git a/products/engineering_analytics/backend/tests/test_access_control.py b/products/engineering_analytics/backend/tests/test_access_control.py
index 55d182bab89b..0801d356eb7f 100644
--- a/products/engineering_analytics/backend/tests/test_access_control.py
+++ b/products/engineering_analytics/backend/tests/test_access_control.py
@@ -31,7 +31,7 @@ from products.engineering_analytics.backend.logic.sources import (
WORKFLOW_RUNS_SCHEMA,
resolve_github_tables,
)
-from products.engineering_analytics.backend.tests.test_views import (
+from products.engineering_analytics.backend.tests._github_fixtures import (
GITHUB_SOURCE_PREFIX,
connect_github_source_without_data,
create_github_source,
diff --git a/products/engineering_analytics/backend/tests/test_flaky_tests.py b/products/engineering_analytics/backend/tests/test_flaky_tests.py
index a1fe32776477..74b0f6f7653c 100644
--- a/products/engineering_analytics/backend/tests/test_flaky_tests.py
+++ b/products/engineering_analytics/backend/tests/test_flaky_tests.py
@@ -10,7 +10,7 @@ from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.traces.spans import TRACE_SPANS_DISTRIBUTED_TABLE_SQL, TRACE_SPANS_TABLE_SQL
from products.engineering_analytics.backend.logic.queries._test_spans import selector_from_nodeid
-from products.engineering_analytics.backend.tests.test_views import connect_github_source_without_data
+from products.engineering_analytics.backend.tests._github_fixtures import connect_github_source_without_data
from products.warehouse_sources.backend.facade.models import ExternalDataSource
T_PRS = "posthog/api/test/test_prs/TestPRs::test_flaky_on_prs"
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 566b4655b6f8..7596717f2235 100644
--- a/products/engineering_analytics/backend/tests/test_logic_pull_requests.py
+++ b/products/engineering_analytics/backend/tests/test_logic_pull_requests.py
@@ -11,7 +11,16 @@ from parameterized import parameterized
from products.engineering_analytics.backend.facade import api
from products.engineering_analytics.backend.facade.contracts import MetricQuality, PRLifecycleEventKind, PRState
-from products.engineering_analytics.backend.logic.views.source_schema import WORKFLOW_JOBS_COLUMNS
+from products.engineering_analytics.backend.logic.views.source_schema import (
+ PULL_REQUESTS_COLUMNS,
+ WORKFLOW_JOBS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
+)
+from products.engineering_analytics.backend.tests._github_fixtures import (
+ _pr_row,
+ _run_row,
+ connect_github_source_without_data,
+)
from products.engineering_analytics.backend.tests._logic_helpers import (
_PR_LIST,
_RUN_QUERY,
@@ -24,13 +33,6 @@ from products.engineering_analytics.backend.tests._logic_helpers import (
_resp,
_WarehouseMixin,
)
-from products.engineering_analytics.backend.tests.test_views import (
- _PULL_REQUESTS_COLUMNS,
- _WORKFLOW_RUNS_COLUMNS,
- _pr_row,
- _run_row,
- connect_github_source_without_data,
-)
class TestPRLifecycleMapping(BaseTest):
@@ -267,12 +269,12 @@ class TestPullRequestEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# With the jobs source synced, the list carries per-PR cost + billable minutes.
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(70, "alice", "open", 0, _ago(1), head_sha="sha70")],
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[_run_row(9400, "CI", "sha70", "completed", "success", _ago(1), _ago(1), pr_number=70)],
)
self._create_table(
@@ -289,12 +291,12 @@ class TestPullRequestEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# silently truncate to the first 100 (the truncation that made PR detail cost disagree with the list).
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(71, "alice", "open", 0, _ago(1), head_sha="sha71")],
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[_run_row(9700, "CI", "sha71", "completed", "success", _ago(1), _ago(1), pr_number=71)],
)
job_count = 150
@@ -320,12 +322,12 @@ class TestPullRequestEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# normal job's 120s survives = 2 billable min, depot 4-core (2x) at $0.004/min = $0.016.
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(72, "alice", "open", 0, _ago(1), head_sha="sha72")],
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[_run_row(9800, "CI", "sha72", "completed", "success", _ago(1), _ago(1), pr_number=72)],
)
self._create_table(
@@ -347,7 +349,7 @@ class TestPullRequestEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# The author filter scopes the list to one author's PRs (drives the author page).
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[
_pr_row(81, "alice", "open", 0, _ago(1), head_sha="sha81"),
_pr_row(82, "bob", "open", 0, _ago(1), head_sha="sha82"),
@@ -355,7 +357,7 @@ class TestPullRequestEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[_run_row(8100, "CI", "sha81", "completed", "success", _ago(1), _ago(1), pr_number=81)],
)
assert {i.number for i in api.list_pull_requests(team=self.team, author="alice").items} == {81}
@@ -366,7 +368,7 @@ class TestPullRequestEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# and PRs on other branches are excluded.
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[
_pr_row(62, "bob", "closed", 0, _ago(6), merged_at=_ago(1), head_sha="sha62", head_ref="feat/login"),
_pr_row(61, "alice", "open", 0, _ago(2), head_sha="sha61", head_ref="feat/login"),
@@ -375,7 +377,7 @@ class TestPullRequestEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
)
# Source resolution requires the workflow_runs schema synced too (SPEC: both endpoints
# required together), even though the branch path only reads the PR snapshot.
- self._create_table("github_workflow_runs", _WORKFLOW_RUNS_COLUMNS, [])
+ self._create_table("github_workflow_runs", WORKFLOW_RUNS_COLUMNS, [])
matches = api.resolve_branch(team=self.team, branch="feat/login")
assert [m.number for m in matches] == [61, 62] # only feat/login PRs, open first
# A branch matching no PR resolves to nothing (empty list, not an error).
@@ -385,7 +387,7 @@ class TestPullRequestEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# Same head ref reused across PRs over time: an old one merged months ago and a newer open one.
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[
_pr_row(
70, "bob", "closed", 0, _ago(120), merged_at=_ago(110), head_sha="sha70", head_ref="feat/reuse"
@@ -393,7 +395,7 @@ class TestPullRequestEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
_pr_row(71, "alice", "open", 0, _ago(2), head_sha="sha71", head_ref="feat/reuse"),
],
)
- self._create_table("github_workflow_runs", _WORKFLOW_RUNS_COLUMNS, [])
+ self._create_table("github_workflow_runs", WORKFLOW_RUNS_COLUMNS, [])
# No timestamp: open PR wins on the open-first/recency fallback.
assert [m.number for m in api.resolve_branch(team=self.team, branch="feat/reuse")] == [71, 70]
# A timestamp inside the old PR's lifetime window ranks it first, even though the newer PR is open.
@@ -405,12 +407,12 @@ class TestPullRequestEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# The PR detail lists runs across all of the PR's commits (by association), not just head SHA.
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(70, "alice", "open", 0, _ago(1), head_sha="shaA")],
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[
_run_row(9300, "CI", "shaA", "completed", "success", _ago(2), _ago(2), pr_number=70),
_run_row(9301, "CI", "shaB", "completed", "failure", _ago(1), _ago(1), pr_number=70),
@@ -426,12 +428,12 @@ class TestPullRequestEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# runners; absent jobs source → graceful empty with jobs_available False.
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(60, "alice", "open", 0, _ago(1), head_sha="sha60")],
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[
_run_row(9100, "CI", "sha60a", "completed", "success", _ago(2), _ago(2), pr_number=60),
_run_row(9101, "CI", "sha60b", "completed", "failure", _ago(1), _ago(1), pr_number=60),
@@ -477,7 +479,7 @@ class TestPullRequestEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# one repo today, so this is the defensive guarantee, exercised by seeding both into one.
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[
_pr_row(10, "alice", "open", 0, _ago(1), head_sha="sha10", full_name="PostHog/posthog"),
_pr_row(10, "bob", "open", 0, _ago(1), head_sha="shaB10", full_name="PostHog/posthog.com"),
@@ -485,7 +487,7 @@ class TestPullRequestEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[
_run_row(3001, "CI", "sha10", "completed", "success", _ago(1), _ago(1), pr_number=10),
_run_row(
@@ -565,7 +567,7 @@ class TestPRLLMSpendWarehouse(_WarehouseMixin, BaseTest):
# must exist for the source to resolve even though LLM spend never reads it (mixin gotcha).
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[
_pr_row(
number,
@@ -582,7 +584,7 @@ class TestPRLLMSpendWarehouse(_WarehouseMixin, BaseTest):
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[_run_row(number * 100, "CI", f"sha{number}", "completed", "success", _ago(4), _ago(4), pr_number=number)],
)
@@ -633,12 +635,12 @@ class TestPRLLMSpendWarehouse(_WarehouseMixin, BaseTest):
# Open PR whose branch no event carries — spend stays null so the UI hides the row.
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(81, "alice", "open", 0, _ago(2), head_sha="sha81", head_ref="feat/empty")],
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[_run_row(8100, "CI", "sha81", "completed", "success", _ago(1), _ago(1), pr_number=81)],
)
cost = api.get_pr_cost(team=self.team, pr_number=81, repo="PostHog/posthog")
@@ -732,7 +734,7 @@ class TestPRLLMSpendWarehouse(_WarehouseMixin, BaseTest):
created = _ago(5)
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[
_pr_row(90, "alice", "closed", 0, created, merged_at=_ago(3), head_sha="sha90a", head_ref="feat/stale"),
_pr_row(90, "alice", "closed", 0, created, merged_at=_ago(1), head_sha="sha90b", head_ref="feat/fresh"),
@@ -740,7 +742,7 @@ class TestPRLLMSpendWarehouse(_WarehouseMixin, BaseTest):
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[_run_row(9000, "CI", "sha90b", "completed", "success", _ago(4), _ago(4), pr_number=90)],
)
self._generation(branch="feat/fresh", days_ago=4, cost=3.0, input_tokens=30, output_tokens=10)
diff --git a/products/engineering_analytics/backend/tests/test_logic_sources.py b/products/engineering_analytics/backend/tests/test_logic_sources.py
index 40142e5a3db6..f57f24f0a21b 100644
--- a/products/engineering_analytics/backend/tests/test_logic_sources.py
+++ b/products/engineering_analytics/backend/tests/test_logic_sources.py
@@ -17,14 +17,16 @@ from products.engineering_analytics.backend.logic.sources import (
resolve_github_tables,
resolve_job_cost_source_pairs,
)
-from products.engineering_analytics.backend.tests._logic_helpers import _ago, _WarehouseMixin
-from products.engineering_analytics.backend.tests.test_views import (
- _PULL_REQUESTS_COLUMNS,
- _WORKFLOW_RUNS_COLUMNS,
+from products.engineering_analytics.backend.logic.views.source_schema import (
+ PULL_REQUESTS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
+)
+from products.engineering_analytics.backend.tests._github_fixtures import (
_pr_row,
create_warehouse_table_row,
link_schema,
)
+from products.engineering_analytics.backend.tests._logic_helpers import _ago, _WarehouseMixin
from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource
from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
@@ -473,12 +475,12 @@ class TestMultiSourceResolutionWarehouse(_WarehouseMixin, BaseTest):
older = self._connect_source(source_id="src-a", prefix="repoa", repository="PostHog/posthog")
newer = self._connect_source(source_id="src-b", prefix="repob", repository="PostHog/posthog.com")
# Source A (older, other repo): synced but holds no PR on the branch.
- self._create_table("github_pull_requests", _PULL_REQUESTS_COLUMNS, [], source=older, prefix="repoa")
- self._create_table("github_workflow_runs", _WORKFLOW_RUNS_COLUMNS, [], source=older, prefix="repoa")
+ self._create_table("github_pull_requests", PULL_REQUESTS_COLUMNS, [], source=older, prefix="repoa")
+ self._create_table("github_workflow_runs", WORKFLOW_RUNS_COLUMNS, [], source=older, prefix="repoa")
# Source B (newer, target repo): holds the feat/login PR.
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[
_pr_row(
61,
@@ -494,7 +496,7 @@ class TestMultiSourceResolutionWarehouse(_WarehouseMixin, BaseTest):
source=newer,
prefix="repob",
)
- self._create_table("github_workflow_runs", _WORKFLOW_RUNS_COLUMNS, [], source=newer, prefix="repob")
+ self._create_table("github_workflow_runs", WORKFLOW_RUNS_COLUMNS, [], source=newer, prefix="repob")
# Clone-URL casing: both the source hint and the repo filter compare case-insensitively.
matches = api.resolve_branch(team=self.team, branch="feat/login", repo="posthog/POSTHOG.com")
diff --git a/products/engineering_analytics/backend/tests/test_logic_workflows.py b/products/engineering_analytics/backend/tests/test_logic_workflows.py
index 3072646878f9..4b48a71d9c3e 100644
--- a/products/engineering_analytics/backend/tests/test_logic_workflows.py
+++ b/products/engineering_analytics/backend/tests/test_logic_workflows.py
@@ -12,7 +12,16 @@ from products.engineering_analytics.backend.logic import build_workflow_health
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
from products.engineering_analytics.backend.logic.queries.pr_cost import query_cost_per_merge_series
from products.engineering_analytics.backend.logic.sources import GitHubTables
-from products.engineering_analytics.backend.logic.views.source_schema import WORKFLOW_JOBS_COLUMNS
+from products.engineering_analytics.backend.logic.views.source_schema import (
+ PULL_REQUESTS_COLUMNS,
+ WORKFLOW_JOBS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
+)
+from products.engineering_analytics.backend.tests._github_fixtures import (
+ _pr_row,
+ _run_row,
+ connect_github_source_without_data,
+)
from products.engineering_analytics.backend.tests._logic_helpers import (
_RUN_QUERY,
_ago,
@@ -22,13 +31,6 @@ from products.engineering_analytics.backend.tests._logic_helpers import (
_job_row,
_resp,
)
-from products.engineering_analytics.backend.tests.test_views import (
- _PULL_REQUESTS_COLUMNS,
- _WORKFLOW_RUNS_COLUMNS,
- _pr_row,
- _run_row,
- connect_github_source_without_data,
-)
class TestWorkflowEndpointMapping(BaseTest):
@@ -197,7 +199,7 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# chart series empty. The default call keeps the series for the UI.
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[
# human, merged in window: open->merge = 8 days; the median's only sample
_pr_row(80, "alice", "closed", 0, _ago(10), merged_at=_ago(2), head_sha="sha80"),
@@ -209,7 +211,7 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[
_run_row(9500, "CI", "sha80", "completed", "success", _ago(2), _ago(2), pr_number=80),
_run_row(9501, "CI", "sha81", "completed", "success", _ago(3), _ago(3), pr_number=81, run_attempt=2),
@@ -255,12 +257,12 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# A -30d window puts its prev twin at [-60d, -30d), so _ago(45) lands squarely in it.
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(60, "alice", "open", 0, _ago(2), head_sha="sha60")],
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[
_run_row(6001, "CI", "sha60", "completed", "success", _ago(2), _ago(2), pr_number=60),
_run_row(6002, "CI", "sha60p", "completed", "success", _ago(45), _ago(45), pr_number=60),
@@ -273,7 +275,7 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
def test_workflow_health_duration_percentiles_exclude_cancelled_failed_and_noop_runs(self) -> None:
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(90, "alice", "open", 0, _ago(1), head_sha="sha90")],
)
# Every real success shares one duration, so the percentile population is exactly 100; any
@@ -281,7 +283,7 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
conclusions = [("success", 100)] * 2 + [("success", 4)] * 3 + [("cancelled", 1)] * 3 + [("failure", 1000)]
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[
_run_row(
9000 + index,
@@ -318,14 +320,14 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
def test_workflow_health_pull_request_scope_excludes_default_branch_and_unattributed_runs(self) -> None:
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(91, "alice", "open", 0, _ago(1), head_sha="sha91")],
)
# The scenario matrix: PR-attributed × head branch. Only the attributed feature-branch
# run belongs in the pull_request scope.
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[
_run_row(run_id, "CI", sha, "completed", "success", _ago(1), _ago(1), pr_number=pr, head_branch=head)
for run_id, sha, pr, head in [
@@ -351,12 +353,12 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# With the jobs source synced, each workflow carries its windowed billable cost + minutes.
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(80, "alice", "open", 0, _ago(1), head_sha="sha80")],
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[_run_row(9500, "CI", "sha80", "completed", "success", _ago(1), _ago(1))],
)
self._create_table(
@@ -372,12 +374,12 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# The single-workflow breakdown splits a workflow's spend across runner tiers.
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(83, "alice", "open", 0, _ago(1), head_sha="sha83")],
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[_run_row(9600, "CI", "sha83", "completed", "success", _ago(1), _ago(1))],
)
self._create_table(
@@ -401,12 +403,12 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# runs are completed but neither successes nor failures, so they must not inflate the trend.
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(30, "alice", "open", 0, _ago(1), head_sha="sha30")],
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[
_run_row(6001, "CI", "sha-a", "completed", "success", _ago(1), _ago(1)),
_run_row(6002, "CI", "sha-b", "completed", "failure", _ago(1), _ago(1)),
@@ -426,12 +428,12 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# only decisive failure is a timeout still has a "last failure".
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(31, "alice", "open", 0, _ago(1), head_sha="sha31")],
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[
_run_row(6101, "CI", "sha-g", "completed", "success", _ago(2), _ago(2)),
_run_row(6102, "CI", "sha-h", "completed", "timed_out", _ago(1), _ago(1)),
@@ -448,12 +450,12 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# The run detail page fetches one run by id; re-runs share the id, so the latest attempt wins.
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(42, "alice", "open", 0, _ago(1), head_sha="sha42")],
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[
_run_row(
7777, "CI", "sha42", "completed", "failure", _ago(2), _ago(2), head_branch="master", pr_number=42
@@ -491,12 +493,12 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# The workflow detail page lists one workflow's runs, newest first, scoped to its repo.
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(50, "alice", "open", 0, _ago(1), head_sha="sha50")],
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[
_run_row(8001, "CI", "sha-a", "completed", "success", _ago(3), _ago(3)),
_run_row(8002, "CI", "sha-b", "completed", "failure", _ago(1), _ago(1)),
@@ -524,12 +526,12 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# workflow falls back to showing everything.
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(80, "alice", "open", 0, _ago(1), head_sha="sha80")],
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[
# A fast failure is signal (broken config fails in seconds) — never filtered as no-op.
_run_row(
@@ -602,12 +604,12 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# two dots. Runs off the default branch and outside the window are excluded.
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(95, "alice", "open", 0, _ago(1), head_sha="sha95")],
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[
# Commit A: two workflows, both passed -> one green dot with a wall-clock duration spanning
# the earliest start to the latest finish (not either workflow's own duration).
@@ -644,12 +646,12 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# branch and showed more runs (and more cost) than the tab did.
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(90, "alice", "open", 0, _ago(1), head_sha="sha90")],
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[
_run_row(8501, "CI", "sha-m1", "completed", "success", *_ago_with_duration(2, 60), head_branch="main"),
_run_row(8502, "CI", "sha-m2", "completed", "failure", *_ago_with_duration(1, 60), head_branch="main"),
@@ -699,12 +701,12 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# Jobs are an optional source: absent → graceful empty; present → costed per runner tier.
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(60, "alice", "open", 0, _ago(1), head_sha="sha60")],
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[_run_row(9100, "CI", "sha60", "completed", "failure", _ago(1), _ago(1))],
)
# No jobs table synced yet → empty, not an error (the graceful path).
@@ -732,12 +734,12 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# a contract validation error (regression guard for nullable run_started_at/updated_at).
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(63, "alice", "open", 0, _ago(1), head_sha="sha63")],
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[_run_row(9300, "CI", "sha63", "queued", None, "", "", pr_number=63)],
)
run = api.get_workflow_run(team=self.team, run_id=9300)
@@ -753,12 +755,12 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
# Default (no run_attempt) returns the latest attempt; an explicit attempt returns just that one.
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(62, "alice", "open", 0, _ago(1), head_sha="sha62")],
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[_run_row(9200, "CI", "sha62", "completed", "success", _ago(1), _ago(1), run_attempt=2)],
)
self._create_table(
@@ -781,12 +783,12 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
def test_workflow_health_branch_filter(self) -> None:
self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[_pr_row(20, "alice", "open", 0, _ago(1), head_sha="sha20")],
)
self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[
_run_row(5001, "CI", "sha-m1", "completed", "success", _ago(2), _ago(2), head_branch="main"),
_run_row(5002, "CI", "sha-m2", "completed", "failure", _ago(1), _ago(1), head_branch="main"),
diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.py
index 4b05d2685cc0..d4b6e246dea1 100644
--- a/products/engineering_analytics/backend/tests/test_presentation.py
+++ b/products/engineering_analytics/backend/tests/test_presentation.py
@@ -10,7 +10,7 @@ from rest_framework import status
from products.engineering_analytics.backend.facade import contracts
from products.engineering_analytics.backend.presentation.views import EngineeringAnalyticsViewSet
-from products.engineering_analytics.backend.tests.test_views import connect_github_source_without_data
+from products.engineering_analytics.backend.tests._github_fixtures import connect_github_source_without_data
class TestScopeEnrollment(SimpleTestCase):
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 43cb86523922..f6bc435537b6 100644
--- a/products/engineering_analytics/backend/tests/test_team_ci_health.py
+++ b/products/engineering_analytics/backend/tests/test_team_ci_health.py
@@ -7,7 +7,7 @@ from rest_framework import status
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.traces.spans import TRACE_SPANS_DISTRIBUTED_TABLE_SQL, TRACE_SPANS_TABLE_SQL
-from products.engineering_analytics.backend.tests.test_views import connect_github_source_without_data
+from products.engineering_analytics.backend.tests._github_fixtures import connect_github_source_without_data
T_REPLAY_PRS = "products/replay/backend/tests/test_snap/TestSnap::test_prs"
T_REPLAY_RERUN = "products/replay/backend/tests/test_playlist/TestPlaylist::test_rerun"
diff --git a/products/engineering_analytics/backend/tests/test_team_merge_trend.py b/products/engineering_analytics/backend/tests/test_team_merge_trend.py
index d3a9fa69d90f..ec7663409565 100644
--- a/products/engineering_analytics/backend/tests/test_team_merge_trend.py
+++ b/products/engineering_analytics/backend/tests/test_team_merge_trend.py
@@ -10,7 +10,7 @@ from products.engineering_analytics.backend.logic.queries._curated import Curate
from products.engineering_analytics.backend.logic.queries.team_merge_trend import query_team_merge_trend
from products.engineering_analytics.backend.logic.sources import GitHubTables
from products.engineering_analytics.backend.logic.views.source_schema import PULL_REQUESTS_COLUMNS, TEAM_MEMBERS_COLUMNS
-from products.engineering_analytics.backend.tests.test_views import (
+from products.engineering_analytics.backend.tests._github_fixtures import (
_pr_row,
connect_github_source_without_data,
create_github_warehouse_table,
diff --git a/products/engineering_analytics/backend/tests/test_views.py b/products/engineering_analytics/backend/tests/test_views.py
index e73414ba9e7d..4bafafad67d9 100644
--- a/products/engineering_analytics/backend/tests/test_views.py
+++ b/products/engineering_analytics/backend/tests/test_views.py
@@ -1,171 +1,27 @@
-import tempfile
-from pathlib import Path
from typing import Any
from posthog.test.base import BaseTest, ClickhouseTestMixin
-import pandas as pd
-
from posthog.hogql.query import execute_hogql_query
from posthog.constants import AvailableFeature
-from posthog.models.team import Team
from posthog.rbac.user_access_control import UserAccessControl
-from products.engineering_analytics.backend.logic.sources import (
- PULL_REQUESTS_SCHEMA,
- WORKFLOW_RUNS_SCHEMA,
- GitHubTables,
- list_github_sources,
-)
+from products.engineering_analytics.backend.logic.sources import list_github_sources
from products.engineering_analytics.backend.logic.views import pull_requests, workflow_runs
from products.engineering_analytics.backend.logic.views.source_schema import (
- PULL_REQUESTS_COLUMNS as _PULL_REQUESTS_COLUMNS,
- WORKFLOW_RUNS_COLUMNS as _WORKFLOW_RUNS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
+)
+from products.engineering_analytics.backend.tests._github_fixtures import (
+ _pr_row,
+ _run_row,
+ create_github_source,
+ create_github_warehouse_table,
)
-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
from ee.models.rbac.access_control import AccessControl
-TEST_BUCKET = "test_storage_bucket-posthog.products.engineering_analytics.views"
-
-# Non-default prefix on purpose: every fixture below lands tables named
-# `myprefixgithub_*`, so the resolver and builders are proven against a name the old
-# hardcoded `github_*` constants would never have matched.
-GITHUB_SOURCE_PREFIX = "myprefix"
-
-
-def create_github_source(
- team: Team, *, prefix: str = GITHUB_SOURCE_PREFIX, source_id: str = "gh-source", repository: str = ""
-) -> ExternalDataSource:
- return ExternalDataSource.objects.create(
- team=team,
- source_id=source_id,
- connection_id=source_id,
- status=ExternalDataSource.Status.COMPLETED,
- source_type=ExternalDataSourceType.GITHUB,
- prefix=prefix,
- job_inputs={"repository": repository} if repository else {},
- )
-
-
-def link_schema(
- team: Team,
- source: ExternalDataSource,
- *,
- name: str,
- table: DataWarehouseTable | None,
- should_sync: bool = True,
-) -> ExternalDataSchema:
- return ExternalDataSchema.objects.create(team=team, source=source, name=name, table=table, should_sync=should_sync)
-
-
-def create_warehouse_table_row(
- team: Team, *, name: str, source: ExternalDataSource | None = None
-) -> DataWarehouseTable:
- # ORM-only table (no object storage); for resolver/mapping tests that mock the query.
- return DataWarehouseTable.objects.create(
- team=team,
- name=name,
- format=DataWarehouseTable.TableFormat.CSVWithNames,
- url_pattern="",
- external_data_source=source,
- columns={},
- )
-
-
-def connect_github_source_without_data(
- team: Team, *, prefix: str = GITHUB_SOURCE_PREFIX, repository: str = ""
-) -> GitHubTables:
- """A GitHub source with pull_requests/workflow_runs schemas over empty ORM tables.
-
- The resolver finds these without touching object storage; pair with a mocked query
- when only resolution (not real warehouse data) matters.
- """
- source = create_github_source(team, prefix=prefix, repository=repository)
- pr_table = create_warehouse_table_row(team, name=f"{prefix}github_pull_requests", source=source)
- run_table = create_warehouse_table_row(team, name=f"{prefix}github_workflow_runs", source=source)
- link_schema(team, source, name=PULL_REQUESTS_SCHEMA, table=pr_table)
- link_schema(team, source, name=WORKFLOW_RUNS_SCHEMA, table=run_table)
- return GitHubTables(pull_requests=pr_table.name, workflow_runs=run_table.name, repository=repository)
-
-
-def _user(login: str) -> str:
- return f'{{"login": "{login}", "avatar_url": "https://avatars/{login}"}}'
-
-
-def _base(full_name: str, ref: str = "") -> str:
- return f'{{"ref": "{ref}", "repo": {{"full_name": "{full_name}"}}}}'
-
-
-def _labels(*names: str) -> str:
- return "[" + ", ".join(f'{{"name": "{name}"}}' for name in names) + "]"
-
-
-def _pr_row(
- number: int,
- login: str,
- state: str,
- draft: int,
- created_at: str,
- *,
- merged_at: str | None = None,
- head_sha: str = "",
- head_ref: str = "",
- base_ref: str = "",
- full_name: str = "PostHog/posthog",
- labels: tuple[str, ...] = (),
-) -> dict[str, Any]:
- return {
- "id": 1000 + number,
- "number": number,
- "title": f"PR {number}",
- "state": state,
- "draft": draft,
- "created_at": created_at,
- "updated_at": merged_at or created_at,
- "merged_at": merged_at,
- "closed_at": merged_at,
- "user": _user(login),
- "head": f'{{"sha": "{head_sha}", "ref": "{head_ref}"}}',
- "base": _base(full_name, base_ref),
- "labels": _labels(*labels),
- }
-
-
-def _run_row(
- run_id: int,
- name: str,
- head_sha: str,
- status: str,
- conclusion: str | None,
- run_started_at: str,
- updated_at: str,
- *,
- full_name: str = "PostHog/posthog",
- run_attempt: int = 1,
- pr_number: int | None = None,
- head_branch: str = "main",
-) -> dict[str, Any]:
- return {
- "id": run_id,
- "name": name,
- "head_sha": head_sha,
- "head_branch": head_branch,
- "status": status,
- "conclusion": conclusion,
- "created_at": run_started_at,
- "run_started_at": run_started_at,
- "updated_at": updated_at,
- "run_attempt": run_attempt,
- # Mirror the real Nullable(String) column: an unassociated run lands NULL, not "[]",
- # so the builder's ifNull(pull_requests, '[]') guard is exercised on the real path.
- "pull_requests": f'[{{"number": {pr_number}}}]' if pr_number is not None else None,
- "repository": f'{{"full_name": "{full_name}"}}',
- }
-
class TestListGithubSourcesAccessControl(BaseTest):
def setUp(self) -> None:
@@ -203,30 +59,6 @@ class TestListGithubSourcesAccessControl(BaseTest):
assert {source.id for source in visible} == {str(mine.id), str(theirs.id)}
-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.
- 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:
- table, _source, _credential, _df, cleanup = create_data_warehouse_table_from_csv(
- csv_path=Path(tmp.name),
- table_name=base_name,
- table_columns=columns,
- test_bucket=TEST_BUCKET,
- 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
-
-
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
@@ -241,7 +73,7 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
def test_pull_requests_view_maps_columns(self) -> None:
table_name = self._create_table(
"github_pull_requests",
- _PULL_REQUESTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
[
_pr_row(
10,
@@ -287,7 +119,7 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
def test_workflow_runs_view_maps_columns(self) -> None:
table_name = self._create_table(
"github_workflow_runs",
- _WORKFLOW_RUNS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
[
_run_row(2001, "CI", "sha1", "completed", "success", "2026-01-20 10:00:00", "2026-01-20 10:30:00"),
_run_row(2002, "CI", "sha2", "completed", "failure", "2026-01-22 10:00:00", "2026-01-22 10:45:00"),
@@ -361,7 +193,7 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
"pull_requests": None,
"repository": None,
}
- table_name = self._create_table("github_workflow_runs", _WORKFLOW_RUNS_COLUMNS, [sparse_run])
+ table_name = self._create_table("github_workflow_runs", WORKFLOW_RUNS_COLUMNS, [sparse_run])
rows = self._select(
"SELECT status, conclusion, duration_seconds, repo_owner, repo_name, pr_number, run_attempt "
f"FROM ({workflow_runs.build_query(table_name)}) AS r"