返回 last30days-skill
test_github.py
根目录 / tests / test_github.py
1 """Tests for GitHub source module."""
2
3 import json
4 import unittest
5 import urllib.parse
6 from http.client import IncompleteRead
7 from io import BytesIO
8 from unittest.mock import patch, MagicMock
9
10 from lib import github
11
12
13 class TestResolveToken(unittest.TestCase):
14 def test_explicit_token(self):
15 self.assertEqual(github._resolve_token("my-token"), "my-token")
16
17 @patch.dict("os.environ", {"GITHUB_TOKEN": "env-token"})
18 def test_env_token(self):
19 self.assertEqual(github._resolve_token(), "env-token")
20
21 @patch.dict("os.environ", {}, clear=True)
22 @patch("subprocess.run")
23 def test_gh_cli_fallback(self, mock_run):
24 mock_run.return_value = MagicMock(returncode=0, stdout="gh-token\n")
25 # Clear GITHUB_TOKEN from env for this test
26 result = github._resolve_token()
27 self.assertEqual(result, "gh-token")
28
29 @patch.dict("os.environ", {}, clear=True)
30 @patch("subprocess.run", side_effect=FileNotFoundError)
31 def test_no_token_available(self, mock_run):
32 result = github._resolve_token()
33 self.assertIsNone(result)
34
35
36 class TestParseRepoFromUrl(unittest.TestCase):
37 def test_issue_url(self):
38 url = "https://github.com/facebook/react/issues/123"
39 self.assertEqual(github._parse_repo_from_url(url), "facebook/react")
40
41 def test_pr_url(self):
42 url = "https://github.com/vercel/next.js/pull/456"
43 self.assertEqual(github._parse_repo_from_url(url), "vercel/next.js")
44
45 def test_empty(self):
46 self.assertEqual(github._parse_repo_from_url(""), "")
47
48
49 class TestParseDate(unittest.TestCase):
50 def test_iso_date(self):
51 self.assertEqual(github._parse_date("2026-03-15T12:00:00Z"), "2026-03-15")
52
53 def test_none(self):
54 self.assertIsNone(github._parse_date(None))
55
56 def test_empty(self):
57 self.assertIsNone(github._parse_date(""))
58
59 def test_rejects_garbage(self):
60 """The old naive slicing returned 'hello worl' for 'hello world'. Reject it."""
61 self.assertIsNone(github._parse_date("hello world"))
62 self.assertIsNone(github._parse_date("not-a-date"))
63 self.assertIsNone(github._parse_date("abcdefghij"))
64
65 def test_rejects_invalid_date_values(self):
66 """An out-of-range date like 2026-99-99 is not a real date."""
67 self.assertIsNone(github._parse_date("2026-99-99"))
68
69 def test_iso_with_offset(self):
70 self.assertEqual(github._parse_date("2026-03-15T12:00:00+00:00"), "2026-03-15")
71
72 def test_iso_with_no_colon_offset(self):
73 self.assertEqual(github._parse_date("2026-03-15T12:00:00+0000"), "2026-03-15")
74
75
76 class TestSearchGithub(unittest.TestCase):
77 @patch.dict("os.environ", {}, clear=True)
78 @patch("subprocess.run", side_effect=FileNotFoundError)
79 @patch("lib.github._fetch_json", return_value=None)
80 def test_no_token_unauth_rate_limited_sets_error(self, mock_fetch, mock_run):
81 # No token -> unauthenticated request; on failure (likely anon rate
82 # limit) the envelope carries a clear error instead of being silent.
83 result = github.search_github("react", "2026-03-01", "2026-03-31", token=None)
84 self.assertEqual(result.get("items", []), [])
85 self.assertIn("error", result)
86 self.assertIn("unauthenticated", result["error"].lower())
87 self.assertIn("context", result)
88 self.assertEqual(result["context"]["from_date"], "2026-03-01")
89 # Unauth requests are capped to the low-rate tier.
90 self.assertLessEqual(result["context"]["count"], github.UNAUTH_COUNT_CAP)
91 # The request was actually attempted without a token (no early return).
92 mock_fetch.assert_called_once()
93 self.assertIsNone(mock_fetch.call_args.kwargs.get("token"))
94
95 @patch.dict("os.environ", {}, clear=True)
96 @patch("subprocess.run", side_effect=FileNotFoundError)
97 @patch("lib.github._fetch_json", return_value={"items": [{"id": 1, "title": "x"}]})
98 def test_no_token_unauth_success_returns_items(self, mock_fetch, mock_run):
99 result = github.search_github("react", "2026-03-01", "2026-03-31", token=None)
100 self.assertEqual(len(result["items"]), 1)
101 self.assertNotIn("error", result)
102
103 def test_resolve_token_public_alias(self):
104 """resolve_token is the public entry point pipeline uses; _resolve_token stays
105 private. Both should return the same value for the same input."""
106 self.assertEqual(
107 github.resolve_token("explicit-token"),
108 github._resolve_token("explicit-token"),
109 )
110 self.assertEqual(github.resolve_token("explicit-token"), "explicit-token")
111
112 @patch.object(github, "_fetch_json")
113 @patch.object(github, "_resolve_token", return_value="test-token")
114 def test_search_returns_raw_envelope(self, mock_token, mock_fetch):
115 mock_fetch.return_value = {
116 "total_count": 1,
117 "items": [
118 {
119 "html_url": "https://github.com/facebook/react/issues/42",
120 "title": "React Server Components bug",
121 "body": "There is a bug when using RSC with streaming...",
122 "created_at": "2026-03-15T10:00:00Z",
123 "state": "open",
124 "comments": 12,
125 "reactions": {"total_count": 8},
126 "labels": [{"name": "bug"}, {"name": "rsc"}],
127 "user": {"login": "testuser"},
128 },
129 ],
130 }
131 # Search returns raw envelope; parse normalizes.
132 response = github.search_github("react", "2026-03-01", "2026-03-31")
133 self.assertEqual(len(response["items"]), 1)
134 self.assertEqual(response["items"][0]["title"], "React Server Components bug")
135 self.assertEqual(response["context"]["from_date"], "2026-03-01")
136
137 items = github.parse_github_response(response)
138 self.assertEqual(len(items), 1)
139 item = items[0]
140 self.assertEqual(item["source"], "github")
141 self.assertEqual(item["container"], "facebook/react")
142 self.assertEqual(item["title"], "React Server Components bug")
143 self.assertEqual(item["date"], "2026-03-15")
144 self.assertEqual(item["author"], "testuser")
145 self.assertIn("bug", item["metadata"]["labels"])
146 self.assertEqual(item["metadata"]["state"], "open")
147 self.assertEqual(item["metadata"]["comment_count"], 12)
148 self.assertEqual(item["metadata"]["reactions"], 8)
149 self.assertEqual(item["engagement"]["reactions"], 8)
150 self.assertEqual(item["engagement"]["comments"], 12)
151 self.assertFalse(item["metadata"]["is_pr"])
152
153 @patch.object(github, "_fetch_json", return_value={"items": []})
154 @patch.object(github, "_resolve_token", return_value="test-token")
155 def test_search_is_bounded_by_window_end(self, mock_token, mock_fetch):
156 """An --as-of window must not fetch issues created after its end date."""
157 github.search_github("react", "2026-05-31", "2026-06-30")
158 self.assertTrue(mock_fetch.call_args_list)
159 for call in mock_fetch.call_args_list:
160 q = urllib.parse.parse_qs(urllib.parse.urlparse(call.args[0]).query)["q"][0]
161 self.assertIn("created:2026-05-31..2026-06-30", q)
162
163 @patch.object(github, "_fetch_json", return_value=None)
164 @patch.object(github, "_resolve_token", return_value="test-token")
165 def test_rate_limit_returns_empty_envelope(self, mock_token, mock_fetch):
166 """403 rate limit returns envelope with empty items list."""
167 response = github.search_github("react", "2026-03-01", "2026-03-31")
168 self.assertEqual(response["items"], [])
169 self.assertEqual(github.parse_github_response(response), [])
170
171 @patch.object(github, "_fetch_json")
172 @patch.object(github, "_resolve_token", return_value="test-token")
173 def test_pr_detected(self, mock_token, mock_fetch):
174 mock_fetch.return_value = {
175 "total_count": 1,
176 "items": [
177 {
178 "html_url": "https://github.com/vercel/next.js/pull/99",
179 "title": "Add streaming support",
180 "body": "This PR adds...",
181 "created_at": "2026-03-20T10:00:00Z",
182 "state": "open",
183 "comments": 5,
184 "reactions": {"total_count": 3},
185 "labels": [],
186 "user": {"login": "dev"},
187 "pull_request": {"url": "..."},
188 },
189 ],
190 }
191 response = github.search_github("next.js", "2026-03-01", "2026-03-31")
192 items = github.parse_github_response(response)
193 self.assertEqual(len(items), 1)
194 self.assertTrue(items[0]["metadata"]["is_pr"])
195
196
197 class TestParseGithubResponse(unittest.TestCase):
198 """Fixture-driven parse tests: feed a synthetic search_github envelope to
199 parse_github_response and assert normalized output.
200
201 This contract (search returns dict envelope, parse turns it into a list)
202 matches every other source adapter. Before this refactor, search_github
203 returned a bare list and there was no parse step, blocking fixture tests.
204 """
205
206 _RAW_ENVELOPE = {
207 "items": [
208 {
209 "html_url": "https://github.com/facebook/react/issues/42",
210 "title": "React Server Components bug",
211 "body": "There is a bug when using RSC with streaming...",
212 "created_at": "2026-03-15T10:00:00Z",
213 "state": "open",
214 "comments": 12,
215 "reactions": {"total_count": 8},
216 "labels": [{"name": "bug"}, {"name": "rsc"}],
217 "user": {"login": "testuser"},
218 },
219 {
220 "html_url": "https://github.com/vercel/next.js/pull/99",
221 "title": "Add React streaming support",
222 "body": "This PR adds...",
223 "created_at": "2026-03-20T10:00:00Z",
224 "state": "open",
225 "comments": 5,
226 "reactions": {"total_count": 3},
227 "labels": [],
228 "user": {"login": "dev"},
229 "pull_request": {"url": "..."},
230 },
231 ],
232 "context": {
233 "core": "react",
234 "from_date": "2026-03-01",
235 "to_date": "2026-03-31",
236 "count": 25,
237 },
238 }
239
240 def test_normalizes_items(self):
241 items = github.parse_github_response(self._RAW_ENVELOPE)
242 self.assertEqual(len(items), 2)
243 by_url = {i["url"]: i for i in items}
244 issue = by_url["https://github.com/facebook/react/issues/42"]
245 self.assertEqual(issue["source"], "github")
246 self.assertEqual(issue["container"], "facebook/react")
247 self.assertEqual(issue["title"], "React Server Components bug")
248 self.assertEqual(issue["date"], "2026-03-15")
249 self.assertEqual(issue["author"], "testuser")
250 self.assertEqual(issue["engagement"]["reactions"], 8)
251 self.assertEqual(issue["engagement"]["comments"], 12)
252 self.assertFalse(issue["metadata"]["is_pr"])
253
254 def test_detects_pr(self):
255 items = github.parse_github_response(self._RAW_ENVELOPE)
256 pr = next(i for i in items if "/pull/" in i["url"])
257 self.assertTrue(pr["metadata"]["is_pr"])
258
259 def test_date_filter_drops_outside_window(self):
260 envelope = {
261 "items": [
262 {
263 "html_url": "https://github.com/foo/bar/issues/1",
264 "title": "Too old",
265 "created_at": "2026-01-15T10:00:00Z",
266 "comments": 0, "reactions": {"total_count": 0},
267 "labels": [], "user": {"login": "x"},
268 },
269 {
270 "html_url": "https://github.com/foo/bar/issues/2",
271 "title": "In window",
272 "created_at": "2026-03-15T10:00:00Z",
273 "comments": 0, "reactions": {"total_count": 0},
274 "labels": [], "user": {"login": "x"},
275 },
276 ],
277 "context": {"core": "foo", "from_date": "2026-03-01",
278 "to_date": "2026-03-31", "count": 25},
279 }
280 items = github.parse_github_response(envelope)
281 self.assertEqual(len(items), 1)
282 self.assertEqual(items[0]["title"], "In window")
283
284 def test_sorts_by_relevance(self):
285 envelope = {
286 "items": [
287 {"html_url": "https://github.com/foo/bar/issues/1",
288 "title": "Unrelated work", "comments": 0,
289 "reactions": {"total_count": 0}},
290 {"html_url": "https://github.com/foo/bar/issues/2",
291 "title": "foo", "comments": 100,
292 "reactions": {"total_count": 500}},
293 ],
294 "context": {"core": "foo"},
295 }
296 items = github.parse_github_response(envelope)
297 self.assertEqual(
298 [item["url"] for item in items],
299 ["https://github.com/foo/bar/issues/2", "https://github.com/foo/bar/issues/1"],
300 )
301 scores = [i.get("relevance", 0) for i in items]
302 self.assertEqual(scores, sorted(scores, reverse=True))
303
304 def test_drops_results_that_do_not_name_the_topic(self):
305 envelope = {
306 "items": [
307 {"html_url": "https://github.com/vercel/next.js/pull/99",
308 "title": "Add streaming support", "comments": 5,
309 "reactions": {"total_count": 3}},
310 {"html_url": "https://github.com/vercel/next.js/pull/100",
311 "title": "Add React streaming support", "comments": 0,
312 "reactions": {"total_count": 0}},
313 ],
314 "context": {"core": "react"},
315 }
316 items = github.parse_github_response(envelope)
317 self.assertEqual(
318 [item["url"] for item in items],
319 ["https://github.com/vercel/next.js/pull/100"],
320 )
321
322 def test_empty_envelope(self):
323 self.assertEqual(github.parse_github_response({"items": []}), [])
324 self.assertEqual(github.parse_github_response({}), [])
325
326
327 class TestComputeRelevance(unittest.TestCase):
328 def test_basic_relevance(self):
329 score = github._compute_relevance("react hooks", "React Hooks Tutorial", 0, 10, 5)
330 self.assertGreater(score, 0.5)
331 self.assertLessEqual(score, 1.0)
332
333 def test_lower_rank_lower_score(self):
334 high = github._compute_relevance("react", "React", 0, 0, 0)
335 low = github._compute_relevance("react", "React", 20, 0, 0)
336 self.assertGreater(high, low)
337
338
339 class TestFetchItemComments(unittest.TestCase):
340 def test_bot_detection_uses_type_or_conventional_identity_suffix(self):
341 self.assertTrue(github._is_bot_user({"login": "release-helper", "type": "Bot"}))
342 self.assertTrue(github._is_bot_user({"login": "dependabot[bot]"}))
343 self.assertTrue(github._is_bot_user({"login": "actions", "name": "CI Helper [BOT]"}))
344 self.assertFalse(github._is_bot_user({"login": "robotics-team", "type": "User"}))
345 self.assertFalse(github._is_bot_user(None))
346 self.assertFalse(github._is_bot_user({}))
347
348 @patch.object(github, "_fetch_json")
349 def test_non_positive_limit_skips_request(self, mock_fetch):
350 self.assertEqual(
351 github._fetch_item_comments(
352 "https://github.com/example/project/issues/9",
353 max_comments=0,
354 ),
355 [],
356 )
357 mock_fetch.assert_not_called()
358
359 @patch.object(github, "_fetch_json")
360 def test_requests_largest_page_without_unsupported_sort(self, mock_fetch):
361 mock_fetch.return_value = []
362
363 github._fetch_item_comments(
364 "https://github.com/example/project/issues/9",
365 )
366
367 self.assertEqual(
368 mock_fetch.call_args.args[0],
369 "https://api.github.com/repos/example/project/issues/9/comments?per_page=100",
370 )
371 self.assertNotIn("sort=", mock_fetch.call_args.args[0])
372 self.assertNotIn("direction=", mock_fetch.call_args.args[0])
373 self.assertIsNone(mock_fetch.call_args.kwargs.get("token"))
374
375 @patch.object(github, "_fetch_json")
376 def test_filters_bots_and_stably_ranks_humans_by_reactions(self, mock_fetch):
377 mock_fetch.return_value = [
378 {
379 "body": "Early low-signal response",
380 "reactions": {"total_count": 5},
381 "user": {"login": "alice", "type": "User"},
382 },
383 {
384 "body": "Automated release summary",
385 "reactions": {"total_count": 100},
386 "user": {"login": "release-helper", "type": "Bot"},
387 },
388 {
389 "body": "Dependency update",
390 "reactions": {"total_count": 90},
391 "user": {"login": "dependabot[bot]"},
392 },
393 {
394 "body": "First tied human response",
395 "reactions": {"total_count": 21},
396 "user": {"login": "bruno", "type": "User"},
397 },
398 {
399 "body": "Workflow report",
400 "reactions": {"total_count": 80},
401 "user": {"login": "actions", "name": "CI Helper [BOT]"},
402 },
403 {
404 "body": "Highest-signal human response",
405 "reactions": {"total_count": 34},
406 "user": {"login": "carol"},
407 },
408 {
409 "body": "Second tied human response",
410 "reactions": {"total_count": 21},
411 "user": {"login": "dana"},
412 },
413 {
414 "body": "Deleted author's useful response",
415 "reactions": {"total_count": 13},
416 "user": None,
417 },
418 ]
419
420 comments = github._fetch_item_comments(
421 "https://github.com/example/project/issues/9",
422 max_comments=3,
423 )
424
425 self.assertEqual(
426 comments,
427 [
428 {
429 "score": 34,
430 "excerpt": "Highest-signal human response",
431 "author": "carol",
432 },
433 {
434 "score": 21,
435 "excerpt": "First tied human response",
436 "author": "bruno",
437 },
438 {
439 "score": 21,
440 "excerpt": "Second tied human response",
441 "author": "dana",
442 },
443 ],
444 )
445
446
447 class TestPersonPushEventsLane(unittest.TestCase):
448 """Person mode must not go dark when PR search returns nothing."""
449
450 @staticmethod
451 def _event(
452 event_id,
453 *,
454 actor="kurt",
455 repo="kurt/power-bi-agentic-development",
456 created_at="2026-07-22T20:28:18Z",
457 event_type="PushEvent",
458 ):
459 return {
460 "id": str(event_id),
461 "type": event_type,
462 "actor": {"login": actor},
463 "repo": {"name": repo},
464 "created_at": created_at,
465 }
466
467 def _run(self):
468 with patch.object(github, "_resolve_token", return_value="t"), \
469 patch.object(github, "_enrich_own_repo", return_value={}), \
470 patch.object(github, "_fetch_repo_info", return_value={
471 "stars": 811,
472 "forks": 119,
473 "description": "Claude Code plugin marketplace for Power BI",
474 "language": "Python",
475 "open_issues": 4,
476 }):
477 return github.search_github_person(
478 "kurt", "2026-06-25", "2026-07-25", token="t",
479 )
480
481 def test_unsearchable_account_falls_back_to_actor_push_events(self):
482 def fetch(url, **kwargs):
483 if "search/issues" in url:
484 return None
485 return [self._event(1)]
486
487 with patch.object(github, "_fetch_json", side_effect=fetch):
488 items = self._run()
489
490 self.assertEqual(len(items), 1)
491 self.assertEqual(items[0]["container"], "kurt/power-bi-agentic-development")
492 self.assertEqual(items[0]["date"], "2026-07-22")
493 self.assertIn("@kurt pushed", items[0]["title"])
494 self.assertIn("recent-push", items[0]["metadata"]["labels"])
495 self.assertEqual(items[0]["metadata"]["event_type"], "PushEvent")
496
497 def test_empty_pr_search_falls_back_to_actor_push_events(self):
498 def fetch(url, **kwargs):
499 if "search/issues" in url:
500 return {"total_count": 0, "items": []}
501 return [self._event(1, actor="KURT")]
502
503 with patch.object(github, "_fetch_json", side_effect=fetch):
504 items = self._run()
505
506 self.assertEqual(len(items), 1)
507 self.assertEqual(items[0]["author"], "KURT")
508
509 def test_other_actor_push_is_rejected(self):
510 def fetch(url, **kwargs):
511 if "search/issues" in url:
512 return {"total_count": 0, "items": []}
513 return [self._event(1, actor="collaborator")]
514
515 with patch.object(github, "_fetch_json", side_effect=fetch):
516 items = self._run()
517
518 self.assertEqual(items, [])
519
520 def test_discovers_push_on_second_events_page(self):
521 first_page = [
522 self._event(
523 i,
524 event_type="WatchEvent",
525 created_at=f"2026-07-{24 - (i // 25):02d}T12:00:00Z",
526 )
527 for i in range(github.PERSON_EVENTS_PER_PAGE)
528 ]
529 requested_urls = []
530
531 def fetch(url, **kwargs):
532 requested_urls.append(url)
533 if "search/issues" in url:
534 return {"total_count": 0, "items": []}
535 if "&page=1" in url:
536 return first_page
537 if "&page=2" in url:
538 return [self._event(101, repo="kurt/page-two")]
539 self.fail(f"Unexpected URL: {url}")
540
541 with patch.object(github, "_fetch_json", side_effect=fetch):
542 items = self._run()
543
544 self.assertEqual([item["container"] for item in items], ["kurt/page-two"])
545 self.assertTrue(any("&page=2" in url for url in requested_urls))
546
547 def test_requests_page_after_three_full_event_pages(self):
548 full_page = [
549 self._event(
550 i,
551 event_type="WatchEvent",
552 created_at="2026-07-24T12:00:00Z",
553 )
554 for i in range(github.PERSON_EVENTS_PER_PAGE)
555 ]
556 requested_pages = []
557
558 def fetch(url, **kwargs):
559 if "search/issues" in url:
560 return {"total_count": 0, "items": []}
561 page = int(url.rsplit("&page=", 1)[1])
562 requested_pages.append(page)
563 return full_page if page <= 3 else []
564
565 with patch.object(github, "_fetch_json", side_effect=fetch):
566 items = self._run()
567
568 self.assertEqual(items, [])
569 self.assertEqual(requested_pages, [1, 2, 3, 4])
570
571 def test_stops_paging_at_event_older_than_window(self):
572 requested_urls = []
573
574 def fetch(url, **kwargs):
575 requested_urls.append(url)
576 if "search/issues" in url:
577 return {"total_count": 0, "items": []}
578 if "&page=1" in url:
579 return [
580 self._event(1, event_type="WatchEvent"),
581 self._event(2, created_at="2026-06-24T23:59:59Z"),
582 ]
583 self.fail("Events paging continued after reaching an old event")
584
585 with patch.object(github, "_fetch_json", side_effect=fetch):
586 items = self._run()
587
588 self.assertEqual(items, [])
589 event_urls = [url for url in requested_urls if "/events/public" in url]
590 self.assertEqual(len(event_urls), 1)
591
592 def test_ranks_all_event_repos_before_applying_depth_cap(self):
593 events = [
594 self._event(1, repo="kurt/newest", created_at="2026-07-24T12:00:00Z"),
595 self._event(2, repo="kurt/recent", created_at="2026-07-23T12:00:00Z"),
596 self._event(3, repo="kurt/third", created_at="2026-07-22T12:00:00Z"),
597 self._event(4, repo="kurt/high-star", created_at="2026-07-21T12:00:00Z"),
598 ]
599 stars = {
600 "kurt/newest": 3,
601 "kurt/recent": 2,
602 "kurt/third": 1,
603 "kurt/high-star": 10_000,
604 }
605
606 def repo_info(repo, token):
607 return {
608 "stars": stars[repo],
609 "forks": 0,
610 "description": "",
611 "language": "Python",
612 "open_issues": 0,
613 }
614
615 with patch.object(github, "_fetch_json", return_value=events), \
616 patch.object(github, "_fetch_repo_info", side_effect=repo_info), \
617 patch.object(github, "_enrich_own_repo", return_value={}) as enrich:
618 items = github._person_recent_pushes(
619 "kurt",
620 "2026-06-25",
621 "2026-07-25",
622 {"own_repos": 3},
623 "t",
624 )
625
626 containers = [item["container"] for item in items]
627 self.assertIn("kurt/high-star", containers)
628 self.assertNotIn("kurt/third", containers)
629 self.assertEqual(enrich.call_count, 3)
630
631 def test_aggregates_each_repo_at_its_latest_matching_push(self):
632 events = [
633 self._event(2, created_at="2026-07-24T12:00:00Z"),
634 self._event(1, created_at="2026-07-20T12:00:00Z"),
635 ]
636
637 with patch.object(github, "_fetch_json", return_value=events), \
638 patch.object(github, "_fetch_repo_info", return_value={}), \
639 patch.object(github, "_enrich_own_repo", return_value={}):
640 items = github._person_recent_pushes(
641 "kurt",
642 "2026-06-25",
643 "2026-07-25",
644 {"own_repos": 5},
645 "t",
646 )
647
648 self.assertEqual(len(items), 1)
649 self.assertEqual(items[0]["date"], "2026-07-24")
650 self.assertEqual(items[0]["metadata"]["event_id"], "2")
651
652
653 class TestPersonVelocityWindow(unittest.TestCase):
654 """Person-mode PR counts must cover the requested window, not up to today."""
655
656 def _run(self, from_date, to_date, *, open_response=None):
657 queries = []
658
659 def fetch(url, **kwargs):
660 if "search/issues" in url:
661 query = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)["q"][0]
662 queries.append(query)
663 if query.endswith(" is:open"):
664 return open_response
665 count = 4 if query.endswith(" is:merged") else 10
666 return {"total_count": count, "items": []}
667 return []
668
669 with patch.object(github, "_resolve_token", return_value="t"), \
670 patch.object(github, "_fetch_json", side_effect=fetch):
671 items = github.search_github_person("kurt", from_date, to_date, token="t")
672 return queries, items
673
674 def test_pr_searches_end_at_window_end(self):
675 queries, _ = self._run("2026-05-31", "2026-06-30")
676
677 self.assertEqual(len(queries), 3)
678 for q in queries:
679 self.assertIn("created:2026-05-31..2026-06-30", q)
680 self.assertEqual(q.count("created:"), 1)
681
682 def test_velocity_label_uses_window_length(self):
683 _, items = self._run("2026-07-16", "2026-10-14")
684
685 self.assertIn("CONTRIBUTION VELOCITY (last 90 days)", items[0]["snippet"])
686
687 def test_open_pr_count_excludes_closed_unmerged_prs(self):
688 for count in (2, 0):
689 with self.subTest(open_prs=count):
690 _, items = self._run(
691 "2026-05-31", "2026-06-30",
692 open_response={"total_count": count, "incomplete_results": False},
693 )
694 self.assertIn(f"10 total PRs submitted, {count} still open", items[0]["snippet"])
695
696 def test_unavailable_open_pr_count_is_omitted(self):
697 responses = (None, {"total_count": 2, "incomplete_results": True}, {"total_count": 11})
698 for response in responses:
699 with self.subTest(response=response):
700 _, items = self._run("2026-05-31", "2026-06-30", open_response=response)
701 self.assertIn("10 total PRs submitted\n", items[0]["snippet"])
702 self.assertNotIn("still open", items[0]["snippet"])
703
704 def test_unreadable_open_pr_response_keeps_person_report(self):
705 def fetch(request, timeout):
706 parsed = urllib.parse.urlsplit(request.full_url)
707 if parsed.path == "/search/repositories":
708 return BytesIO(b'{"items":[]}')
709 self.assertEqual(parsed.path, "/search/issues")
710 query = urllib.parse.parse_qs(parsed.query)["q"][0]
711 if query.endswith(" is:open"):
712 return open_response
713 count = 4 if query.endswith(" is:merged") else 10
714 return BytesIO(json.dumps({"total_count": count, "items": []}).encode())
715
716 truncated = MagicMock()
717 truncated.__enter__.return_value.read.side_effect = IncompleteRead(b"", 1)
718 for case, open_response in (("truncated", truncated), ("invalid UTF-8", BytesIO(b"\xff"))):
719 with self.subTest(case=case), patch.object(github.http, "open_request", side_effect=fetch):
720 items = github.search_github_person("kurt", "2026-05-31", "2026-06-30", token="t")
721 self.assertIn("10 total PRs submitted\n", items[0]["snippet"])
722 self.assertNotIn("still open", items[0]["snippet"])
723
724
725
726 class TestStripSearchQualifiers(unittest.TestCase):
727 """Planner-injected GitHub search qualifiers must never reach the query
728 builder: search_github appends its own created:>{from_date}, and two
729 created: qualifiers collide (GitHub honors the first), which then makes
730 the local date filter drop everything (issue #949)."""
731
732 def test_strips_qualifiers_keeps_words(self):
733 self.assertEqual(
734 github.strip_search_qualifiers(
735 "open source ai stars:>1000 created:>2025-03-20"
736 ),
737 "open source ai",
738 )
739
740 def test_plain_word_is_not_a_qualifier_without_colon(self):
741 self.assertEqual(
742 github.strip_search_qualifiers("ai in healthcare"),
743 "ai in healthcare",
744 )
745
746 def test_qualifiers_removed_from_mixed_topic(self):
747 self.assertEqual(
748 github.strip_search_qualifiers("langchain is:issue created:>2026-01-01"),
749 "langchain",
750 )
751
752 def test_paren_wrapped_qualifier_stripped(self):
753 # Wrapper shapes bypassed the strip until the boundary accepted them
754 # (issue #952); a surviving created: would collide with the adapter's
755 # own window and silently zero out the source (issue #949 class).
756 self.assertEqual(
757 github.strip_search_qualifiers("(created:>2025-03-20)"),
758 "",
759 )
760
761 def test_double_quote_wrapped_qualifier_stripped(self):
762 self.assertEqual(
763 github.strip_search_qualifiers('"created:>2025-03-20"'),
764 "",
765 )
766
767 def test_single_quote_wrapped_qualifier_stripped(self):
768 self.assertEqual(
769 github.strip_search_qualifiers("'is:issue'"),
770 "",
771 )
772
773 def test_bracket_wrapped_qualifier_stripped(self):
774 self.assertEqual(
775 github.strip_search_qualifiers("[stars:>1000]"),
776 "",
777 )
778
779 def test_wrapped_qualifier_among_words_leaves_no_empty_pair(self):
780 self.assertEqual(
781 github.strip_search_qualifiers("ai (created:>2025-03-20) model"),
782 "ai model",
783 )
784
785 def test_quoted_value_and_wrapped_qualifier_both_stripped(self):
786 self.assertEqual(
787 github.strip_search_qualifiers('label:"bug fix" (created:>2025-03-20)'),
788 "",
789 )
790
791 def test_wrapped_and_plain_duplicate_qualifiers_both_stripped(self):
792 self.assertEqual(
793 github.strip_search_qualifiers("(created:>2025-03-20) created:>2026-01-01"),
794 "",
795 )
796
797 def test_nested_wrapper_collapses_to_fixpoint(self):
798 self.assertEqual(
799 github.strip_search_qualifiers("((created:>2025-03-20))"),
800 "",
801 )
802
803 def test_missing_closer_qualifier_still_stripped(self):
804 self.assertEqual(
805 github.strip_search_qualifiers("(created:>2025-03-20"), "",
806 )
807
808 def test_wrapper_cleanup_preserves_real_topic_text(self):
809 for topic, expected in [
810 ("ai (foo", "ai (foo"),
811 ("ai (foo created:>2025-03-20", "ai (foo"),
812 ("(foo) created:>2025-03-20", "(foo)"),
813 ('"quoted topic" created:>2025-03-20', '"quoted topic"'),
814 ("([foo created:>2025-03-20", "([foo"),
815 ("(", "("),
816 (")", ")"),
817 ]:
818 with self.subTest(topic=topic):
819 self.assertEqual(github.strip_search_qualifiers(topic), expected)
820
821 def test_quote_wrapped_with_space_inside_does_not_leak_qualifier(self):
822 # '"created:>2025-03-20 abc"' has a space in the quoted value, so it is
823 # not a single wrapper pair; the qualifier itself must still not reach
824 # the query.
825 result = github.strip_search_qualifiers('"created:>2025-03-20 abc"')
826 self.assertNotIn("created:", result)
827
828 def test_wrapped_qualifier_with_glued_term_preserves_term(self):
829 # Mirrors the plain glued-term case: "(created:>2025-03-20,robotics)"
830 # must strip the qualifier and keep the term, with no created: leak.
831 result = github.strip_search_qualifiers("(created:>2025-03-20,robotics)")
832 self.assertIn("robotics", result)
833 self.assertNotIn("created:", result)
834
835 def test_case_insensitive_qualifier_only_topic(self):
836 self.assertEqual(github.strip_search_qualifiers("Stars:>1000"), "")
837
838 def test_slash_containing_value_consumed(self):
839 self.assertEqual(
840 github.strip_search_qualifiers("repo:facebook/react bug"),
841 "bug",
842 )
843
844 def test_qualifier_glued_after_comma_is_stripped(self):
845 # A comma-glued qualifier (planner output like "ai,created:>2025-03-20")
846 # must not survive to collide with the adapter's own created: window.
847 self.assertEqual(
848 github.strip_search_qualifiers("ai,created:>2025-03-20"),
849 "ai,",
850 )
851
852 def test_qualifier_glued_after_semicolon_is_stripped(self):
853 self.assertEqual(
854 github.strip_search_qualifiers("ai;created:>2025-03-20"),
855 "ai;",
856 )
857
858 def test_quoted_qualifier_value_fully_consumed(self):
859 # label:"bug fix" spans a space; the whole quoted value must be
860 # consumed so no stray fragment (e.g. `fix"`) reaches the query.
861 self.assertEqual(
862 github.strip_search_qualifiers('label:"bug fix" open source'),
863 "open source",
864 )
865
866 def test_topic_term_glued_after_qualifier_value_is_preserved(self):
867 # A topic term glued after a qualifier value ("created:>2025-03-20,
868 # robotics") must survive stripping - the value class must stop at
869 # the separator instead of greedily eating the following term.
870 result = github.strip_search_qualifiers("created:>2025-03-20,robotics")
871 self.assertIn("robotics", result)
872 self.assertNotIn("created:", result)
873
874 def test_mid_topic_qualifier_with_glued_term_preserves_subject(self):
875 result = github.strip_search_qualifiers("ai created:>2025-03-20,robotics")
876 self.assertIn("robotics", result)
877 self.assertIn("ai", result)
878 self.assertNotIn("created:", result)
879
880
881 class TestSearchGithubQualifiers(unittest.TestCase):
882 """End-to-end behavior of search_github on qualifier-bearing topics."""
883
884 def _capturing_fetch(self, captured):
885 def fake_fetch(url, *args, **kwargs):
886 captured["url"] = url
887 captured.setdefault("urls", []).append(url)
888 return {"total_count": 0, "items": []}
889 return fake_fetch
890
891 def _query(self, captured_url):
892 return urllib.parse.parse_qs(
893 urllib.parse.urlparse(captured_url).query
894 )["q"][0]
895
896 @patch.object(github, "_resolve_token", return_value="test-token")
897 def test_planner_qualifiers_stripped_before_query_build(self, mock_token):
898 captured = {}
899 with patch.object(github, "_fetch_json", side_effect=self._capturing_fetch(captured)):
900 github.search_github(
901 "open source ai stars:>1000 created:>2025-03-20",
902 "2026-07-01", "2026-07-31",
903 )
904 queries = [self._query(u) for u in captured["urls"]]
905 # Authenticated searches must carry `is:issue` or `is:pull-request`
906 # (GitHub 422s without one), so the subject is asserted per sub-query
907 # rather than against a single exact string.
908 self.assertEqual(len(queries), 2)
909 for q in queries:
910 self.assertTrue(q.startswith("is:public open source ai created:2026-07-01..2026-07-31"))
911 self.assertEqual(q.count("created:"), 1)
912 self.assertNotIn("stars:", q)
913 self.assertEqual(
914 {q.rsplit(" ", 1)[-1] for q in queries},
915 {"is:issue", "is:pull-request"},
916 )
917
918 @patch.object(github, "_resolve_token", return_value="test-token")
919 def test_authenticated_search_merges_issues_and_pull_requests(self, mock_token):
920 """Both qualifier queries run, and their results are deduped and
921 re-sorted by reactions — a plain concatenation would let the second
922 query's tail outrank the first query's head."""
923 issue = {"id": 1, "reactions": {"total_count": 5}}
924 pull = {"id": 2, "reactions": {"total_count": 9}}
925 also_issue = {"id": 1, "reactions": {"total_count": 5}} # cross-query dupe
926
927 def fake_fetch(url, *args, **kwargs):
928 q = self._query(url)
929 if "is:issue" in q:
930 return {"items": [issue]}
931 return {"items": [pull, also_issue]}
932
933 with patch.object(github, "_fetch_json", side_effect=fake_fetch):
934 envelope = github.search_github("topic", "2026-07-01", "2026-07-31")
935
936 ids = [item["id"] for item in envelope["items"]]
937 self.assertEqual(ids, [2, 1], "expected reaction-sorted, deduped merge")
938
939 @patch.object(github, "_resolve_token", return_value="test-token")
940 def test_authenticated_search_one_partition_fails_keeps_items_and_reports_error(self, mock_token):
941 """If one authenticated partition fails (returns None) and the other
942 returns items, the surviving items are kept but the envelope carries
943 an error so the source is not marked as a clean success."""
944 issue = {"id": 1, "reactions": {"total_count": 5}}
945
946 def fake_fetch(url, *args, **kwargs):
947 q = self._query(url)
948 if "is:issue" in q:
949 return {"items": [issue]}
950 return None # PR partition failed
951
952 with patch.object(github, "_fetch_json", side_effect=fake_fetch):
953 envelope = github.search_github("topic", "2026-07-01", "2026-07-31")
954
955 self.assertEqual(len(envelope["items"]), 1)
956 self.assertEqual(envelope["items"][0]["id"], 1)
957 self.assertIn("error", envelope)
958 self.assertIn("is:pull-request", envelope["error"])
959 self.assertIn("partition", envelope["error"].lower())
960
961 @patch.object(github, "_resolve_token", return_value="test-token")
962 def test_authenticated_search_both_partitions_fail_is_full_failure(self, mock_token):
963 """If both authenticated partitions fail (return None), the envelope
964 has empty items and carries an error indicating complete failure."""
965
966 with patch.object(github, "_fetch_json", return_value=None):
967 envelope = github.search_github("topic", "2026-07-01", "2026-07-31")
968
969 self.assertEqual(envelope["items"], [])
970 self.assertIn("error", envelope)
971 self.assertIn("GitHub", envelope["error"])
972
973 @patch.object(github, "_resolve_token", return_value=None)
974 def test_unauthenticated_search_omits_qualifier(self, mock_token):
975 """Anonymous /search/issues is still grandfathered without a
976 qualifier, so the single-query path must stay qualifier-free."""
977 captured = {}
978 with patch.object(github, "_fetch_json", side_effect=self._capturing_fetch(captured)):
979 github.search_github("open source ai", "2026-07-01", "2026-07-31")
980 self.assertEqual(len(captured["urls"]), 1)
981 q = self._query(captured["urls"][0])
982 self.assertNotIn("is:issue", q)
983 self.assertNotIn("is:pull-request", q)
984
985 @patch.object(github, "_resolve_token", return_value="test-token")
986 def test_qualifier_only_topic_skips_network(self, mock_token):
987 with patch.object(github, "_fetch_json") as mock_fetch:
988 result = github.search_github(
989 "created:>2025-03-20", "2026-07-01", "2026-07-31",
990 )
991 mock_fetch.assert_not_called()
992 self.assertEqual(result["items"], [])
993 self.assertNotIn("error", result)
994 self.assertEqual(result["context"]["from_date"], "2026-07-01")
995
996 @patch.object(github, "_resolve_token", return_value="test-token")
997 def test_qualifier_key_word_without_colon_survives(self, mock_token):
998 captured = {}
999 with patch.object(github, "_fetch_json", side_effect=self._capturing_fetch(captured)):
1000 github.search_github(
1001 "state of the art ai", "2026-07-01", "2026-07-31",
1002 )
1003 q = self._query(captured["url"])
1004 # `state` is a GitHub qualifier key but appears here without a colon;
1005 # it must survive extract_core_subject + the qualifier strip.
1006 self.assertIn("state", q)
1007 self.assertEqual(q.count("created:"), 1)
1008
1009
1010
1011 @patch.object(github, "_resolve_token", return_value="test-token")
1012 def test_comma_glued_qualifier_builds_single_created_query(self, mock_token):
1013 captured = {}
1014 with patch.object(github, "_fetch_json", side_effect=self._capturing_fetch(captured)):
1015 github.search_github(
1016 "ai,created:>2025-03-20", "2026-07-01", "2026-07-31",
1017 )
1018 q = self._query(captured["url"])
1019 self.assertEqual(q.count("created:"), 1)
1020 self.assertIn("created:2026-07-01..2026-07-31", q)
1021 self.assertNotIn("created:>2025-03-20", q)
1022
1023 @patch.object(github, "_resolve_token", return_value="test-token")
1024 def test_empty_topic_skips_network(self, mock_token):
1025 with patch.object(github, "_fetch_json") as mock_fetch:
1026 result = github.search_github("", "2026-07-01", "2026-07-31")
1027 mock_fetch.assert_not_called()
1028 self.assertEqual(result["items"], [])
1029 self.assertNotIn("error", result)
1030
1031 @patch.object(github, "_resolve_token", return_value="test-token")
1032 def test_glued_term_after_qualifier_value_reaches_query(self, mock_token):
1033 captured = {}
1034 with patch.object(github, "_fetch_json", side_effect=self._capturing_fetch(captured)):
1035 github.search_github(
1036 "ai created:>2025-03-20,robotics", "2026-07-01", "2026-07-31",
1037 )
1038 q = self._query(captured["url"])
1039 self.assertIn("robotics", q)
1040 self.assertIn("ai", q)
1041 self.assertEqual(q.count("created:"), 1)
1042
1043 @patch.object(github, "_resolve_token", return_value="test-token")
1044 def test_paren_wrapped_qualifier_builds_single_created_query(self, mock_token):
1045 # Wrapped qualifier (issue #952) must not survive into the query to
1046 # collide with the adapter's own created: window (issue #949 class).
1047 # Authenticated search emits is:issue / is:pull-request partitions
1048 # (GitHub 422s without one); assert the subject per sub-query.
1049 captured = {}
1050 with patch.object(github, "_fetch_json", side_effect=self._capturing_fetch(captured)):
1051 github.search_github(
1052 "open source ai (created:>2025-03-20)", "2026-07-01", "2026-07-31",
1053 )
1054 queries = [self._query(u) for u in captured["urls"]]
1055 self.assertEqual(len(queries), 2)
1056 for q in queries:
1057 self.assertTrue(q.startswith("is:public open source ai created:2026-07-01..2026-07-31"))
1058 self.assertEqual(q.count("created:"), 1)
1059 self.assertIn("created:2026-07-01..2026-07-31", q)
1060 self.assertNotIn("created:>2025-03-20", q)
1061 self.assertIn("open source", q)
1062 self.assertIn("ai", q)
1063 self.assertEqual(
1064 {q.rsplit(" ", 1)[-1] for q in queries},
1065 {"is:issue", "is:pull-request"},
1066 )
1067
1068 @patch.object(github, "_resolve_token", return_value="test-token")
1069 def test_quote_wrapped_qualifier_only_topic_skips_network(self, mock_token):
1070 # A quote-wrapped qualifier-only topic strips to nothing, so the
1071 # adapter must skip the network (#949/#952) and return a clean
1072 # no-results envelope rather than ERROR (#953).
1073 with patch.object(github, "_fetch_json") as mock_fetch:
1074 result = github.search_github(
1075 '"created:>2025-03-20"', "2026-07-01", "2026-07-31",
1076 )
1077 mock_fetch.assert_not_called()
1078 self.assertEqual(result["items"], [])
1079 self.assertNotIn("error", result)
1080
1081
1082 if __name__ == "__main__":
1083 unittest.main()
1084
1085
1086 def test_snapshot_date_uses_in_window_release_else_window_end():
1087 from lib import github
1088
1089 window = ("2026-09-11", "2026-10-11")
1090 assert github._snapshot_date([{"date": "2026-10-05"}], *window) == "2026-10-05"
1091 assert github._snapshot_date([{"date": "2022-11-17"}], *window) == "2026-10-11"
1092 assert github._snapshot_date([], *window) == "2026-10-11"
1093 assert github._snapshot_date([{"date": None}], *window) == "2026-10-11"
1094
1095
1096 def _project_mode_items(release_date):
1097 from lib import github
1098
1099 enrichment = {
1100 "info": {"stars": 40000, "open_issues": 900, "description": "A terminal", "language": "Zig"},
1101 "readme": "Ghostty terminal",
1102 "releases": [{"name": "tip", "date": release_date, "body": ""}],
1103 "top_issues": {},
1104 }
1105 with patch.object(github, "_resolve_token", return_value="t"), \
1106 patch.object(github, "_enrich_project_repo", return_value=enrichment):
1107 return github.search_github_project(
1108 ["ghostty-org/ghostty"], "2026-09-11", "2026-10-11",
1109 )
1110
1111
1112 def test_snapshot_repo_gets_neutral_freshness_not_window_end_boost():
1113 # A pinned repo whose newest release predates the window is dated to_date
1114 # so the date filter keeps it. That date is a read time, not an event: it
1115 # must rank on neutral freshness, not pin to #1 on maximum freshness.
1116 from lib import normalize, signals
1117
1118 window = ("2026-09-11", "2026-10-11")
1119 raw = _project_mode_items("2022-11-17") + [{
1120 "id": "GH9",
1121 "title": "ghostty-org/ghostty issue",
1122 "url": "https://github.com/ghostty-org/ghostty/issues/1",
1123 "date": "2026-09-26",
1124 "source": "github",
1125 "relevance": 0.9,
1126 "metadata": {"labels": ["project-mode"], "state": "open"},
1127 }]
1128 items = normalize.normalize_source_items("github", raw, *window)
1129 assert len(items) == 2 # the date filter still keeps the snapshot
1130 ranked = signals.annotate_stream(items, "ghostty", "balanced_recent", reference_date=window[1])
1131 by_id = {item.item_id: item for item in ranked}
1132 snapshot, mid = by_id["GH1"], by_id["GH9"]
1133 assert snapshot.local_relevance == mid.local_relevance
1134 assert snapshot.freshness == 50
1135 assert snapshot.freshness <= mid.freshness # mid-window scores the 50 midpoint
1136 assert snapshot.local_rank_score <= mid.local_rank_score + 0.10 # engagement only
1137
1138
1139 def test_in_window_release_keeps_normal_freshness():
1140 from lib import normalize, signals
1141
1142 window = ("2026-09-11", "2026-10-11")
1143 items = normalize.normalize_source_items("github", _project_mode_items("2026-10-09"), *window)
1144 item = signals.annotate_stream(items, "ghostty", "balanced_recent", reference_date=window[1])[0]
1145 assert item.published_at == "2026-10-09"
1146 assert item.freshness > 80
1147
1147 lines PYTHON