:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(signals): split reviewer PR assignment into helpers (#100664)
posthog[bot]4018ab9671e3
diff --git a/products/signals/backend/reviewer_pr_assignment.py b/products/signals/backend/reviewer_pr_assignment.pyindex c489e8aca381..0a587feacf6e 100644--- a/products/signals/backend/reviewer_pr_assignment.py+++ b/products/signals/backend/reviewer_pr_assignment.py@@ -14,6 +14,7 @@ from django.db import transactionimport structlog+from posthog.models.github_integration_base import PullRequestReffrom posthog.models.integration import GitHubIntegrationfrom products.signals.backend.models import (@@ -112,39 +113,29 @@ def opted_in_reviewer_logins(*, team_id: int, report_id: str) -> list[str]:return sorted(login for login, user in login_to_user.items() if user.id in opted_in_user_ids)-def assign_reviewers_to_pull_request(*, team_id: int, report_id: str, pr_url: str) -> list[str]:- """Add the report's opted-in reviewers to its pull request. Returns the logins GitHub accepted.-- Never unassigns: GitHub's add-assignees endpoint is additive, so a reviewer somebody assigned by- hand stays on the pull request. Returns an empty list when there is nothing to do or the call- failed, and raises nothing.- """- if not SignalReport.objects.filter(id=report_id, team_id=team_id).exists():- return []-- logins = opted_in_reviewer_logins(team_id=team_id, report_id=report_id)- if not logins:- return []-- parsed = GitHubIntegration.parse_pull_request_url(pr_url)- if parsed is None:- return []-+def _github_for_repository(*, team_id: int, report_id: str, repository: str) -> GitHubIntegration | None:+ """The team's GitHub integration for a repository, or None when there is none to call."""try:- github = GitHubIntegration.first_for_team_repository(team_id, parsed.repository)+ return GitHubIntegration.first_for_team_repository(team_id, repository)except Exception:logger.exception("signals.reviewer_pr_assignment.integration_lookup_failed",team_id=team_id,report_id=report_id,- repository=parsed.repository,+ repository=repository,)- return []- if github is None:- return []+ return None+++def _pull_request_is_assignable(+ github: GitHubIntegration, *, team_id: int, report_id: str, parsed: PullRequestRef+) -> bool:+ """Whether the pull request still accepts assignees.- # A pull request closed or merged since the assignment was queued must not be reopened in- # somebody's assigned list, so re-read the state here rather than trusting the queued snapshot.+ A pull request closed or merged since the assignment was queued must not be reopened in+ somebody's assigned list, so this reads the state from GitHub rather than trusting the queued+ snapshot. A read that fails counts as not assignable.+ """try:pr = github.get_pull_request(parsed.repository, parsed.number)except Exception:@@ -155,7 +146,7 @@ def assign_reviewers_to_pull_request(*, team_id: int, report_id: str, pr_url: strepository=parsed.repository,pr_number=parsed.number,)- return []+ return Falseif not pr.get("success"):logger.warning("signals.reviewer_pr_assignment.pr_fetch_failed",@@ -165,10 +156,14 @@ def assign_reviewers_to_pull_request(*, team_id: int, report_id: str, pr_url: stpr_number=parsed.number,error=pr.get("error"),)- return []- if pr.get("merged") or pr.get("state") == "closed":- return []+ return False+ return not pr.get("merged") and pr.get("state") != "closed"++def _add_assignees(+ github: GitHubIntegration, *, team_id: int, report_id: str, parsed: PullRequestRef, logins: list[str]+) -> list[str]:+ """Add the logins to the pull request. Returns the logins GitHub accepted, or none on failure."""try:result = github.add_pull_request_assignees(parsed.repository, parsed.number, logins)except Exception:@@ -204,3 +199,31 @@ def assign_reviewers_to_pull_request(*, team_id: int, report_id: str, pr_url: stassigned=len(assigned),)return assigned+++def assign_reviewers_to_pull_request(*, team_id: int, report_id: str, pr_url: str) -> list[str]:+ """Add the report's opted-in reviewers to its pull request. Returns the logins GitHub accepted.++ Never unassigns: GitHub's add-assignees endpoint is additive, so a reviewer somebody assigned by+ hand stays on the pull request. Returns an empty list when there is nothing to do or the call+ failed, and raises nothing.+ """+ if not SignalReport.objects.filter(id=report_id, team_id=team_id).exists():+ return []++ logins = opted_in_reviewer_logins(team_id=team_id, report_id=report_id)+ if not logins:+ return []++ parsed = GitHubIntegration.parse_pull_request_url(pr_url)+ if parsed is None:+ return []++ github = _github_for_repository(team_id=team_id, report_id=report_id, repository=parsed.repository)+ if github is None:+ return []++ if not _pull_request_is_assignable(github, team_id=team_id, report_id=report_id, parsed=parsed):+ return []++ return _add_assignees(github, team_id=team_id, report_id=report_id, parsed=parsed, logins=logins)diff --git a/products/signals/backend/test/test_reviewer_pr_assignment.py b/products/signals/backend/test/test_reviewer_pr_assignment.pyindex 162fececb8c7..f87b6ff09a53 100644--- a/products/signals/backend/test/test_reviewer_pr_assignment.py+++ b/products/signals/backend/test/test_reviewer_pr_assignment.py@@ -175,10 +175,11 @@ class TestAssignReviewersToPullRequest:("failing_call", "outcome"),[("get_pull_request", Exception("boom")),+ ("get_pull_request", {"success": False, "error": "Failed to fetch pull request"}),("add_pull_request_assignees", Exception("boom")),("add_pull_request_assignees", {"success": False, "error": "Failed to assign pull request"}),],- ids=["pr_read_raises", "assign_raises", "assign_reports_failure"],+ ids=["pr_read_raises", "pr_read_reports_failure", "assign_raises", "assign_reports_failure"],)def test_a_github_failure_is_swallowed(self, org_and_team, failing_call: str, outcome: object):org, team = org_and_team@@ -196,6 +197,38 @@ class TestAssignReviewersToPullRequest:):assert assign_reviewers_to_pull_request(team_id=team.id, report_id=str(report.id), pr_url=PR_URL) == []+ @pytest.mark.django_db+ def test_a_url_that_is_not_a_pull_request_is_not_assigned(self, org_and_team):+ org, team = org_and_team+ _make_reviewer(org, "opted-in", opted_in=True)+ report = _make_report(team, ["opted-in"])++ with patch(+ "products.signals.backend.reviewer_pr_assignment.GitHubIntegration.first_for_team_repository"+ ) as mock_lookup:+ assigned = assign_reviewers_to_pull_request(+ team_id=team.id, report_id=str(report.id), pr_url="https://example.com/not-a-pr"+ )++ assert assigned == []+ mock_lookup.assert_not_called()++ @pytest.mark.django_db+ @pytest.mark.parametrize(+ "lookup",+ [{"return_value": None}, {"side_effect": Exception("boom")}],+ ids=["no_integration", "lookup_raises"],+ )+ def test_an_unavailable_integration_is_not_assigned(self, org_and_team, lookup: dict):+ org, team = org_and_team+ _make_reviewer(org, "opted-in", opted_in=True)+ report = _make_report(team, ["opted-in"])++ with patch(+ "products.signals.backend.reviewer_pr_assignment.GitHubIntegration.first_for_team_repository", **lookup+ ):+ assert assign_reviewers_to_pull_request(team_id=team.id, report_id=str(report.id), pr_url=PR_URL) == []+@pytest.mark.django_dbdef test_a_report_from_another_team_is_not_assigned(self, org_and_team):org, team = org_and_team