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.

fix(signals): request reviews from suggested reviewers (#108789)

Dylan Martinb13604131396
diff --git a/docs/internal/signals-pr-lifecycle.md b/docs/internal/signals-pr-lifecycle.md
index 1168aa42e347..5c4303911902 100644
--- a/docs/internal/signals-pr-lifecycle.md
+++ b/docs/internal/signals-pr-lifecycle.md
@@ -65,6 +65,8 @@ The same access rule applies when a reviewer is added later.
If no suggested reviewer has access, the ready report still goes to the configured team channel without reviewer mentions.
The notification activity retries transient ClickHouse reads before it claims the report for delivery.
+When an implementation pull request reaches the report, the worker requests reviews from suggested reviewers with connected GitHub accounts. It sends up to 15 reviewers per request. It skips the pull request author, existing assignees, the DRI it assigns, people with pending requests, and people who submitted a review. If GitHub rejects one reviewer, the worker continues with the other reviewers. Under the DRI rule, one assignee remains responsible for the pull request.
+
## Report links
Only scouts and the signals pipeline create and manage typed, directed report links.
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index 28ecd74852e8..4acb9a39afcc 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -9,6 +9,7 @@ import re
import json
import time
import uuid
+from collections import deque
from collections.abc import Callable, Collection, Iterable, Mapping
from dataclasses import dataclass
from datetime import datetime
@@ -80,6 +81,8 @@ GITHUB_ACCOUNT_NAME_HEAL_CLAIM_TTL_SECONDS = 60
# GitHub's add-assignees endpoint caps a single call at 10 logins and silently drops the rest.
MAX_PR_ASSIGNEES = 10
+# GitHub's request-reviewers endpoint caps a single call at 15 users.
+MAX_PR_REVIEWERS = 15
# GitHub label names cap at 50 characters, and a self-driving pull request only ever carries the one
# label its team configured, so a longer list is a caller mistake rather than a use we support.
@@ -1220,6 +1223,11 @@ class GitHubIntegrationBase:
for entry in (pr.get("assignees") or [])
if isinstance(entry, dict) and entry.get("login")
],
+ "requested_reviewers": [
+ entry["login"]
+ for entry in (pr.get("requested_reviewers") or [])
+ if isinstance(entry, dict) and entry.get("login")
+ ],
"created_at": pr.get("created_at"),
"updated_at": pr.get("updated_at"),
"merged_at": pr.get("merged_at"),
@@ -1378,6 +1386,99 @@ class GitHubIntegrationBase:
]
return {"success": True, "assignees": assigned}
+ def request_pull_request_reviews(self, repository: str, pr_number: int, reviewers: Iterable[str]) -> dict[str, Any]:
+ """Request reviews from GitHub users on a pull request."""
+ wanted = list(dict.fromkeys(login for login in reviewers if login))
+ if not wanted:
+ return {"success": True, "requested_reviewers": []}
+
+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
+ requested_reviewers: list[str] = []
+ batches = deque(
+ wanted[offset : offset + MAX_PR_REVIEWERS] for offset in range(0, len(wanted), MAX_PR_REVIEWERS)
+ )
+ rejected = 0
+ while batches:
+ batch = batches.popleft()
+ response = self._installation_authenticated_post(
+ f"https://api.github.com/repos/{repo_path}/pulls/{pr_number}/requested_reviewers",
+ endpoint="/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers",
+ json_body={"reviewers": batch},
+ )
+ if response is None:
+ return {"success": False, "error": "Network error requesting pull request reviews"}
+ try:
+ details = response.json() if response.status_code == 422 else {}
+ except Exception:
+ details = {}
+ errors = details.get("errors") if isinstance(details, dict) else None
+ reviewer_validation_failed = any(
+ isinstance(error, dict) and error.get("field") == "reviewers"
+ for error in (errors if isinstance(errors, list) else [])
+ )
+ if response.status_code == 422 and reviewer_validation_failed:
+ if len(batch) == 1:
+ rejected += 1
+ else:
+ midpoint = len(batch) // 2
+ batches.appendleft(batch[midpoint:])
+ batches.appendleft(batch[:midpoint])
+ continue
+ if response.status_code != 201:
+ return {
+ "success": False,
+ "error": f"Failed to request pull request reviews: {response.text}",
+ "status_code": response.status_code,
+ }
+ try:
+ pull_request = response.json()
+ except Exception:
+ pull_request = {}
+ requested_reviewers.extend(
+ entry["login"]
+ for entry in (pull_request.get("requested_reviewers") or [])
+ if isinstance(entry, dict) and entry.get("login")
+ )
+ if rejected:
+ logger.warning(
+ "GitHubIntegration: review requests rejected",
+ repository=repo_path,
+ pr_number=pr_number,
+ rejected=rejected,
+ )
+ return {"success": True, "requested_reviewers": list(dict.fromkeys(requested_reviewers))}
+
+ def list_submitted_pull_request_reviewers(self, repository: str, pr_number: int) -> dict[str, Any]:
+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
+ responses, complete = self._installation_authenticated_get_pages(
+ f"https://api.github.com/repos/{repo_path}/pulls/{pr_number}/reviews",
+ endpoint="/repos/{owner}/{repo}/pulls/{pull_number}/reviews",
+ params={"per_page": 100},
+ )
+ if not complete:
+ return {"success": False, "error": "Failed to list pull request reviews"}
+
+ reviewed_by: list[str] = []
+ for response in responses:
+ try:
+ reviews = response.json()
+ except Exception:
+ return {"success": False, "error": "Failed to parse pull request reviews JSON"}
+ if not isinstance(reviews, list):
+ return {"success": False, "error": "Pull request reviews JSON is not a list"}
+ for review in reviews:
+ if not isinstance(review, dict) or review.get("state") not in {
+ "APPROVED",
+ "CHANGES_REQUESTED",
+ "COMMENTED",
+ "DISMISSED",
+ }:
+ continue
+ user = review.get("user")
+ if isinstance(user, dict) and isinstance(user.get("login"), str):
+ reviewed_by.append(user["login"])
+ return {"success": True, "reviewed_by": reviewed_by}
+
def add_pull_request_labels(self, repository: str, pr_number: int, labels: Iterable[str]) -> dict[str, Any]:
"""Add labels to a pull request. ``repository`` is ``owner/repo`` or a bare repo.
diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.py
index 4474bbb486da..cbe41a0baad4 100644
--- a/posthog/models/test/integration/test_github.py
+++ b/posthog/models/test/integration/test_github.py
@@ -1087,6 +1087,58 @@ class TestGitHubIntegrationModel(BaseTest):
assert mock_post.call_args.args[0] == "https://api.github.com/repos/PostHog/posthog/issues/123/comments"
assert mock_post.call_args.kwargs["json_body"] == {"body": "hello"}
+ def test_get_pull_request_includes_requested_reviewers(self):
+ integration = self.create_integration(
+ config={"account": {"name": "PostHog"}}, sensitive_config={"access_token": "ACCESS_TOKEN"}
+ )
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=200)
+ mock_response.json.return_value = {
+ "number": 123,
+ "assignees": [{"login": "alice"}],
+ "requested_reviewers": [{"login": "bob"}],
+ }
+
+ with patch.object(github, "_installation_authenticated_get", return_value=mock_response):
+ result = github.get_pull_request("PostHog/posthog", 123)
+
+ assert result["assignees"] == ["alice"]
+ assert result["requested_reviewers"] == ["bob"]
+
+ def test_list_submitted_pull_request_reviewers_reads_every_page(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ first_page = MagicMock(status_code=200)
+ first_page.links = {
+ "next": {"url": "https://api.github.com/repos/PostHog/posthog/pulls/123/reviews?page=2&per_page=100"}
+ }
+ first_page.json.return_value = [
+ {"state": "PENDING", "user": {"login": "pending"}},
+ {"state": "APPROVED", "user": {"login": "approved"}},
+ ]
+ second_page = MagicMock(status_code=200)
+ second_page.links = {}
+ second_page.json.return_value = [{"state": "COMMENTED", "user": {"login": "commented"}}]
+
+ with patch.object(github, "_installation_authenticated_get", side_effect=[first_page, second_page]) as mock_get:
+ result = github.list_submitted_pull_request_reviewers("PostHog/posthog", 123)
+
+ assert result == {"success": True, "reviewed_by": ["approved", "commented"]}
+ assert mock_get.call_count == 2
+ assert mock_get.call_args_list[0].kwargs["params"] == {"per_page": 100}
+
+ def test_list_submitted_pull_request_reviewers_requires_every_page(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ first_page = MagicMock(status_code=200)
+ first_page.links = {"next": {"url": "https://api.github.com/repos/PostHog/posthog/pulls/123/reviews?page=2"}}
+ first_page.json.return_value = [{"state": "APPROVED", "user": {"login": "approved"}}]
+
+ with patch.object(github, "_installation_authenticated_get", side_effect=[first_page, None]):
+ result = github.list_submitted_pull_request_reviewers("PostHog/posthog", 123)
+
+ assert result["success"] is False
+
def test_comment_on_pull_request_from_url_parses_and_posts(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
github = GitHubIntegration(integration)
@@ -1134,6 +1186,68 @@ class TestGitHubIntegrationModel(BaseTest):
sent = mock_post.call_args.kwargs["json_body"]["assignees"]
assert sent == ["alice", *[f"user{i}" for i in range(9)]]
+ def test_request_pull_request_reviews_posts_deduplicated_bounded_batches(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=201)
+ mock_response.json.return_value = {"requested_reviewers": [{"login": "alice"}]}
+ requested = ["alice", "alice", *[f"user{i}" for i in range(20)]]
+
+ with patch.object(github, "_installation_authenticated_post", return_value=mock_response) as mock_post:
+ result = github.request_pull_request_reviews("PostHog/posthog", 123, requested)
+
+ assert result == {"success": True, "requested_reviewers": ["alice"]}
+ url = "https://api.github.com/repos/PostHog/posthog/pulls/123/requested_reviewers"
+ assert mock_post.call_args_list == [
+ call(
+ url,
+ endpoint="/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers",
+ json_body={"reviewers": ["alice", *[f"user{i}" for i in range(14)]]},
+ ),
+ call(
+ url,
+ endpoint="/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers",
+ json_body={"reviewers": [f"user{i}" for i in range(14, 20)]},
+ ),
+ ]
+
+ @parameterized.expand([("first_batch", 3), ("later_batch", 18)])
+ def test_request_pull_request_reviews_continues_after_rejected_reviewer(self, _name: str, invalid_index: int):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ requested = [f"user{i}" for i in range(31)]
+ rejected = requested[invalid_index]
+
+ def post_review_request(_url: str, *, endpoint: str, json_body: dict) -> MagicMock:
+ reviewers = json_body["reviewers"]
+ response = MagicMock(status_code=422 if rejected in reviewers else 201)
+ response.json.return_value = (
+ {"errors": [{"field": "reviewers", "code": "invalid"}]}
+ if rejected in reviewers
+ else {"requested_reviewers": [{"login": login} for login in reviewers]}
+ )
+ return response
+
+ with patch.object(github, "_installation_authenticated_post", side_effect=post_review_request) as mock_post:
+ result = github.request_pull_request_reviews("PostHog/posthog", 123, requested)
+
+ assert result == {"success": True, "requested_reviewers": [login for login in requested if login != rejected]}
+ assert all(len(request.kwargs["json_body"]["reviewers"]) <= 15 for request in mock_post.call_args_list)
+
+ @parameterized.expand([("forbidden", 403), ("unrelated_validation", 422)])
+ def test_request_pull_request_reviews_stops_on_non_reviewer_error(self, _name: str, status_code: int):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ response = MagicMock(status_code=status_code, text="Request failed")
+ response.json.return_value = {"errors": [{"field": "pull_request", "code": "invalid"}]}
+
+ with patch.object(github, "_installation_authenticated_post", return_value=response) as mock_post:
+ result = github.request_pull_request_reviews("PostHog/posthog", 123, ["alice", "bob"])
+
+ assert result["success"] is False
+ assert result["status_code"] == status_code
+ mock_post.assert_called_once()
+
def test_add_pull_request_assignees_reports_a_github_error(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
github = GitHubIntegration(integration)
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index 956f79e8f03c..0a05806bf38a 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -1363,7 +1363,7 @@ Every self-driving pull request opens with no assignee, so it never reaches a Gi
This governs what the rule adds. Nobody is ever unassigned, so a person can still assign three people by hand.
-"Assignee" here means GitHub's assignee, the person responsible. GitHub's other field, the requested reviewer, is never written by this code — a separate app requests the owning team for review, which is why both appear on these pull requests.
+"Assignee" here means GitHub's assignee, the person responsible. Each suggested reviewer with a connected GitHub account also receives an individual review request, in bounded batches of 15. The worker does not request a review from the pull request author, an assignee, or an existing requested reviewer. A separate app can still request the owning team for review.
Under the `signals-pr-dri-assignee` flag, the candidates are, most responsible first:
diff --git a/products/signals/backend/reviewer_pr_assignment.py b/products/signals/backend/reviewer_pr_assignment.py
index 926a02e8bee7..5bd44dda0975 100644
--- a/products/signals/backend/reviewer_pr_assignment.py
+++ b/products/signals/backend/reviewer_pr_assignment.py
@@ -1,4 +1,4 @@
-"""Put a person on a report's implementation PR as its GitHub assignee.
+"""Assign ownership and request reviews on a report's implementation PR.
Somebody whose workflow is GitHub's "Assigned to me" never sees an inbox PR otherwise, because
every self-driving pull request opens with no assignee.
@@ -12,8 +12,8 @@ nobody picks up, and a wrong owner costs one reassignment.
Without the flag the older rule stands: every suggested reviewer who opted in through
`SignalUserAutonomyConfig.github_assign_on_pull_request` is added, and there is no DRI.
-Reviewers, in GitHub's sense of a review request, are never written here. This module only ever
-writes assignees.
+Suggested reviewers with a connected GitHub account receive review requests. The pull request
+author, assignees, and existing requested reviewers are left alone.
Best effort throughout: a GitHub failure must never break the claim, sync, or reviewer edit that
triggered it.
@@ -316,6 +316,52 @@ def _add_assignees(
return assigned
+def _request_reviews(
+ github: GitHubIntegration,
+ *,
+ team_id: int,
+ report_id: str,
+ parsed: PullRequestRef,
+ pr: dict[str, Any],
+ reviewers: list[str],
+) -> list[str]:
+ existing = {
+ str(login).lower()
+ for login in [pr.get("author"), *(pr.get("assignees") or []), *(pr.get("requested_reviewers") or [])]
+ if login
+ }
+ wanted = [login for login in reviewers if login.lower() not in existing]
+ if not wanted:
+ return []
+
+ log = logger.bind(team_id=team_id, report_id=report_id, repository=parsed.repository, pr_number=parsed.number)
+ try:
+ reviews = github.list_submitted_pull_request_reviewers(parsed.repository, parsed.number)
+ except Exception:
+ log.exception("signals.reviewer_pr_assignment.reviews_fetch_failed")
+ return []
+ if not reviews.get("success"):
+ log.warning("signals.reviewer_pr_assignment.reviews_fetch_failed", error=reviews.get("error"))
+ return []
+ existing.update(str(login).lower() for login in (reviews.get("reviewed_by") or []) if login)
+ wanted = [login for login in wanted if login.lower() not in existing]
+ if not wanted:
+ return []
+
+ try:
+ result = github.request_pull_request_reviews(parsed.repository, parsed.number, wanted)
+ except Exception:
+ log.exception("signals.reviewer_pr_assignment.review_request_failed")
+ return []
+ if not result.get("success"):
+ log.warning("signals.reviewer_pr_assignment.review_request_failed", error=result.get("error"))
+ return []
+
+ requested = list(result.get("requested_reviewers") or [])
+ log.info("signals.reviewer_pr_assignment.reviews_requested", requested=len(wanted), accepted=len(requested))
+ return requested
+
+
def _first_assignable_login(
github: GitHubIntegration, *, team_id: int, report_id: str, parsed: PullRequestRef, candidates: list[str]
) -> str | None:
@@ -402,7 +448,7 @@ def dri_candidate_logins(
def assign_reviewers_to_pull_request(*, team_id: int, report_id: str, pr_url: str) -> list[str]:
- """Assign the report's pull request: one DRI under the flag, else every opted-in reviewer.
+ """Request reviews and assign one DRI under the flag, else every opted-in reviewer.
Returns the assignees GitHub accepted. Never unassigns: the add-assignees endpoint is additive,
so a person somebody assigned by hand stays on the pull request. Returns an empty list when
@@ -412,8 +458,9 @@ def assign_reviewers_to_pull_request(*, team_id: int, report_id: str, pr_url: st
return []
logins = opted_in_assignee_logins(team_id=team_id, report_id=report_id)
+ reviewers = ranked_reviewer_logins(team_id=team_id, report_id=report_id)
dri_enabled = _pr_dri_enabled(team_id)
- if not logins and not dri_enabled:
+ if not reviewers and not logins and not dri_enabled:
return []
parsed = GitHubIntegration.parse_pull_request_url(pr_url)
@@ -429,8 +476,31 @@ def assign_reviewers_to_pull_request(*, team_id: int, report_id: str, pr_url: st
return []
if dri_enabled:
- return _assign_one_dri(github, team_id=team_id, report_id=report_id, parsed=parsed, pr=pr, opted_in=set(logins))
- return _add_assignees(github, team_id=team_id, report_id=report_id, parsed=parsed, logins=logins) or []
+ assigned = _assign_one_dri(
+ github,
+ team_id=team_id,
+ report_id=report_id,
+ parsed=parsed,
+ pr=pr,
+ opted_in=set(logins),
+ reviewers=reviewers,
+ )
+ else:
+ assigned = (
+ _add_assignees(github, team_id=team_id, report_id=report_id, parsed=parsed, logins=logins) or []
+ if logins
+ else []
+ )
+
+ _request_reviews(
+ github,
+ team_id=team_id,
+ report_id=report_id,
+ parsed=parsed,
+ pr={**pr, "assignees": [*(pr.get("assignees") or []), *assigned]},
+ reviewers=reviewers,
+ )
+ return assigned
def _assign_one_dri(
@@ -441,6 +511,7 @@ def _assign_one_dri(
parsed: PullRequestRef,
pr: dict[str, Any],
opted_in: set[str],
+ reviewers: list[str],
) -> list[str]:
"""Put exactly one directly responsible individual on a pull request that has none.
@@ -456,7 +527,7 @@ def _assign_one_dri(
claimant=human_claimant_login(team_id=team_id, report_id=report_id),
opted_in=opted_in,
team=_owning_team(github, team_id=team_id, report_id=report_id, parsed=parsed),
- reviewers=ranked_reviewer_logins(team_id=team_id, report_id=report_id),
+ reviewers=reviewers,
)
dri = _first_assignable_login(github, team_id=team_id, report_id=report_id, parsed=parsed, candidates=candidates)
if dri is None:
diff --git a/products/signals/backend/test/test_reviewer_pr_assignment.py b/products/signals/backend/test/test_reviewer_pr_assignment.py
index 7550c95febfb..90aaccb44692 100644
--- a/products/signals/backend/test/test_reviewer_pr_assignment.py
+++ b/products/signals/backend/test/test_reviewer_pr_assignment.py
@@ -79,8 +79,20 @@ def _make_report(team: Team, *reviewer_rows: list[str]) -> SignalReport:
def _open_pr_github() -> MagicMock:
github = MagicMock()
- github.get_pull_request.return_value = {"success": True, "state": "open", "draft": False, "merged": False}
+ github.get_pull_request.return_value = {
+ "success": True,
+ "state": "open",
+ "draft": False,
+ "merged": False,
+ "assignees": [],
+ "requested_reviewers": [],
+ }
github.add_pull_request_assignees.return_value = {"success": True, "assignees": ["opted-in"]}
+ github.request_pull_request_reviews.return_value = {
+ "success": True,
+ "requested_reviewers": ["opted-in"],
+ }
+ github.list_submitted_pull_request_reviewers.return_value = {"success": True, "reviewed_by": []}
return github
@@ -149,10 +161,9 @@ class TestAssignReviewersToPullRequest:
github.add_pull_request_assignees.assert_called_once_with("PostHog/posthog", 123, ["opted-in"])
@pytest.mark.django_db
- def test_no_opted_in_reviewers_skips_github_entirely(self, org_and_team):
- org, team = org_and_team
- _make_reviewer(org, "opted-out", opted_in=False)
- report = _make_report(team, ["opted-out"])
+ def test_no_reviewers_or_assignment_work_skips_github_entirely(self, org_and_team):
+ _, team = org_and_team
+ report = _make_report(team)
with patch(
"products.signals.backend.reviewer_pr_assignment.GitHubIntegration.first_for_team_repository"
@@ -160,6 +171,33 @@ class TestAssignReviewersToPullRequest:
assert assign_reviewers_to_pull_request(team_id=team.id, report_id=str(report.id), pr_url=PR_URL) == []
mock_lookup.assert_not_called()
+ @pytest.mark.django_db
+ def test_suggested_reviewers_receive_review_requests(self, org_and_team):
+ org, team = org_and_team
+ for login in ("author", "assigned", "requested", "completed", "new-reviewer"):
+ _make_reviewer(org, login, opted_in=False)
+ report = _make_report(team, ["author", "assigned", "requested", "completed", "new-reviewer"])
+ github = _open_pr_github()
+ github.get_pull_request.return_value.update(
+ {"author": "Author", "assignees": ["Assigned"], "requested_reviewers": ["Requested"]}
+ )
+ github.list_submitted_pull_request_reviewers.return_value = {"success": True, "reviewed_by": ["Completed"]}
+ github.request_pull_request_reviews.return_value = {
+ "success": True,
+ "requested_reviewers": ["requested", "new-reviewer"],
+ }
+
+ with patch(
+ "products.signals.backend.reviewer_pr_assignment.GitHubIntegration.first_for_team_repository",
+ return_value=github,
+ ):
+ assigned = assign_reviewers_to_pull_request(team_id=team.id, report_id=str(report.id), pr_url=PR_URL)
+
+ assert assigned == []
+ github.list_submitted_pull_request_reviewers.assert_called_once_with("PostHog/posthog", 123)
+ github.request_pull_request_reviews.assert_called_once_with("PostHog/posthog", 123, ["new-reviewer"])
+ github.add_pull_request_assignees.assert_not_called()
+
@pytest.mark.django_db
@pytest.mark.parametrize(
"pr",
@@ -182,22 +220,48 @@ class TestAssignReviewersToPullRequest:
):
assert assign_reviewers_to_pull_request(team_id=team.id, report_id=str(report.id), pr_url=PR_URL) == []
github.add_pull_request_assignees.assert_not_called()
+ github.request_pull_request_reviews.assert_not_called()
@pytest.mark.django_db
@pytest.mark.parametrize(
- ("failing_call", "outcome"),
+ ("failing_call", "outcome", "expected"),
[
- ("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"}),
+ ("get_pull_request", Exception("boom"), []),
+ ("get_pull_request", {"success": False, "error": "Failed to fetch pull request"}, []),
+ ("list_submitted_pull_request_reviewers", Exception("boom"), ["opted-in"]),
+ (
+ "list_submitted_pull_request_reviewers",
+ {"success": False, "error": "Failed to fetch reviews"},
+ ["opted-in"],
+ ),
+ ("request_pull_request_reviews", Exception("boom"), ["opted-in"]),
+ (
+ "request_pull_request_reviews",
+ {"success": False, "error": "Failed to request pull request reviews"},
+ ["opted-in"],
+ ),
+ ("add_pull_request_assignees", Exception("boom"), []),
+ ("add_pull_request_assignees", {"success": False, "error": "Failed to assign pull request"}, []),
+ ],
+ ids=[
+ "pr_read_raises",
+ "pr_read_reports_failure",
+ "reviews_read_raises",
+ "reviews_read_reports_failure",
+ "review_request_raises",
+ "review_request_reports_failure",
+ "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):
+ def test_a_github_failure_is_swallowed(self, org_and_team, failing_call: str, outcome: object, expected: list[str]):
org, team = org_and_team
_make_reviewer(org, "opted-in", opted_in=True)
- report = _make_report(team, ["opted-in"])
+ reviewer_logins = ["opted-in"]
+ if failing_call in {"list_submitted_pull_request_reviewers", "request_pull_request_reviews"}:
+ _make_reviewer(org, "opted-out", opted_in=False)
+ reviewer_logins.append("opted-out")
+ report = _make_report(team, reviewer_logins)
github = _open_pr_github()
if isinstance(outcome, Exception):
getattr(github, failing_call).side_effect = outcome
@@ -208,7 +272,15 @@ class TestAssignReviewersToPullRequest:
"products.signals.backend.reviewer_pr_assignment.GitHubIntegration.first_for_team_repository",
return_value=github,
):
- assert assign_reviewers_to_pull_request(team_id=team.id, report_id=str(report.id), pr_url=PR_URL) == []
+ assert (
+ assign_reviewers_to_pull_request(team_id=team.id, report_id=str(report.id), pr_url=PR_URL) == expected
+ )
+
+ if failing_call in {"list_submitted_pull_request_reviewers", "request_pull_request_reviews"}:
+ github.list_submitted_pull_request_reviewers.assert_called_once_with("PostHog/posthog", 123)
+ github.add_pull_request_assignees.assert_called_once_with("PostHog/posthog", 123, ["opted-in"])
+ if failing_call == "request_pull_request_reviews":
+ github.request_pull_request_reviews.assert_called_once_with("PostHog/posthog", 123, ["opted-out"])
@pytest.mark.django_db
def test_a_url_that_is_not_a_pull_request_is_not_assigned(self, org_and_team):
@@ -520,6 +592,15 @@ class TestDirectlyResponsibleIndividual:
assert calls == ([[expected_owner]] if expected_owner else [])
+ @pytest.mark.django_db
+ def test_the_dri_does_not_receive_a_review_request(self, org_and_team):
+ org, team = org_and_team
+ report, _ = self._setup(org, team, ["alice", "bob"])
+ github = self._github(existing_assignees=[], assignable=None)
+
+ assert self._assign(team, report, github) == [["alice"]]
+ github.request_pull_request_reviews.assert_called_once_with("PostHog/posthog", 123, ["bob"])
+
@pytest.mark.django_db
@pytest.mark.parametrize(
("opted_in", "existing_assignees", "assignable", "expected_calls"),