feat(tests): implement dynamic GraphQL response handling for tests

This commit is contained in:
shay
2026-05-04 12:56:52 -04:00
parent 4a1d31ffdd
commit 673eb5b39d
3 changed files with 118 additions and 116 deletions
+48 -43
View File
@@ -139,21 +139,22 @@ class DirectAPISource:
def fetch_repos(self, username: str) -> list: def fetch_repos(self, username: str) -> list:
"""Fetch user repositories (owned + contributed to).""" """Fetch user repositories (owned + contributed to)."""
_assert_username(username) _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) def _get(repo_type: str):
all_repos = requests.get( return requests.get(
f"{self.base}/users/{username}/repos", f"{self.base}/users/{username}/repos",
headers=self.headers, headers=self.headers,
params={"per_page": 100, "sort": "pushed", "type": "all"}, params={"per_page": 100, "sort": "pushed", "type": repo_type},
timeout=config.API_TIMEOUT, timeout=config.API_TIMEOUT,
).json() ).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 # Combine and deduplicate
repos = owned if isinstance(owned, list) else [] repos = owned if isinstance(owned, list) else []
@@ -614,40 +615,44 @@ def fetch_github_data(
# Use provided data source or default to direct API # Use provided data source or default to direct API
source = data_source or DirectAPISource(token) 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") 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 # Stage 1: every fetch with no dependencies on another fetch's result
print(" Fetching PR count...") # runs in parallel. Previously these 8 calls ran one at a time, so the
total_prs = source.fetch_pr_count(username) # 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 user = fut_user.result()
collaborators_data = _fetch_collaborators_data( repos = fut_repos.result()
username, repos, source 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 = "" avatar_b64 = ""
if user.get("avatar_url"): avatar_url = user.get("avatar_url") if isinstance(user, dict) else None
avatar_b64 = source.fetch_avatar(user["avatar_url"]) 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 { return {
"user": user, "user": user,
+32 -22
View File
@@ -32,31 +32,41 @@ def test_endpoints_require_internal_token(client):
@resp_lib.activate @resp_lib.activate
def test_data_auto_fetches_on_miss(client, monkeypatch): def test_data_auto_fetches_on_miss(client, monkeypatch):
# fetch_commits: contributionCalendar/weeks # The fetcher fires the independent GitHub calls in parallel, so we
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql", # can't rely on a fixed FIFO order of `resp_lib.add` calls. Match each
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}}}, status=200) # GraphQL call by inspecting the request body and returning the right
# fetch_commit_count (alltime) — first call: get createdAt # response for that query — this mirrors how the real GitHub API
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql", # routes by query content rather than insertion order.
json={"data": {"user": {"createdAt": "2020-01-01T00:00:00Z"}}}, status=200) import json as _json
# fetch_commit_count (alltime) — per-year contribution totals (2020–2026, 7 years)
for _ in range(7): def _graphql_callback(request):
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql", body = _json.loads(request.body)
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 10}}}}}, q = body.get("query", "")
status=200) variables = body.get("variables", {})
# fetch_commit_count (recent, last 6 months) if "weeks" in q:
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql", data = {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}}
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 5}}}}}, elif "createdAt" in q:
status=200) data = {"user": {"createdAt": "2020-01-01T00:00:00Z"}}
# fetch_user_commit_repos (for collaborators) elif "commitContributionsByRepository" in q:
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql", data = {"user": {"contributionsCollection": {"commitContributionsByRepository": []}}}
json={"data": {"user": {"contributionsCollection": {"commitContributionsByRepository": []}}}}, elif "contributionCalendar" in q and "totalContributions" in q:
status=200) # Both alltime per-year and 6-month range queries land here. Tests
# PR count search # 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", resp_lib.add(resp_lib.GET, "https://api.github.com/search/issues",
json={"total_count": 0, "items": []}, status=200) json={"total_count": 0, "items": []}, status=200)
resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice", 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) json={"login": "alice", "public_repos": 1, "followers": 0,
# fetch_repos: two calls (owner + all) "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/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) resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/events", json=[], status=200)
+38 -51
View File
@@ -5,61 +5,38 @@ from src import github
@responses.activate @responses.activate
def test_fetch_user_data_returns_user_payload(): def test_fetch_user_data_returns_user_payload():
# fetch_commits: contributionCalendar/weeks # The fetcher fires the independent GitHub calls in parallel, so the
responses.add( # mock registry can't depend on FIFO ordering. Route GraphQL requests
responses.POST, "https://api.github.com/graphql", # by query content instead.
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}}}, import json as _json
status=200,
) def _graphql_callback(request):
# fetch_commit_count (alltime) — first call: get createdAt q = _json.loads(request.body).get("query", "")
responses.add( if "weeks" in q:
responses.POST, "https://api.github.com/graphql", data = {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}}
json={"data": {"user": {"createdAt": "2020-01-01T00:00:00Z"}}}, elif "createdAt" in q:
status=200, data = {"user": {"createdAt": "2020-01-01T00:00:00Z"}}
) elif "commitContributionsByRepository" in q:
# fetch_commit_count (alltime) — per-year contribution totals (2020–2026) data = {"user": {"contributionsCollection": {"commitContributionsByRepository": []}}}
for _ in range(7): elif "totalContributions" in q:
responses.add( data = {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 10}}}}
responses.POST, "https://api.github.com/graphql", else:
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 10}}}}}, data = {"user": None}
status=200, return (200, {}, _json.dumps({"data": data}))
)
# fetch_commit_count (recent, last 6 months) responses.add_callback(responses.POST, "https://api.github.com/graphql",
responses.add( callback=_graphql_callback)
responses.POST, "https://api.github.com/graphql", responses.add(responses.GET, "https://api.github.com/search/issues",
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 5}}}}}, json={"total_count": 0, "items": []}, status=200)
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,
)
responses.add( responses.add(
responses.GET, "https://api.github.com/users/alice", 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, 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.add(responses.GET, "https://api.github.com/users/alice/repos", json=[], status=200)
responses.GET, "https://api.github.com/users/alice/repos", responses.add(responses.GET, "https://api.github.com/users/alice/events", json=[], status=200)
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") data = github.fetch_github_data("alice", token="t")
assert data["user"]["login"] == "alice" assert data["user"]["login"] == "alice"
assert "repos" in data assert "repos" in data
@@ -76,6 +53,12 @@ def test_fetch_handles_404():
responses.POST, "https://api.github.com/graphql", responses.POST, "https://api.github.com/graphql",
json={"data": {"user": None}}, status=200, 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.add(
responses.GET, "https://api.github.com/users/nope/repos", responses.GET, "https://api.github.com/users/nope/repos",
json={"message": "Not Found"}, status=404, json={"message": "Not Found"}, status=404,
@@ -84,5 +67,9 @@ def test_fetch_handles_404():
responses.GET, "https://api.github.com/users/nope/events", responses.GET, "https://api.github.com/users/nope/events",
json={"message": "Not Found"}, status=404, 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") data = github.fetch_github_data("nope", token="t")
assert data["user"].get("message") == "Not Found" or data["user"] is None assert data["user"].get("message") == "Not Found" or data["user"] is None