Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Calculate PR urgency based on ready for review time (#2027)
sarayourfriend9408be27e532
diff --git a/catalog/dags/common/github.py b/catalog/dags/common/github.pyindex 75b2d941e..6adb103bd 100644--- a/catalog/dags/common/github.py+++ b/catalog/dags/common/github.py@@ -54,6 +54,12 @@ class GitHubAPI:f"repos/{owner}/{repo}/issues/{issue_number}/comments",)+ def get_issue_events(self, repo: str, issue_number: int, owner: str = "WordPress"):+ return self._make_request(+ "GET",+ f"repos/{owner}/{repo}/issues/{issue_number}/events",+ )+def delete_issue_comment(self, repo: str, comment_id: int, owner: str = "WordPress"):diff --git a/catalog/dags/maintenance/pr_review_reminders/pr_review_reminders.py b/catalog/dags/maintenance/pr_review_reminders/pr_review_reminders.pyindex 7d6679400..c0b222e6f 100644--- a/catalog/dags/maintenance/pr_review_reminders/pr_review_reminders.py+++ b/catalog/dags/maintenance/pr_review_reminders/pr_review_reminders.py@@ -28,6 +28,28 @@ class Urgency:MEDIUM = Urgency("medium", 4)LOW = Urgency("low", 5)+ @classmethod+ def for_pr(cls, pr: dict) -> Urgency | None:+ priority_labels = [+ label["name"]+ for label in pr["labels"]+ if "priority" in label["name"].lower()+ ]+ if not priority_labels:+ logger.error(f"Found unlabeled PR ({pr['html_url']}). Skipping!")+ return None++ priority_label = priority_labels[0]++ if "critical" in priority_label:+ return cls.CRITICAL+ elif "high" in priority_label:+ return cls.HIGH+ elif "medium" in priority_label:+ return cls.MEDIUM+ elif "low" in priority_label:+ return cls.LOW+@dataclassclass ReviewDelta:@@ -35,27 +57,9 @@ class ReviewDelta:days: int-def pr_urgency(pr: dict) -> Urgency.Urgency:- priority_labels = [- label["name"] for label in pr["labels"] if "priority" in label["name"].lower()- ]- if not priority_labels:- logger.error(f"Found unabled PR ({pr['html_url']}). Skipping!")- return None-- priority_label = priority_labels[0]-- if "critical" in priority_label:- return Urgency.CRITICAL- elif "high" in priority_label:- return Urgency.HIGH- elif "medium" in priority_label:- return Urgency.MEDIUM- elif "low" in priority_label:- return Urgency.LOW---def days_without_weekends(today: datetime, updated_at: datetime) -> int:+def days_without_weekends(+ today: datetime.datetime, updated_at: datetime.datetime+) -> int:"""Return the number of days between two dates, excluding weekends.@@ -76,16 +80,32 @@ def parse_gh_date(d) -> datetime.datetime:return datetime.datetime.fromisoformat(d.rstrip("Z"))-def get_urgency_if_urgent(pr: dict) -> ReviewDelta | None:- updated_at = parse_gh_date(pr["updated_at"])+def get_urgency_if_urgent(gh: GitHubAPI, pr: dict) -> ReviewDelta | None:+ events = gh.get_issue_events(base_repo_name(pr), pr["number"])+ ready_for_review_date = pr["created_at"]+ for event in reversed(events):+ # Find the latest "ready_for_review" event.+ # We don't need to check for or stop if we+ # find a draft event because drafted PRs are+ # already filtered out at this point. Any draft+ # events present in the events list would+ # be further back in time than the latest+ # (and therefore relevant) ready_for_review+ # event will appear before we reach any+ # draft events.+ if event["event"] == "ready_for_review":+ ready_for_review_date = event["created_at"]+ break++ urgency_base_date = parse_gh_date(ready_for_review_date)today = datetime.datetime.now()- urgency = pr_urgency(pr)- if urgency is None:+ pr_urgency = Urgency.for_pr(pr)+ if pr_urgency is None:return None- days = days_without_weekends(today, updated_at)+ days = days_without_weekends(today, urgency_base_date)- return ReviewDelta(urgency, days) if days >= urgency.days else None+ return ReviewDelta(pr_urgency, days) if days >= pr_urgency.days else NoneCOMMENT_MARKER = (@@ -103,16 +123,16 @@ gently reminded to review this PR:f"{COMMENT_MARKER}""""-Excluding weekend[^1] days, this PR was updated {days_since_update} day(s) ago. \-PRs labelled with {urgency_label} urgency are expected to be reviewed within \-{urgency_days} weekday(s)[^2].+Excluding weekend[^1] days, this PR was ready for review {days_ready_for_review} \+day(s) ago. PRs labelled with {urgency_label} urgency are expected to be reviewed \+within {urgency_days} weekday(s)[^2].@{pr_author}, if this PR is not ready for a review, please draft it to \prevent reviewers from getting further unnecessary pings.[^1]: Specifically, Saturday and Sunday.[^2]: For the purpose of these reminders we treat Monday - Friday as weekdays. \-Please note that the that generates these reminders runs at midnight \+Please note that the operation that generates these reminders runs at midnight \UTC on Monday - Friday. This means that depending on your timezone, \you may be pinged outside of the expected range."""@@ -125,7 +145,7 @@ def build_comment(review_delta: ReviewDelta, pr: dict):urgency_label=review_delta.urgency.label,urgency_days=review_delta.urgency.days,user_logins="\n".join(user_handles),- days_since_update=review_delta.days,+ days_ready_for_review=review_delta.days,pr_author=pr["user"]["login"],)@@ -175,7 +195,7 @@ def post_reminders(github_pat: str, dry_run: bool):urgent_prs = []for pr in open_prs:- review_delta = get_urgency_if_urgent(pr)+ review_delta = get_urgency_if_urgent(gh, pr)if review_delta:urgent_prs.append((pr, review_delta))diff --git a/catalog/tests/dags/maintenance/test_pr_review_reminders.py b/catalog/tests/dags/maintenance/test_pr_review_reminders.pyindex f7dede754..b83994cd7 100644--- a/catalog/tests/dags/maintenance/test_pr_review_reminders.py+++ b/catalog/tests/dags/maintenance/test_pr_review_reminders.py@@ -4,19 +4,23 @@ from datetime import datetime, timedeltaimport pytestfrom requests import HTTPError, Request, Response-from catalog.dags.maintenance.pr_review_reminders.pr_review_reminders import (- Urgency,- days_without_weekends,- post_reminders,-)from catalog.tests.factories.github import (+ EventsConfig,make_branch_protection,make_current_pr_comment,+ make_non_urgent_events,+ make_non_urgent_reviewable_events,make_outdated_pr_comment,make_pr_comment,make_pull,make_requested_reviewer,make_review,+ make_urgent_events,+)+from maintenance.pr_review_reminders.pr_review_reminders import (+ Urgency,+ days_without_weekends,+ post_reminders,)@@ -77,6 +81,7 @@ def github(monkeypatch):deleted_comments = []pull_reviews = defaultdict(list)branch_protection = defaultdict(dict)+ events = defaultdict(list)def get_prs(*args, **kwargs):return pulls@@ -98,6 +103,10 @@ def github(monkeypatch):pr_number = args[2]return pull_reviews[pr_number]+ def get_events(*args, **kwargs):+ pr_number = args[2]+ return events[pr_number]+def get_branch_protection(*args, **kwargs):repo = args[1]branch = args[2]@@ -118,6 +127,7 @@ def github(monkeypatch):patch_gh_fn("get_open_prs", get_prs)patch_gh_fn("get_issue_comments", get_comments)+ patch_gh_fn("get_issue_events", get_events)patch_gh_fn("post_issue_comment", post_comment)patch_gh_fn("delete_issue_comment", delete_comment)patch_gh_fn("get_pull_reviews", get_reviews)@@ -130,6 +140,7 @@ def github(monkeypatch):"deleted_comments": deleted_comments,"pull_reviews": pull_reviews,"branch_protection": branch_protection,+ "events": events,}@@ -154,38 +165,115 @@ def _setup_branch_protection_for_branch(parametrize_urgency = pytest.mark.parametrize("urgency",- (- Urgency.CRITICAL,- Urgency.HIGH,- Urgency.MEDIUM,- Urgency.LOW,- ),+ [+ pytest.param(urgency, id=f"{urgency.label}-urgency")+ for urgency in (+ Urgency.CRITICAL,+ Urgency.HIGH,+ Urgency.MEDIUM,+ Urgency.LOW,+ )+ ],+)+++# We don't need to test events list where the last+# event is "convert_to_draft" because drafted PRs+# are filtered out of the scenarios where a PR would+# be eligible for a ping based on urgency.+parametrize_possible_pingable_events = pytest.mark.parametrize(+ "events",+ [+ # PRs opened "ready for review" do not have a ready for review event.+ # This covers the most common case as most PRs will only have these+ # events. There are no events for actual PR reviews or comments as those+ # are in the "comments" and "reviews" feeds for the issue/PR+ pytest.param(+ ["labeled", "review_requested"],+ id="opened_ready_for_review",+ ),+ # PRs converted to a draft after being opened will have both convert and ready events+ pytest.param(+ [+ "labeled",+ "review_requested",+ "convert_to_draft",+ EventsConfig("ready_for_review", 1),+ ],+ id="opened_then_drafted_finally_ready",+ ),+ # A PR opened as a draft does not have a "convert_to_draft" event but does still have "ready_for_review"+ pytest.param(+ ["labeled", "review_requested", EventsConfig("ready_for_review", 2)],+ id="opened_as_draft_finally_ready",+ ),+ # PRs can have multiple ready for review events if converted to draft multiple times+ pytest.param(+ [+ "labeled",+ "review_requested",+ "convert_to_draft",+ EventsConfig("ready_for_review", 1),+ "convert_to_draft",+ "ready_for_review",+ ],+ id="opened_then_drafted_redrafted_finally_ready",+ ),+ # A PR opened as a draft can be set as ready for review and then redrafted.+ # A length of time greater than the lowest urgency window is set to pass between+ # the first ready_for_review event and the next event; this ensures that the+ # first ready_for_review event is definitely out of the urgency window. This+ # tests that the date of the most *recent* ready_for_review event is what is+ # used to determine if a PR should be pinged.+ pytest.param(+ [+ "labeled",+ "review_requested",+ EventsConfig("ready_for_review", 2),+ EventsConfig("convert_to_draft", Urgency.LOW.days * 2),+ EventsConfig("ready_for_review", 1),+ ],+ id="opened_as_draft_redrafted_finally_ready",+ ),+ ],)@parametrize_urgency-def test_pings_past_due(github, urgency):- past_due_pull = make_pull(urgency, past_due=True)+@parametrize_possible_pingable_events+def test_pings_past_due(github, urgency, events):+ past_due_pull = make_pull(urgency, old=True)past_due_pull["requested_reviewers"] = [make_requested_reviewer(f"reviewer-due-{i}") for i in range(2)]- not_due_pull = make_pull(urgency, past_due=False)+ not_due_pull = make_pull(urgency, old=False)not_due_pull["requested_reviewers"] = [make_requested_reviewer(f"reviewer-not-due-{i}") for i in range(2)]+ old_but_not_due_pull = make_pull(urgency, old=True)+ old_but_not_due_pull["requested_reviewers"] = [+ make_requested_reviewer(f"reviewer-old-but-not-due-{i}") for i in range(2)+ ]- for pr in [past_due_pull, not_due_pull]:+ for pr in [past_due_pull, not_due_pull, old_but_not_due_pull]:_setup_branch_protection(github, pr)- github["pulls"] += [past_due_pull, not_due_pull]+ github["pulls"] += [past_due_pull, not_due_pull, old_but_not_due_pull]github["pull_comments"][past_due_pull["number"]].append(make_pr_comment(is_reminder=False))+ github["events"][past_due_pull["number"]] = make_urgent_events(urgency, events)+ github["events"][not_due_pull["number"]] = make_non_urgent_events(events)+ github["events"][+ old_but_not_due_pull["number"]+ ] = make_non_urgent_reviewable_events(events)+post_reminders("not_set", dry_run=False)assert past_due_pull["number"] in github["posted_comments"]assert not_due_pull["number"] not in github["posted_comments"]+ assert old_but_not_due_pull["number"] not in github["posted_comments"]comments = github["posted_comments"][past_due_pull["number"]]for reviewer in past_due_pull["requested_reviewers"]:@@ -194,40 +282,57 @@ def test_pings_past_due(github, urgency):@parametrize_urgency-def test_does_not_reping_past_due_if_reminder_is_current(github, urgency):- past_due_pull = make_pull(urgency, past_due=True)+@parametrize_possible_pingable_events+def test_does_not_reping_past_due_if_reminder_is_current(github, urgency, events):+ past_due_pull = make_pull(urgency, old=True)past_due_pull["requested_reviewers"] = [make_requested_reviewer(f"reviewer-due-{i}") for i in range(2)]- not_due_pull = make_pull(urgency, past_due=False)+ not_due_pull = make_pull(urgency, old=False)not_due_pull["requested_reviewers"] = [make_requested_reviewer(f"reviewer-not-due-{i}") for i in range(2)]+ old_but_not_due_pull = make_pull(urgency, old=True)+ old_but_not_due_pull["requested_reviewers"] = [+ make_requested_reviewer(f"reviewer-old-but-not-due-{i}") for i in range(2)+ ]- for pr in [past_due_pull, not_due_pull]:+ for pr in [past_due_pull, not_due_pull, old_but_not_due_pull]:_setup_branch_protection(github, pr)- github["pulls"] += [past_due_pull, not_due_pull]+ github["pulls"] += [past_due_pull, not_due_pull, old_but_not_due_pull]github["pull_comments"][past_due_pull["number"]].append(make_current_pr_comment(past_due_pull))+ github["events"][past_due_pull["number"]] = make_urgent_events(urgency, events)+ github["events"][not_due_pull["number"]] = make_non_urgent_events(events)+ github["events"][+ old_but_not_due_pull["number"]+ ] = make_non_urgent_reviewable_events(events)+post_reminders("not_set", dry_run=False)assert past_due_pull["number"] not in github["posted_comments"]assert not_due_pull["number"] not in github["posted_comments"]+ assert old_but_not_due_pull["number"] not in github["posted_comments"]@parametrize_urgency-def test_does_reping_past_due_if_reminder_is_outdated(github, urgency):- past_due_pull = make_pull(urgency, past_due=True)+@parametrize_possible_pingable_events+def test_does_reping_past_due_if_reminder_is_outdated(github, urgency, events):+ past_due_pull = make_pull(urgency, old=True)past_due_pull["requested_reviewers"] = [make_requested_reviewer(f"reviewer-due-{i}") for i in range(2)]- not_due_pull = make_pull(urgency, past_due=False)+ not_due_pull = make_pull(urgency, old=False)not_due_pull["requested_reviewers"] = [make_requested_reviewer(f"reviewer-not-due-{i}") for i in range(2)]+ old_but_not_due_pull = make_pull(urgency, old=True)+ old_but_not_due_pull["requested_reviewers"] = [+ make_requested_reviewer(f"reviewer-old-but-not-due-{i}") for i in range(2)+ ]for pr in [past_due_pull, not_due_pull]:_setup_branch_protection(github, pr)@@ -236,10 +341,18 @@ def test_does_reping_past_due_if_reminder_is_outdated(github, urgency):reminder_comment = make_outdated_pr_comment(past_due_pull)github["pull_comments"][past_due_pull["number"]].append(reminder_comment)+ github["events"][past_due_pull["number"]] = make_urgent_events(urgency, events)+ github["events"][not_due_pull["number"]] = make_non_urgent_events(events)+ github["events"][+ old_but_not_due_pull["number"]+ ] = make_non_urgent_reviewable_events(events)+post_reminders("not_set", dry_run=False)assert past_due_pull["number"] in github["posted_comments"]assert not_due_pull["number"] not in github["posted_comments"]+ assert old_but_not_due_pull["number"] not in github["posted_comments"]+assert reminder_comment["id"] in github["deleted_comments"]@@ -261,15 +374,16 @@ UNAPPROVED_REVIEW_STATES = ("CHANGES_REQUESTED", "COMMENTED")("APPROVED",) + UNAPPROVED_REVIEW_STATES,)@pytest.mark.parametrize("base_branch", ("main", "not_main"))+@parametrize_possible_pingable_eventsdef test_does_ping_if_pr_has_less_than_min_required_approvals(- github, urgency, first_review_state, second_review_state, base_branch+ github, urgency, first_review_state, second_review_state, base_branch, events):reviews = [make_review(state)for state in (first_review_state, second_review_state)if state is not None]- past_due_pull = make_pull(urgency, past_due=True, base_branch=base_branch)+ past_due_pull = make_pull(urgency, old=True, base_branch=base_branch)past_due_pull["requested_reviewers"] = [make_requested_reviewer(f"reviewer-due-{i}") for i in range(2)]@@ -283,7 +397,8 @@ def test_does_ping_if_pr_has_less_than_min_required_approvals()github["pulls"] += [past_due_pull]- github["pull_reviews"][past_due_pull["id"]] = reviews+ github["pull_reviews"][past_due_pull["number"]] = reviews+ github["events"][past_due_pull["number"]] = make_urgent_events(urgency, events)post_reminders("not_set", dry_run=False)@@ -298,8 +413,11 @@ def test_does_ping_if_pr_has_less_than_min_required_approvals("not_main", # should fallback to use `main`),)-def test_does_not_ping_if_pr_has_min_required_approvals(github, urgency, base_branch):- past_due_pull = make_pull(urgency, past_due=True, base_branch=base_branch)+@parametrize_possible_pingable_events+def test_does_not_ping_if_pr_has_min_required_approvals(+ github, urgency, base_branch, events+):+ past_due_pull = make_pull(urgency, old=True, base_branch=base_branch)past_due_pull["requested_reviewers"] = [make_requested_reviewer(f"reviewer-due-{i}") for i in range(2)]@@ -315,9 +433,10 @@ def test_does_not_ping_if_pr_has_min_required_approvals(github, urgency, base_br)github["pulls"] += [past_due_pull]- github["pull_reviews"][past_due_pull["id"]] = [+ github["pull_reviews"][past_due_pull["number"]] = [make_review("APPROVED"),] * min_required_approvals+ github["events"][past_due_pull["number"]] = make_urgent_events(urgency, events)post_reminders("not_set", dry_run=False)@@ -325,16 +444,25 @@ def test_does_not_ping_if_pr_has_min_required_approvals(github, urgency, base_br@parametrize_urgency-def test_does_not_ping_if_no_reviewers(github, urgency):- past_due_pull = make_pull(urgency, past_due=True)+@parametrize_possible_pingable_events+def test_does_not_ping_if_no_reviewers(github, urgency, events):+ past_due_pull = make_pull(urgency, old=True)past_due_pull["requested_reviewers"] = []- not_due_pull = make_pull(urgency, past_due=False)+ not_due_pull = make_pull(urgency, old=False)not_due_pull["requested_reviewers"] = []- github["pulls"] += [past_due_pull, not_due_pull]+ old_but_not_due_pull = make_pull(urgency, old=True)++ github["pulls"] += [past_due_pull, not_due_pull, old_but_not_due_pull]github["pull_comments"][past_due_pull["number"]].append(make_pr_comment(is_reminder=False))+ github["events"][past_due_pull["number"]] = make_urgent_events(urgency, events)+ github["events"][not_due_pull["number"]] = make_non_urgent_events(events)+ github["events"][+ old_but_not_due_pull["number"]+ ] = make_non_urgent_reviewable_events(events)+for pr in [past_due_pull, not_due_pull]:_setup_branch_protection(github, pr)@@ -342,3 +470,81 @@ def test_does_not_ping_if_no_reviewers(github, urgency):assert past_due_pull["number"] not in github["posted_comments"]assert not_due_pull["number"] not in github["posted_comments"]+ assert old_but_not_due_pull["number"] not in github["posted_comments"]+++@parametrize_urgency+# We cannot use the ``possible_pingable_events`` fixture+# because this test is only relevant for PRs that have+# ready for review events (i.e., were at one point drafts).+# Possible pingable events includes the one case where+# a PR would not have a ready for review event but still+# be eligible: PRs that were never drafts. As there's no+# easy way to combine parametrized fixtures or to abstract+# this without a great deal of displacement, it's easier+# to just copy the relevant cases.+ "events",+ (+ # PRs converted to a draft after being opened will have both convert and ready events+ (+ "labeled",+ "review_requested",+ "convert_to_draft",+ EventsConfig("ready_for_review", 1),+ ),+ # A PR opened as a draft does not have a "convert_to_draft" event but does still have "ready_for_review"+ ("labeled", "review_requested", EventsConfig("ready_for_review", 2)),+ # PRs can have multiple ready for review events if converted to draft multiple times+ (+ "labeled",+ "review_requested",+ "convert_to_draft",+ EventsConfig("ready_for_review", 1),+ "convert_to_draft",+ "ready_for_review",+ ),+ # A PR opened as a draft can be set as ready for review and then redrafted+ (+ "labeled",+ "review_requested",+ EventsConfig("ready_for_review", 2),+ EventsConfig("convert_to_draft", 1),+ EventsConfig("ready_for_review", 1),+ ),+ ),+)+def test_ignores_created_at_and_pings_if_urgent_ready_for_review_event_exists(+ github, urgency, events+):+ """+ Artificial case to confirm ready for review events are respected.++ This case never happens in reality because it's impossible to have an event+ that occurs before the creation of the PR. However, while the other tests+ show that pings happen for past due PRs and do not happen for+ PRs not past due, they don't definitely show that the ready_for_review+ event date is what marked the PR urgent.++ This test creates a PR with a created_at timestamp that by itself+ would _not_ cause the PR to be urgent. However, the PR's events+ list has a ready_for_review event+ """++ # old=False ensures the PR's created_at date will not+ # be the cause of it being eligible for a ping+ pull = make_pull(urgency, old=False)+ pull["requested_reviewers"] = [+ make_requested_reviewer(f"reviewer-due-{i}") for i in range(2)+ ]++ github["pulls"] += [pull]++ # Create urgent events to cause a ping+ github["events"][pull["number"]] = make_urgent_events(urgency, events)++ _setup_branch_protection(github, pull)++ post_reminders("not_set", dry_run=False)++ assert pull["number"] in github["posted_comments"]diff --git a/catalog/tests/factories/github/__init__.py b/catalog/tests/factories/github/__init__.pyindex f612f10ab..25c04e272 100644--- a/catalog/tests/factories/github/__init__.py+++ b/catalog/tests/factories/github/__init__.py@@ -1,5 +1,8 @@import datetimeimport json+import random+from collections import namedtuple+from functools import partialfrom pathlib import Pathfrom typing import Literal@@ -15,7 +18,7 @@ def _read_fixture(fixture: str) -> dict:return json.loads(file.read())-def _make_label(priority: Urgency) -> dict:+def _make_label(priority: Urgency.Urgency) -> dict:return {"name": f"priority: {priority.label}"}@@ -36,8 +39,10 @@ def walk_backwards_in_time_until_weekday_count(today: datetime.datetime, count:_pr_count = 1+_id_offset = 1000000-def make_pull(urgency: Urgency, past_due: bool, base_branch: str = "main") -> dict:++def make_pull(urgency: Urgency, old: bool, base_branch: str = "main") -> dict:"""Create a PR object like the one returned by the GitHub API.@@ -49,11 +54,33 @@ def make_pull(urgency: Urgency, past_due: bool, base_branch: str = "main") -> diurgency of the PR.:param urgency: The priority to apply to the PR.- :param past_due: Whether to create a PR that is "past due".+ :param old: Whether to create a PR with a created_at date beyond+ the urgency window for ``urgency``.+ :param base_branch: The target branch for the PR."""global _pr_countpull = _read_fixture("pull")- pull["number"] = pull["id"] = _pr_count+ # PR "number" is the number for the repository+ # that we're used to+ pull["number"] = _pr_count+ # PR "id" is GitHub's internal unique identifier+ # for the PR across all PRs on GitHub. It must+ # be different from the "number" to ensure+ # we're not confusing the two in code.+ # Instead of tracking a separate number,+ # we can add a huge number to the _pr_count.+ # This would only ever be a problem if our+ # function was used to generate more+ # PR fixtures than the id offset accounts+ # for. If that ever becomes the case, just add+ # a 0 to the end of ``_id_offset`` above+ # and it will resolve the issue.+ # Note: We could use a UUID for this to prevent+ # all possible collision with ``number`` from+ # but GitHub uses integers for this property+ # so to keep realistic-ish fixture data we+ # should prefer an integer here as well.+ pull["id"] = _pr_count + _id_offset_pr_count += 1for label in pull["labels"]:@@ -61,14 +88,14 @@ def make_pull(urgency: Urgency, past_due: bool, base_branch: str = "main") -> dilabel.update(**_make_label(urgency))break- if past_due:- updated_at = walk_backwards_in_time_until_weekday_count(+ if old:+ created_at = walk_backwards_in_time_until_weekday_count(datetime.datetime.now(), urgency.days)else:- updated_at = datetime.datetime.now()+ created_at = datetime.datetime.now()- pull["updated_at"] = _gh_date(updated_at)+ pull["created_at"] = _gh_date(created_at)base = pull["base"]base["ref"] = base_branch@@ -152,3 +179,109 @@ def make_branch_protection(required_reviewers: int = 2) -> dict:] = required_reviewersreturn branch_protection+++EventsConfig = namedtuple("EventsConfig", "event_name, days_since_previous_event")+++def make_events(origin_days_ago: int, events: list[str | EventsConfig]) -> list[dict]:+ """+ Create an issue events list with events starting at the origin.++ The complexity of this fixture function is necessary to ease building+ events list and testing the various states an events list can be in.++ :param origin_days_ago: The number of days ago to treat as the origin+ for the events list. If 0 then all events will be treated as being created the+ same day and days lapsed configured for individual events will be ignored.+ :param events: A list of mixed strings and (string, int) tuples. The string+ must always be an event name. If a tuple, the int should be the number+ of days to increment the event past the previous event.+ """+ result = []+ previous_event_days_ago = origin_days_ago+ for event_name in events:+ days_since_previous_event = 0+ if isinstance(event_name, tuple):+ if origin_days_ago == 0:+ # If origin days is 0 then treat all events as occurring today,+ # otherwise events configured with days lapsed would end up+ # in the future.+ days_since_previous_event = 0+ else:+ days_since_previous_event = event_name[1]++ event_name = event_name[0]++ # Example: If the previous event was 2 days ago, and it has been+ # 1 day since that previous event, then this event was 1 day ago.+ days_ago = previous_event_days_ago - days_since_previous_event+ created_at = walk_backwards_in_time_until_weekday_count(+ datetime.datetime.now(), days_ago+ )++ event = _read_fixture(f"events/{event_name}")+ event["created_at"] = _gh_date(created_at)++ previous_event_days_ago = days_ago+ result.append(event)++ return result+++def make_non_urgent_events(events: list[str | EventsConfig]) -> list[dict]:+ """+ Create an events list where all events happened today.++ By setting ``origin_days_ago`` to 0 we force the entire+ events list to happen _now_ which necessarily means+ none of the events could be considered urgent.+ """+ return make_events(0, events)+++def make_non_urgent_reviewable_events(events: list[str | EventsConfig]) -> list[dict]:+ """+ Create a reviewable but non-urgent events list.++ By adding a "ready_for_review" event at the+ end of the events list, we create valid events for+ a reviewable PR.++ We set the origin_days_ago to ensure that the last+ `ready_for_review` event happened today, guaranteeing+ that despite the reviewable status, the events will not+ be considered urgent. We do this by summing the days between+ each event in the event list.++ Suitable for testing old PRs that _must_ be+ reviewable but non-urgent. This allows us to+ combine tests that would otherwise need to be+ split out due to old PRs automatically being+ urgent if they do not have a non-urgent ready+ for review event. As this is the most common case+ for urgent PRs (i.e, PRs that have never been+ drafted or undrafted, just opened as ready for review)+ it is included in the "pingable" events examples+ but needs to be patched for old but non-urgent PRs.+ """+ events_list_days = sum(+ [event[1] if isinstance(event, tuple) else 0 for event in events]+ )++ return make_events(events_list_days, events + ["ready_for_review"])+++def make_urgent_events(+ urgency: Urgency.Urgency, events: list[str | EventsConfig]+) -> list[dict]:+ """+ Create an events list ending in an event older than the urgency days.++ Allows parametrizing events without while setting origin days+ in the test function.+ """+ events_list_days = sum(+ [event[1] if isinstance(event, tuple) else 0 for event in events]+ )+ return make_events(events_list_days + urgency.days, events)diff --git a/catalog/tests/factories/github/events/convert_to_draft.json b/catalog/tests/factories/github/events/convert_to_draft.jsonnew file mode 100644index 000000000..1a2d6bfde--- /dev/null+++ b/catalog/tests/factories/github/events/convert_to_draft.json@@ -0,0 +1,30 @@+{+ "id": 9162154723,+ "node_id": "CTDE_lADOFU_ugM5lB45_zwAAAAIiG2Lj",+ "url": "https://api.github.com/repos/WordPress/openverse/issues/events/9162154723",+ "actor": {+ "login": "octocat",+ "id": 24264157,+ "node_id": "MDQ6VXNlcjI0MjY0MTU3",+ "avatar_url": "https://avatars.githubusercontent.com/u/24264157?v=4",+ "gravatar_id": "",+ "url": "https://api.github.com/users/octocat",+ "html_url": "https://github.com/octocat",+ "followers_url": "https://api.github.com/users/octocat/followers",+ "following_url": "https://api.github.com/users/octocat/following{/other_user}",+ "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",+ "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",+ "subscriptions_url": "https://api.github.com/users/octocat/subscriptions",+ "organizations_url": "https://api.github.com/users/octocat/orgs",+ "repos_url": "https://api.github.com/users/octocat/repos",+ "events_url": "https://api.github.com/users/octocat/events{/privacy}",+ "received_events_url": "https://api.github.com/users/octocat/received_events",+ "type": "User",+ "site_admin": false+ },+ "event": "convert_to_draft",+ "commit_id": null,+ "commit_url": null,+ "created_at": "2023-05-04T02:47:33Z",+ "performed_via_github_app": null+}diff --git a/catalog/tests/factories/github/events/labeled.json b/catalog/tests/factories/github/events/labeled.jsonnew file mode 100644index 000000000..9230b1064--- /dev/null+++ b/catalog/tests/factories/github/events/labeled.json@@ -0,0 +1,34 @@+{+ "id": 9161178634,+ "node_id": "LE_lADOFU_ugM5lB45_zwAAAAIiDH4K",+ "url": "https://api.github.com/repos/WordPress/openverse/issues/events/9161178634",+ "actor": {+ "login": "octocat",+ "id": 24264157,+ "node_id": "MDQ6VXNlcjI0MjY0MTU3",+ "avatar_url": "https://avatars.githubusercontent.com/u/24264157?v=4",+ "gravatar_id": "",+ "url": "https://api.github.com/users/octocat",+ "html_url": "https://github.com/octocat",+ "followers_url": "https://api.github.com/users/octocat/followers",+ "following_url": "https://api.github.com/users/octocat/following{/other_user}",+ "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",+ "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",+ "subscriptions_url": "https://api.github.com/users/octocat/subscriptions",+ "organizations_url": "https://api.github.com/users/octocat/orgs",+ "repos_url": "https://api.github.com/users/octocat/repos",+ "events_url": "https://api.github.com/users/octocat/events{/privacy}",+ "received_events_url": "https://api.github.com/users/octocat/received_events",+ "type": "User",+ "site_admin": false+ },+ "event": "labeled",+ "commit_id": null,+ "commit_url": null,+ "created_at": "2023-05-03T23:48:32Z",+ "label": {+ "name": "skip-changelog",+ "color": "ededed"+ },+ "performed_via_github_app": null+}diff --git a/catalog/tests/factories/github/events/ready_for_review.json b/catalog/tests/factories/github/events/ready_for_review.jsonnew file mode 100644index 000000000..80a90f183--- /dev/null+++ b/catalog/tests/factories/github/events/ready_for_review.json@@ -0,0 +1,30 @@+{+ "id": 9162155584,+ "node_id": "RFRE_lADOFU_ugM5lB45_zwAAAAIiG2ZA",+ "url": "https://api.github.com/repos/WordPress/openverse/issues/events/9162155584",+ "actor": {+ "login": "octocat",+ "id": 24264157,+ "node_id": "MDQ6VXNlcjI0MjY0MTU3",+ "avatar_url": "<redacted>",+ "gravatar_id": "",+ "url": "https://api.github.com/users/octocat",+ "html_url": "https://github.com/octocat",+ "followers_url": "https://api.github.com/users/octocat/followers",+ "following_url": "https://api.github.com/users/octocat/following{/other_user}",+ "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",+ "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",+ "subscriptions_url": "https://api.github.com/users/octocat/subscriptions",+ "organizations_url": "https://api.github.com/users/octocat/orgs",+ "repos_url": "https://api.github.com/users/octocat/repos",+ "events_url": "https://api.github.com/users/octocat/events{/privacy}",+ "received_events_url": "https://api.github.com/users/octocat/received_events",+ "type": "User",+ "site_admin": false+ },+ "event": "ready_for_review",+ "commit_id": null,+ "commit_url": null,+ "created_at": "2023-05-04T02:47:41Z",+ "performed_via_github_app": null+}diff --git a/catalog/tests/factories/github/events/review_requested.json b/catalog/tests/factories/github/events/review_requested.jsonnew file mode 100644index 000000000..4ffa8d136--- /dev/null+++ b/catalog/tests/factories/github/events/review_requested.json@@ -0,0 +1,70 @@+{+ "id": 9161178690,+ "node_id": "RRE_lADOFU_ugM5lB45_zwAAAAIiDH5C",+ "url": "https://api.github.com/repos/WordPress/openverse/issues/events/9161178690",+ "actor": {+ "login": "octocat",+ "id": 24264157,+ "node_id": "MDQ6VXNlcjI0MjY0MTU3",+ "avatar_url": "https://avatars.githubusercontent.com/u/24264157?v=4",+ "gravatar_id": "",+ "url": "https://api.github.com/users/octocat",+ "html_url": "https://github.com/octocat",+ "followers_url": "https://api.github.com/users/octocat/followers",+ "following_url": "https://api.github.com/users/octocat/following{/other_user}",+ "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",+ "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",+ "subscriptions_url": "https://api.github.com/users/octocat/subscriptions",+ "organizations_url": "https://api.github.com/users/octocat/orgs",+ "repos_url": "https://api.github.com/users/octocat/repos",+ "events_url": "https://api.github.com/users/octocat/events{/privacy}",+ "received_events_url": "https://api.github.com/users/octocat/received_events",+ "type": "User",+ "site_admin": false+ },+ "event": "review_requested",+ "commit_id": null,+ "commit_url": null,+ "created_at": "2023-05-03T23:48:33Z",+ "review_requester": {+ "login": "octocat",+ "id": 24264157,+ "node_id": "MDQ6VXNlcjI0MjY0MTU3",+ "avatar_url": "https://avatars.githubusercontent.com/u/24264157?v=4",+ "gravatar_id": "",+ "url": "https://api.github.com/users/octocat",+ "html_url": "https://github.com/octocat",+ "followers_url": "https://api.github.com/users/octocat/followers",+ "following_url": "https://api.github.com/users/octocat/following{/other_user}",+ "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",+ "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",+ "subscriptions_url": "https://api.github.com/users/octocat/subscriptions",+ "organizations_url": "https://api.github.com/users/octocat/orgs",+ "repos_url": "https://api.github.com/users/octocat/repos",+ "events_url": "https://api.github.com/users/octocat/events{/privacy}",+ "received_events_url": "https://api.github.com/users/octocat/received_events",+ "type": "User",+ "site_admin": false+ },+ "requested_reviewer": {+ "login": "obulat",+ "id": 15233243,+ "node_id": "MDQ6VXNlcjE1MjMzMjQz",+ "avatar_url": "https://avatars.githubusercontent.com/u/15233243?v=4",+ "gravatar_id": "",+ "url": "https://api.github.com/users/obulat",+ "html_url": "https://github.com/obulat",+ "followers_url": "https://api.github.com/users/obulat/followers",+ "following_url": "https://api.github.com/users/obulat/following{/other_user}",+ "gists_url": "https://api.github.com/users/obulat/gists{/gist_id}",+ "starred_url": "https://api.github.com/users/obulat/starred{/owner}{/repo}",+ "subscriptions_url": "https://api.github.com/users/obulat/subscriptions",+ "organizations_url": "https://api.github.com/users/obulat/orgs",+ "repos_url": "https://api.github.com/users/obulat/repos",+ "events_url": "https://api.github.com/users/obulat/events{/privacy}",+ "received_events_url": "https://api.github.com/users/obulat/received_events",+ "type": "User",+ "site_admin": false+ },+ "performed_via_github_app": null+}