import responses import pytest from src import github @responses.activate def test_fetch_user_data_returns_user_payload(): # 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"}, 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 assert "events" in data @responses.activate def test_fetch_handles_404(): responses.add( responses.GET, "https://api.github.com/users/nope", json={"message": "Not Found"}, status=404, ) responses.add( 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, ) responses.add( 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 @responses.activate def test_commit_count_raises_on_graphql_rate_limit(): # GraphQL reports a rate limit as HTTP 200 with an `errors` array — the # exact shape a valid response uses. It must NOT be swallowed into a 0 # that would overwrite the last good count in fetcher.db. responses.add( responses.POST, "https://api.github.com/graphql", json={"data": {"user": None}, "errors": [{"type": "RATE_LIMITED", "message": "API rate limit exceeded"}]}, status=200, ) src = github.DirectAPISource(token="t") with pytest.raises(github.GitHubTransientError): src.fetch_commit_count("alice", []) @responses.activate def test_commit_count_raises_on_rest_rate_limit(): # A 403 with the remaining budget at 0 is a rate limit, not a real answer. responses.add( responses.POST, "https://api.github.com/graphql", json={"message": "rate limited"}, status=403, headers={"X-RateLimit-Remaining": "0"}, ) src = github.DirectAPISource(token="t") with pytest.raises(github.GitHubTransientError): src.fetch_commit_count("alice", []) @responses.activate def test_commit_count_zero_on_not_found_is_not_transient(): # A genuinely unknown user (NOT_FOUND, no rate-limit error) is a real, # persistable "no data" answer — return 0, don't raise. responses.add( responses.POST, "https://api.github.com/graphql", json={"data": {"user": None}}, status=200, ) src = github.DirectAPISource(token="t") assert src.fetch_commit_count("ghost", []) == 0 # --- REST rate-limit guards ------------------------------------------------- # The REST calls used to hand `.json()` straight back, so a 403 rate-limit body # ({"message": "API rate limit exceeded for user ID ..."}) was persisted as if # it were real data, wiping the user's last-good record for up to 24h. RATE_LIMIT_BODY = { "message": "API rate limit exceeded for user ID 123.", "documentation_url": "https://docs.github.com/rest/overview/rate-limits", } RATE_LIMIT_HEADERS = {"X-RateLimit-Remaining": "0"} @responses.activate def test_fetch_user_data_raises_on_rest_rate_limit(): responses.add( responses.GET, "https://api.github.com/users/alice", json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS, ) src = github.DirectAPISource(token="t") with pytest.raises(github.GitHubTransientError): src.fetch_user_data("alice") @responses.activate def test_fetch_user_data_raises_on_rate_limit_without_header(): # Secondary rate limits come back as 403 without the remaining-budget # header — the message is the only signal. responses.add( responses.GET, "https://api.github.com/users/alice", json={"message": "You have exceeded a secondary rate limit."}, status=403, ) src = github.DirectAPISource(token="t") with pytest.raises(github.GitHubTransientError): src.fetch_user_data("alice") @responses.activate def test_fetch_repos_raises_on_rest_rate_limit(): responses.add( responses.GET, "https://api.github.com/users/alice/repos", json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS, ) src = github.DirectAPISource(token="t") with pytest.raises(github.GitHubTransientError): src.fetch_repos("alice") @responses.activate def test_fetch_events_raises_on_rest_rate_limit(): responses.add( responses.GET, "https://api.github.com/users/alice/events", json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS, ) src = github.DirectAPISource(token="t") with pytest.raises(github.GitHubTransientError): src.fetch_events("alice") @responses.activate def test_fetch_repo_contributors_raises_on_rest_rate_limit(): responses.add( responses.GET, "https://api.github.com/repos/alice/proj/contributors", json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS, ) src = github.DirectAPISource(token="t") with pytest.raises(github.GitHubTransientError): src.fetch_repo_contributors("alice/proj") @responses.activate def test_fetch_repo_languages_raises_on_rest_rate_limit(): responses.add( responses.GET, "https://api.github.com/repos/alice/proj/languages", json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS, ) src = github.DirectAPISource(token="t") with pytest.raises(github.GitHubTransientError): src.fetch_repo_languages("alice/proj") @responses.activate def test_single_repo_404_stays_non_fatal(): # A deleted/renamed repo is a real per-repo answer, not a budget problem: # it must keep degrading gracefully instead of aborting the whole fetch. responses.add( responses.GET, "https://api.github.com/repos/alice/gone/languages", json={"message": "Not Found"}, status=404, ) responses.add( responses.GET, "https://api.github.com/repos/alice/gone/contributors", json={"message": "Not Found"}, status=404, ) src = github.DirectAPISource(token="t") assert src.fetch_repo_languages("alice/gone") == {} assert src.fetch_repo_contributors("alice/gone") == [] @responses.activate def test_rest_success_path_unchanged(): responses.add( responses.GET, "https://api.github.com/users/alice", json={"login": "alice", "followers": 5}, status=200, ) responses.add( responses.GET, "https://api.github.com/users/alice/events", json=[{"type": "PushEvent"}], status=200, ) responses.add( responses.GET, "https://api.github.com/repos/alice/proj/languages", json={"Python": 100}, status=200, ) responses.add( responses.GET, "https://api.github.com/repos/alice/proj/contributors", json=[{"login": "bob", "contributions": 4}], status=200, ) src = github.DirectAPISource(token="t") assert src.fetch_user_data("alice")["login"] == "alice" assert src.fetch_events("alice") == [{"type": "PushEvent"}] assert src.fetch_repo_languages("alice/proj") == {"Python": 100} assert src.fetch_repo_contributors("alice/proj") == [{"login": "bob", "contributions": 4}] @responses.activate def test_rate_limited_repo_languages_aborts_whole_fetch(): # A rate limit inside the per-repo fan-out means the budget is gone, so it # must propagate rather than being swallowed into an empty breakdown. responses.add( responses.GET, "https://api.github.com/repos/alice/proj/languages", json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS, ) src = github.DirectAPISource(token="t") repos = [{"full_name": "alice/proj"}] with pytest.raises(github.GitHubTransientError): github._enrich_repo_languages(repos, src) def test_repo_languages_capped_to_recent_owned_repos(monkeypatch): # One REST call per repo, so only the most recently pushed non-fork repos # the user owns get a byte breakdown. monkeypatch.setattr(github.config, "LANGUAGE_MAX_REPOS", 2) class _Src: def __init__(self): self.calls = [] def fetch_repo_languages(self, full_name): self.calls.append(full_name) return {"Python": 1} repos = [ {"full_name": "Alice/old", "pushed_at": "2024-01-01T00:00:00Z"}, {"full_name": "alice/new", "pushed_at": "2026-01-01T00:00:00Z"}, {"full_name": "alice/mid", "pushed_at": "2025-01-01T00:00:00Z"}, {"full_name": "alice/fork", "pushed_at": "2026-06-01T00:00:00Z", "fork": True}, {"full_name": "org/other", "pushed_at": "2026-06-01T00:00:00Z"}, ] src = _Src() github._enrich_repo_languages(repos, src, "alice") assert sorted(src.calls) == ["alice/mid", "alice/new"] assert repos[1]["language_bytes"] == {"Python": 1} assert "language_bytes" not in repos[0] @responses.activate def test_rate_limit_error_carries_retry_after(): responses.add( responses.GET, "https://api.github.com/users/alice", json={"message": "You have exceeded a secondary rate limit."}, status=403, headers={"Retry-After": "42"}, ) src = github.DirectAPISource(token="t") with pytest.raises(github.GitHubTransientError) as exc: src.fetch_user_data("alice") assert exc.value.retry_after == 42