返回 last30days-skill
test_github_metrics.py
根目录 / tests / test_github_metrics.py
1 """GitHub repo/profile counters keep their own units instead of posing as comments."""
2
3 import io
4 import urllib.parse
5 from datetime import datetime, timezone
6 from types import SimpleNamespace
7 from unittest.mock import patch
8
9 import pytest
10
11 from lib import dedupe, fusion, github, normalize, render, schema, signals
12
13 START, END = "2026-10-01", "2026-10-25"
14
15
16 def _fake_json(url, **kwargs):
17 parsed = urllib.parse.urlsplit(url)
18 if "/events/public" in parsed.path:
19 return [{
20 "id": "event-1", "type": "PushEvent", "actor": {"login": "alice"},
21 "repo": {"name": "alice/own"}, "created_at": "2026-10-20T12:00:00Z",
22 }]
23 if parsed.path == "/search/repositories":
24 return {"items": [{
25 "full_name": "alice/own", "stargazers_count": 123,
26 "open_issues_count": 17, "description": "Own repo", "fork": False,
27 }]}
28 if parsed.path == "/search/issues":
29 query = urllib.parse.parse_qs(parsed.query).get("q", [""])[0]
30 if "author:alice" in query:
31 merged = "is:merged" in query
32 return {
33 "total_count": 3 if merged else 8,
34 "items": [{"html_url": "https://github.com/other/ext/pull/1"}] if merged else [],
35 }
36 return {"total_count": 1, "items": [{
37 "title": "Real issue", "comments": 9, "reactions": {"total_count": 5},
38 "html_url": "https://github.com/alice/own/issues/1",
39 }]}
40 if parsed.path.endswith("/releases"):
41 return []
42 if parsed.path.startswith("/repos/"):
43 return {
44 "stargazers_count": 123, "open_issues_count": 17, "visibility": "public",
45 "description": "Repo description", "language": "Python", "forks_count": 4,
46 }
47 raise AssertionError(f"Unexpected HTTP endpoint: {url}")
48
49
50 @pytest.fixture(autouse=True)
51 def _offline_github(monkeypatch):
52 monkeypatch.setattr(github, "_fetch_json", _fake_json)
53 monkeypatch.setattr(github.http, "open_request", lambda *a, **kw: io.BytesIO(b"README"))
54
55
56 def _person_item(label):
57 items = github.search_github_person("alice", START, END, token="dummy-token")
58 return next(x for x in items if label in x["metadata"]["labels"])
59
60
61 @pytest.mark.parametrize(
62 "collect, key, count",
63 [
64 (lambda: github._person_recent_pushes(
65 "alice", START, END, github.PERSON_DEPTH_LIMITS["default"], "dummy-token")[0],
66 "open_issues", 17),
67 (lambda: _person_item("own-repo"), "open_issues", 17),
68 (lambda: _person_item("external-repo"), "contributed_prs", 1),
69 (lambda: _person_item("velocity"), "total_prs", 8),
70 (lambda: github.search_github_project(["alice/own"], START, END, token="dummy-token")[0],
71 "open_issues", 17),
72 ],
73 ids=["recent-push", "own-repo", "external-repo", "velocity", "project"],
74 )
75 def test_collector_counters_are_not_comments(collect, key, count):
76 observed = "2026-11-03"
77 received = datetime(2026, 11, 3, 9, 21, 5, tzinfo=timezone.utc)
78 with patch.object(github, "datetime", wraps=datetime) as clock, patch.object(
79 github.dates, "get_date_range", return_value=(observed, observed)
80 ):
81 clock.now.return_value = received
82 item = collect()
83 assert item["engagement"][key] == count
84 assert "comments" not in item["engagement"]
85 assert item["metadata"].get("comment_count", 0) == 0
86 card = normalize._normalize_github("github", item, 0, START, END)
87 assert card.engagement[key] == count
88 if "stars" in card.engagement:
89 assert item["metadata"]["repo_counts_observed_at"] == received.isoformat()
90 assert card.metadata["repo_counts_observed_at"] == received.isoformat()
91 assert f"Repository counts observed {observed} UTC" in card.snippet
92 else:
93 assert "repo_counts_observed_at" not in card.metadata
94
95
96 def test_project_description_survives_normalization_for_local_ranking():
97 [raw] = github.search_github_project(["alice/own"], START, END, token="dummy-token")
98 card = normalize._normalize_github("github", raw, 0, START, END)
99 assert card.metadata["repo_description"] == "Repo description"
100
101
102 @pytest.mark.parametrize("mode", ["project", "own-repo", "recent-push"])
103 def test_repo_cards_label_the_combined_open_issue_and_pr_count(mode):
104 if mode == "project":
105 [item] = github.search_github_project(["alice/own"], START, END, token="dummy-token")
106 elif mode == "recent-push":
107 [item] = github._person_recent_pushes(
108 "alice", START, END, github.PERSON_DEPTH_LIMITS["default"], "dummy-token",
109 )
110 else:
111 item = _person_item("own-repo")
112 assert "17 open issues/PRs" in item["snippet"]
113 if mode != "recent-push":
114 assert "17 open issues/PRs" in item["title"]
115
116
117 @pytest.mark.parametrize("fields, expected", [
118 ({}, {}),
119 ({"stargazers_count": 0, "open_issues_count": 0}, {"stars": 0, "open_issues": 0}),
120 ({"stargazers_count": None, "open_issues_count": 7}, {"open_issues": 7}),
121 ({"stargazers_count": 3, "open_issues_count": False}, {"stars": 3}),
122 ({"stargazers_count": -1, "open_issues_count": "5"}, {}),
123 ])
124 def test_repository_cards_publish_only_measured_counters(monkeypatch, fields, expected):
125 def fetch(url, **kwargs):
126 data = _fake_json(url, **kwargs)
127 path = urllib.parse.urlsplit(url).path
128 if path == "/search/repositories":
129 return {"items": [{"full_name": "alice/own", **fields}]}
130 if path in ("/repos/alice/own", "/repos/other/ext"):
131 return {"visibility": "public", **fields}
132 return data
133
134 monkeypatch.setattr(github, "_fetch_json", fetch)
135 [project] = github.search_github_project(["alice/own"], START, END, token="dummy-token")
136 [pushed] = github._person_recent_pushes("alice", START, END, github.PERSON_DEPTH_LIMITS["quick"], "dummy-token")
137 cards = github.search_github_person("alice", START, END, token="dummy-token")
138 for raw in [project, pushed, *(card for card in cards if "velocity" not in card["metadata"]["labels"])]:
139 external = "external-repo" in raw["metadata"]["labels"]
140 counters = dict(expected)
141 if external:
142 counters.pop("open_issues", None)
143 card = normalize._normalize_github("github", raw, 0, START, END)
144 assert card.engagement == {**counters, **({"contributed_prs": 1} if external else {})}
145 assert signals.is_repo_snapshot(card) and signals.engagement_score(card) is None
146 assert bool(card.metadata.get("repo_counts_observed_at")) == bool(counters)
147 assert ("Repository counts observed" in card.snippet) == bool(counters)
148 assert (f"{counters['stars']} stars" if "stars" in counters else "stars unavailable") in card.snippet
149 if not external:
150 assert (f"{counters['open_issues']} open issues/PRs" if "open_issues" in counters
151 else "open issue/PR count unavailable") in card.snippet
152 if "stars" not in counters:
153 assert raw.get("score") is None and raw["metadata"].get("reactions") is None
154 assert "0 stars" not in card.body + card.why_relevant
155 assert project["metadata"].get("github_stars", {}) == (
156 {"alice/own": expected["stars"]} if "stars" in expected else {}
157 )
158
159
160 def test_missing_repository_response_preserves_public_activity(monkeypatch):
161 def fetch(url, **kwargs):
162 path = urllib.parse.urlsplit(url).path
163 if path in ("/repos/alice/own", "/repos/other/ext"):
164 return None
165 return _fake_json(url, **kwargs)
166
167 monkeypatch.setattr(github, "_fetch_json", fetch)
168 contributed = _person_item("external-repo")
169 assert contributed["engagement"] == {"contributed_prs": 1}
170 assert contributed["container"] == "other/ext" and "stars unavailable" in contributed["snippet"]
171
172 def empty_pr_search(url, **kwargs):
173 if "/search/issues?" in url:
174 return {"items": [], "total_count": 0}
175 return fetch(url, **kwargs)
176
177 monkeypatch.setattr(github, "_fetch_json", empty_pr_search)
178 [raw] = github.search_github_person("alice", START, END, token="dummy-token")
179 [event] = normalize.normalize_source_items("github", [raw], START, END)
180 assert event.engagement == {}
181 assert event.published_at == "2026-10-20" and "@alice pushed alice/own" in event.title
182 assert "repo_counts_observed_at" not in event.metadata and "0 stars" not in event.body
183
184
185 @pytest.mark.parametrize("value, measured", [(None, False), (False, False), (-1, False), (0, True)])
186 def test_missing_stars_cannot_become_a_verified_or_replayed_claim(monkeypatch, value, measured):
187 response = {"visibility": "public", "stargazers_count": value}
188 monkeypatch.setattr(github, "_fetch_json", lambda *args, **kw: response)
189 monkeypatch.setattr(github.http, "request", lambda *args, **kw: response)
190 monkeypatch.setattr(github, "_resolve_token", lambda *args: "dummy-token")
191 candidate = SimpleNamespace(url="https://github.com/alice/own", title="Repo", evidence="Public project", metadata={})
192 recorded = {}
193 assert github.enrich_candidates_with_stars([candidate], collect_map=recorded) == int(measured)
194 assert recorded == ({"alice/own": 0} if measured else {})
195 assert github.apply_star_map([candidate], {"alice/own": value}) == int(measured)
196 assert ("live: 0 stars" in candidate.evidence) == measured
197 if measured:
198 assert github.refetch_datum(None, "alice/own")["value"] == 0
199 else:
200 with pytest.raises(KeyError):
201 github.refetch_datum(None, "alice/own")
202
203
204 def _item(item_id, engagement, url="https://github.com/alice/own"):
205 return schema.SourceItem(
206 item_id=item_id, source="github", title="t", body="", url=url, engagement=engagement,
207 )
208
209
210 @pytest.mark.parametrize("reverse", [False, True])
211 @pytest.mark.parametrize("include_issues", [True, False])
212 def test_repeated_repo_keeps_one_observation_and_independent_activity(reverse, include_issues):
213 older = _item("older", {"stars": 120, "open_issues": 5, "contributed_prs": 4})
214 older.metadata = {"repo_counts_observed_at": "2026-11-04T08:30:00Z", "date_is_snapshot": True,
215 "top_comments": [{"excerpt": "A previous comment"}]}
216 older.title = older.snippet = older.body = "Earlier measurement: 120 stars and five open issues and PRs"
217 older.published_at = "2026-10-02"
218 newer = _item("newer", {"stars": 100}, url="https://github.com/alice/own/")
219 if include_issues:
220 newer.engagement["open_issues"] = 17
221 newer.title = newer.snippet = newer.body = "Later measurement: 100 stars"
222 newer.published_at = "2026-10-25"
223 newer.metadata = {"repo_counts_observed_at": "2026-11-04T09:30:00Z", "date_is_snapshot": False}
224
225 [merged] = dedupe.dedupe_items([newer, older] if reverse else [older, newer])
226 assert merged.engagement == {**newer.engagement, "contributed_prs": 4}
227 assert merged.metadata["repo_counts_observed_at"] == newer.metadata["repo_counts_observed_at"]
228 assert (merged.title, merged.body, merged.snippet) == (newer.title, newer.body, newer.snippet)
229 assert merged.published_at == newer.published_at and not merged.metadata["date_is_snapshot"]
230 assert merged.metadata["top_comments"] == older.metadata["top_comments"]
231 assert older.engagement["stars"] == 120 and "top_comments" not in newer.metadata
232
233 plan = schema.QueryPlan(
234 raw_topic="repo", intent="general", freshness_mode="balanced_recent", cluster_mode="story",
235 subqueries=[schema.SubQuery(label=label, search_query="repo", ranking_query="repo", sources=["github"])
236 for label in ("a", "b")], source_weights={"github": 1.0},
237 )
238 rows = [newer, older] if reverse else [older, newer]
239 [candidate] = fusion.weighted_rrf({("a", "github"): rows[:1], ("b", "github"): rows[1:]}, plan, pool_limit=2)
240 assert (candidate.title, candidate.snippet) == (newer.title, newer.snippet)
241 assert schema.candidate_primary_item(candidate).engagement == merged.engagement
242
243
244 def test_day_only_and_legacy_repository_snapshots_remain_coherent():
245 legacy = _item("legacy", {"stars": 10, "open_issues": 8})
246 dated = _item("dated", {"stars": 0, "open_issues": 0})
247 dated.metadata = {"repo_counts_observed_on": "2026-11-03"}
248 for pair in ([legacy, dated], [dated, legacy]):
249 [merged] = dedupe.dedupe_items(pair)
250 assert merged.engagement == dated.engagement and merged.metadata == dated.metadata
251 dated.metadata.clear()
252 [merged] = dedupe.dedupe_items([dated, legacy])
253 assert merged.engagement == dated.engagement and not merged.metadata
254
255
256 def test_failed_enrichment_of_same_push_does_not_replace_measured_copy():
257 missing = _item("unmeasured", {})
258 observed = _item("measured", {"stars": 0, "open_issues": 0})
259 for item in (missing, observed):
260 item.metadata = {"labels": ["person-profile", "recent-push"]}
261 item.published_at = END
262 missing.body = missing.snippet = "Push with a long description and stars unavailable"
263 observed.body = observed.snippet = "Push with 0 stars"
264 observed.metadata["repo_counts_observed_at"] = "2026-10-25T18:00:00Z"
265 for pair in ([missing, observed], [observed, missing]):
266 [merged] = dedupe.dedupe_items(pair)
267 assert (merged.engagement, merged.metadata, merged.snippet) == (
268 observed.engagement, observed.metadata, observed.snippet,
269 )
270
271
272 def test_old_repository_counts_cannot_subtract_from_other_cards():
273 good = _item("one", {"stars": 2, "open_issues": 7})
274 bad = _item("two", {"stars": 2, "open_issues": -3}, "https://github.com/other/two")
275 for item in (good, bad):
276 item.metadata["labels"] = ["project-mode"]
277 payload = {
278 "topic": "projects", "range_from": START, "range_to": END, "generated_at": END,
279 "provider_runtime": {"reasoning_provider": "local", "planner_model": "fixture", "rerank_model": "fixture"},
280 "query_plan": {"intent": "product", "freshness_mode": "balanced_recent", "cluster_mode": "none", "raw_topic": "projects"},
281 "items_by_source": {"github": [schema.to_dict(good), schema.to_dict(bad)]},
282 }
283 report = schema.report_from_dict(payload)
284 [one, two] = report.items_by_source["github"]
285 assert one.engagement == good.engagement and two.engagement == {"stars": 2}
286 assert payload["items_by_source"]["github"][1]["engagement"]["open_issues"] == -3
287 [line] = render._build_source_footer_lines(report)
288 assert "7 open issues/PRs" in line and "open issues/PRs measured on 1 of 2 repository cards" in line
289 assert render._aggregate_engagement("github", [one, two]) == "4stars, 7open"
290
291
292 @pytest.mark.parametrize("invalid", [False, -1, 1.25, "NaN", "missing"])
293 def test_old_invalid_star_enrichments_preserve_measured_siblings(invalid):
294 payload = {"candidate_id": "C1", "item_id": "G1", "source": "reddit", "title": "Projects",
295 "metadata": {"github_stars": {"a/b": invalid, "c/d": 0, "e/f": 27}}}
296 cached = schema.candidate_from_dict(payload)
297 assert cached.metadata["github_stars"] == {"c/d": 0, "e/f": 27}
298 assert "a/b" in payload["metadata"]["github_stars"]
299 item = schema.to_dict(_item("G1", {"stars": invalid, "contributed_prs": 1}))
300 item["metadata"] = {"repo_counts_observed_on": END}
301 restored = schema.source_item_from_dict(item)
302 assert restored.engagement == {"contributed_prs": 1} and not schema.github_repo_count_time(restored)
303
304
305 def test_loading_older_whole_count_encodings_keeps_their_evidence():
306 raw = schema.to_dict(_item("G1", {"stars": "7.00", "open_issues": 0.0}))
307 raw["metadata"] = {"repo_counts_observed_on": END}
308 item = schema.source_item_from_dict(raw)
309 assert item.engagement == raw["engagement"] and schema.github_repo_count_time(item)
310 raw.update(source="reddit", engagement={"score": -3})
311 assert schema.source_item_from_dict(raw).engagement == {"score": -3}
312
313
314 def test_recorded_star_enrichment_accepts_saved_count_encodings_without_loosening_live_reads(monkeypatch):
315 candidate = SimpleNamespace(url="https://github.com/example/tool", title="Tool", metadata={})
316 stamp = "2026-11-22T12:00:00Z"
317 assert github.apply_star_map([candidate], {"example/tool": {"stars": "7.00", "observed_at": stamp}}) == 1
318 assert candidate.metadata["github_stars"]["example/tool"] == 7
319 assert candidate.metadata["github_stars_observed_at"]["example/tool"] == stamp
320 assert github.apply_star_map([candidate], {"example/tool": "0.0"}) == 1
321 assert candidate.metadata["github_stars"]["example/tool"] == 0
322 assert "example/tool" not in candidate.metadata["github_stars_observed_at"]
323
324 raw = {"visibility": "public", "stargazers_count": "7.00"}
325 assert "stars" not in github._repo_metadata(raw, stamp)
326 monkeypatch.setattr(github, "_resolve_token", lambda: None)
327 monkeypatch.setattr(github.http, "request", lambda *args, **kwargs: raw)
328 with pytest.raises(KeyError):
329 github.refetch_datum(None, "example/tool")
330
331
332 def test_footer_labels_each_counter_and_keeps_real_comments():
333 report = schema.Report(
334 topic="t", range_from=START, range_to=END, generated_at=f"{END}T12:00:00Z",
335 provider_runtime=schema.ProviderRuntime(
336 reasoning_provider="gemini", planner_model="m", rerank_model="m",
337 ),
338 query_plan=schema.QueryPlan(
339 intent="general", freshness_mode="balanced_recent", cluster_mode="story",
340 raw_topic="t", subqueries=[], source_weights={"github": 1.0},
341 ),
342 clusters=[], ranked_candidates=[], errors_by_source={},
343 items_by_source={"github": [
344 _item("repo", {"stars": 1200, "open_issues": 17}),
345 _item("profile", {"merged_prs": 3, "total_prs": 8}, "https://github.com/alice"),
346 _item("ext", {"stars": 5, "contributed_prs": 2}, "https://github.com/other/ext"),
347 _item("issue", {"comments": 9, "reactions": 4}, "https://github.com/alice/own/issues/1"),
348 ]},
349 )
350 assert render._build_source_footer_lines(report) == [
351 "🐙 GitHub: 4 items │ 1,205 stars │ 3 merged │ 4 reactions │ 17 open issues/PRs"
352 " │ 8 total PRs │ 2 contributed PRs │ 9 comments"
353 ]
354
355
356 def test_aggregate_stats_tell_total_and_contributed_prs_apart():
357 items = [
358 _item("profile", {"merged_prs": 3, "total_prs": 8}, "https://github.com/alice"),
359 _item("ext", {"stars": 5, "contributed_prs": 2}, "https://github.com/other/ext"),
360 ]
361 assert render._aggregate_engagement("github", items) == "5stars, 3merged, 8PRs, 2contrib"
362
362 lines PYTHON