From 673eb5b39d27464d4ecea23633737d4706a4f0c3 Mon Sep 17 00:00:00 2001 From: shay Date: Mon, 4 May 2026 12:56:52 -0400 Subject: [PATCH] feat(tests): implement dynamic GraphQL response handling for tests --- fetcher/src/github.py | 91 +++++++++++++++++++----------------- fetcher/tests/test_api.py | 54 ++++++++++++--------- fetcher/tests/test_github.py | 89 +++++++++++++++-------------------- 3 files changed, 118 insertions(+), 116 deletions(-) diff --git a/fetcher/src/github.py b/fetcher/src/github.py index 2cdcb70..29108e9 100644 --- a/fetcher/src/github.py +++ b/fetcher/src/github.py @@ -139,21 +139,22 @@ class DirectAPISource: def fetch_repos(self, username: str) -> list: """Fetch user repositories (owned + contributed to).""" _assert_username(username) - # Fetch owned repos - owned = requests.get( - f"{self.base}/users/{username}/repos", - headers=self.headers, - params={"per_page": 100, "sort": "pushed", "type": "owner"}, - timeout=config.API_TIMEOUT, - ).json() - # Fetch all repos (includes collabs, orgs) - all_repos = requests.get( - f"{self.base}/users/{username}/repos", - headers=self.headers, - params={"per_page": 100, "sort": "pushed", "type": "all"}, - timeout=config.API_TIMEOUT, - ).json() + def _get(repo_type: str): + return requests.get( + f"{self.base}/users/{username}/repos", + headers=self.headers, + params={"per_page": 100, "sort": "pushed", "type": repo_type}, + timeout=config.API_TIMEOUT, + ).json() + + # The two REST calls are independent — fire them in parallel so the + # second isn't waiting on the first to come back. + with ThreadPoolExecutor(max_workers=2, thread_name_prefix="fetch-repos") as pool: + fut_owned = pool.submit(_get, "owner") + fut_all = pool.submit(_get, "all") + owned = fut_owned.result() + all_repos = fut_all.result() # Combine and deduplicate repos = owned if isinstance(owned, list) else [] @@ -614,40 +615,44 @@ def fetch_github_data( # Use provided data source or default to direct API source = data_source or DirectAPISource(token) - # Fetch all data through the data source abstraction - user = source.fetch_user_data(username) - repos = source.fetch_repos(username) - events = source.fetch_events(username) - commits = source.fetch_commits(username) - - # Attach per-repo language byte breakdown. Without this, the languages - # widget falls back to a primary-language repo-count tally, which - # heavily under-represents repos whose primary language has small files - # (e.g. HTML, Jupyter Notebook). - _enrich_repo_languages(repos, source) - - # Fetch contribution counts (commits + PRs + issues + reviews) - print(" Fetching all-time contribution count...") - total_commits = source.fetch_commit_count(username, repos) - - # Recent contributions (last 6 months) six_months_ago = (datetime.now() - timedelta(days=180)).strftime("%Y-%m-%d") - print(" Fetching recent contribution count (last 6 months)...") - recent_commits = source.fetch_commit_count(username, repos, since_date=six_months_ago) - # Fetch PR count - print(" Fetching PR count...") - total_prs = source.fetch_pr_count(username) + # Stage 1: every fetch with no dependencies on another fetch's result + # runs in parallel. Previously these 8 calls ran one at a time, so the + # whole pipeline was wait-time × 8. Each is I/O-bound (a single HTTPS + # request to GitHub or a small GraphQL query), so threading is the + # right primitive. _fetch_collaborators_data internally calls + # fetch_user_commit_repos and ignores the `repos` arg, so it has no + # ordering dependency on fetch_repos — start them together. + with ThreadPoolExecutor(max_workers=10, thread_name_prefix="fetch-stage1") as pool: + fut_user = pool.submit(source.fetch_user_data, username) + fut_repos = pool.submit(source.fetch_repos, username) + fut_events = pool.submit(source.fetch_events, username) + fut_commits = pool.submit(source.fetch_commits, username) + fut_total = pool.submit(source.fetch_commit_count, username, []) + fut_recent = pool.submit(source.fetch_commit_count, username, [], six_months_ago) + fut_prs = pool.submit(source.fetch_pr_count, username) + fut_collab = pool.submit(_fetch_collaborators_data, username, [], source) - # Fetch collaborators from user's active repos - collaborators_data = _fetch_collaborators_data( - username, repos, source - ) + user = fut_user.result() + repos = fut_repos.result() + events = fut_events.result() + commits = fut_commits.result() + total_commits = fut_total.result() + recent_commits = fut_recent.result() + total_prs = fut_prs.result() + collaborators_data = fut_collab.result() - # Fetch avatar + # Stage 2: avatar needs user.avatar_url, languages need the repos list. + # Both run in parallel against each other. avatar_b64 = "" - if user.get("avatar_url"): - avatar_b64 = source.fetch_avatar(user["avatar_url"]) + avatar_url = user.get("avatar_url") if isinstance(user, dict) else None + with ThreadPoolExecutor(max_workers=2, thread_name_prefix="fetch-stage2") as pool: + fut_lang = pool.submit(_enrich_repo_languages, repos, source) + fut_avatar = pool.submit(source.fetch_avatar, avatar_url) if avatar_url else None + fut_lang.result() + if fut_avatar is not None: + avatar_b64 = fut_avatar.result() return { "user": user, diff --git a/fetcher/tests/test_api.py b/fetcher/tests/test_api.py index 008b5d1..b44ecaa 100644 --- a/fetcher/tests/test_api.py +++ b/fetcher/tests/test_api.py @@ -32,31 +32,41 @@ def test_endpoints_require_internal_token(client): @resp_lib.activate def test_data_auto_fetches_on_miss(client, monkeypatch): - # fetch_commits: contributionCalendar/weeks - resp_lib.add(resp_lib.POST, "https://api.github.com/graphql", - json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}}}, status=200) - # fetch_commit_count (alltime) — first call: get createdAt - resp_lib.add(resp_lib.POST, "https://api.github.com/graphql", - json={"data": {"user": {"createdAt": "2020-01-01T00:00:00Z"}}}, status=200) - # fetch_commit_count (alltime) — per-year contribution totals (2020–2026, 7 years) - for _ in range(7): - resp_lib.add(resp_lib.POST, "https://api.github.com/graphql", - json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 10}}}}}, - status=200) - # fetch_commit_count (recent, last 6 months) - resp_lib.add(resp_lib.POST, "https://api.github.com/graphql", - json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 5}}}}}, - status=200) - # fetch_user_commit_repos (for collaborators) - resp_lib.add(resp_lib.POST, "https://api.github.com/graphql", - json={"data": {"user": {"contributionsCollection": {"commitContributionsByRepository": []}}}}, - status=200) - # PR count search + # The fetcher fires the independent GitHub calls in parallel, so we + # can't rely on a fixed FIFO order of `resp_lib.add` calls. Match each + # GraphQL call by inspecting the request body and returning the right + # response for that query — this mirrors how the real GitHub API + # routes by query content rather than insertion order. + import json as _json + + def _graphql_callback(request): + body = _json.loads(request.body) + q = body.get("query", "") + variables = body.get("variables", {}) + if "weeks" in q: + data = {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}} + elif "createdAt" in q: + data = {"user": {"createdAt": "2020-01-01T00:00:00Z"}} + elif "commitContributionsByRepository" in q: + data = {"user": {"contributionsCollection": {"commitContributionsByRepository": []}}} + elif "contributionCalendar" in q and "totalContributions" in q: + # Both alltime per-year and 6-month range queries land here. Tests + # don't care about the exact totals — just that a number comes back. + data = {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 10}}}} + else: + data = {"user": None} + return (200, {}, _json.dumps({"data": data})) + + resp_lib.add_callback(resp_lib.POST, "https://api.github.com/graphql", + callback=_graphql_callback) + resp_lib.add(resp_lib.GET, "https://api.github.com/search/issues", json={"total_count": 0, "items": []}, status=200) resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice", - json={"login": "alice", "public_repos": 1, "followers": 0, "avatar_url": "https://avatars.example/a"}, status=200) - # fetch_repos: two calls (owner + all) + json={"login": "alice", "public_repos": 1, "followers": 0, + "avatar_url": "https://avatars.example/a"}, + status=200) + # fetch_repos fires the owner+all calls in parallel; both hit the same URL. resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/repos", json=[], status=200) resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/repos", json=[], status=200) resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/events", json=[], status=200) diff --git a/fetcher/tests/test_github.py b/fetcher/tests/test_github.py index e9b6494..88346ae 100644 --- a/fetcher/tests/test_github.py +++ b/fetcher/tests/test_github.py @@ -5,61 +5,38 @@ from src import github @responses.activate def test_fetch_user_data_returns_user_payload(): - # fetch_commits: contributionCalendar/weeks - responses.add( - responses.POST, "https://api.github.com/graphql", - json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}}}, - status=200, - ) - # fetch_commit_count (alltime) — first call: get createdAt - responses.add( - responses.POST, "https://api.github.com/graphql", - json={"data": {"user": {"createdAt": "2020-01-01T00:00:00Z"}}}, - status=200, - ) - # fetch_commit_count (alltime) — per-year contribution totals (2020–2026) - for _ in range(7): - responses.add( - responses.POST, "https://api.github.com/graphql", - json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 10}}}}}, - status=200, - ) - # fetch_commit_count (recent, last 6 months) - responses.add( - responses.POST, "https://api.github.com/graphql", - json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 5}}}}}, - status=200, - ) - # fetch_user_commit_repos (for collaborators) - responses.add( - responses.POST, "https://api.github.com/graphql", - json={"data": {"user": {"contributionsCollection": {"commitContributionsByRepository": []}}}}, - status=200, - ) - # PR count search - responses.add( - responses.GET, "https://api.github.com/search/issues", - json={"total_count": 0, "items": []}, - status=200, - ) + # The fetcher fires the independent GitHub calls in parallel, so the + # mock registry can't depend on FIFO ordering. Route GraphQL requests + # by query content instead. + import json as _json + + def _graphql_callback(request): + q = _json.loads(request.body).get("query", "") + if "weeks" in q: + data = {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}} + elif "createdAt" in q: + data = {"user": {"createdAt": "2020-01-01T00:00:00Z"}} + elif "commitContributionsByRepository" in q: + data = {"user": {"contributionsCollection": {"commitContributionsByRepository": []}}} + elif "totalContributions" in q: + data = {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 10}}}} + else: + data = {"user": None} + return (200, {}, _json.dumps({"data": data})) + + responses.add_callback(responses.POST, "https://api.github.com/graphql", + callback=_graphql_callback) + responses.add(responses.GET, "https://api.github.com/search/issues", + json={"total_count": 0, "items": []}, status=200) responses.add( responses.GET, "https://api.github.com/users/alice", - json={"login": "alice", "public_repos": 3, "followers": 5, "avatar_url": "https://avatars.example/1"}, + json={"login": "alice", "public_repos": 3, "followers": 5, + "avatar_url": "https://avatars.example/1"}, status=200, ) - # fetch_repos: two calls (owner + all) - responses.add( - responses.GET, "https://api.github.com/users/alice/repos", - json=[], status=200, - ) - responses.add( - responses.GET, "https://api.github.com/users/alice/repos", - json=[], status=200, - ) - responses.add( - responses.GET, "https://api.github.com/users/alice/events", - json=[], status=200, - ) + responses.add(responses.GET, "https://api.github.com/users/alice/repos", json=[], status=200) + responses.add(responses.GET, "https://api.github.com/users/alice/repos", json=[], status=200) + responses.add(responses.GET, "https://api.github.com/users/alice/events", json=[], status=200) data = github.fetch_github_data("alice", token="t") assert data["user"]["login"] == "alice" assert "repos" in data @@ -76,6 +53,12 @@ def test_fetch_handles_404(): responses.POST, "https://api.github.com/graphql", json={"data": {"user": None}}, status=200, ) + # Both fetch_repos calls (owner + all) hit the same URL — register + # twice so the parallel firing gets a response either way round. + responses.add( + responses.GET, "https://api.github.com/users/nope/repos", + json={"message": "Not Found"}, status=404, + ) responses.add( responses.GET, "https://api.github.com/users/nope/repos", json={"message": "Not Found"}, status=404, @@ -84,5 +67,9 @@ def test_fetch_handles_404(): responses.GET, "https://api.github.com/users/nope/events", json={"message": "Not Found"}, status=404, ) + responses.add( + responses.GET, "https://api.github.com/search/issues", + json={"total_count": 0, "items": []}, status=200, + ) data = github.fetch_github_data("nope", token="t") assert data["user"].get("message") == "Not Found" or data["user"] is None