返回 last30days-skill
test_bird_x.py
根目录 / tests / test_bird_x.py
1 import json
2 import os
3 import shutil
4 import subprocess
5 import textwrap
6 import unittest
7 from pathlib import Path
8 from unittest import mock
9
10 from lib import bird_x
11 from lib.bird_x import parse_bird_response
12
13 REPO_ROOT = Path(__file__).resolve().parents[1]
14 VENDORED_BIRD = REPO_ROOT / "skills" / "last30days" / "scripts" / "lib" / "vendor" / "bird-search" / "bird-search.mjs"
15
16
17 class TestSubprocessEnv(unittest.TestCase):
18 """_subprocess_env() passes only the vendored client's env surface (issue #1063)."""
19
20 def _ambient(self, **overrides):
21 base = {
22 "PATH": "/usr/bin:/bin",
23 "HOME": "/home/test",
24 "NODE_ENV": "production",
25 "AUTH_TOKEN": "ambient-token",
26 "CT0": "ambient-ct0",
27 "TWITTER_AUTH_TOKEN": "ambient-tw-token",
28 "TWITTER_CT0": "ambient-tw-ct0",
29 "LAST30DAYS_DISABLE_BROWSER_COOKIES": "0",
30 "BIRD_QUERY_IDS_CACHE": "/tmp/ids.json",
31 "SCRAPECREATORS_API_KEY": "sc-secret",
32 "AWS_SECRET_ACCESS_KEY": "aws-secret",
33 }
34 base.update(overrides)
35 return base
36
37 def _call(self, ambient, credentials=None):
38 from lib import bird_x
39 old = bird_x._credentials
40 try:
41 bird_x._credentials = dict(credentials or {})
42 # None means "absent" - os.environ cannot hold None values.
43 patch_env = {k: v for k, v in ambient.items() if v is not None}
44 with mock.patch.dict(os.environ, patch_env, clear=True):
45 return bird_x._subprocess_env()
46 finally:
47 bird_x._credentials = old
48
49 def test_unrelated_ambient_secrets_are_excluded(self):
50 out = self._call(self._ambient())
51 self.assertNotIn("SCRAPECREATORS_API_KEY", out)
52 self.assertNotIn("AWS_SECRET_ACCESS_KEY", out)
53
54 def test_runtime_and_client_vars_pass_through(self):
55 out = self._call(self._ambient())
56 self.assertEqual("/usr/bin:/bin", out.get("PATH"))
57 self.assertEqual("/home/test", out.get("HOME"))
58 self.assertEqual("production", out.get("NODE_ENV"))
59 self.assertEqual("ambient-token", out.get("AUTH_TOKEN"))
60 self.assertEqual("ambient-ct0", out.get("CT0"))
61 self.assertEqual("ambient-tw-token", out.get("TWITTER_AUTH_TOKEN"))
62 self.assertEqual("ambient-tw-ct0", out.get("TWITTER_CT0"))
63 self.assertEqual("0", out.get("LAST30DAYS_DISABLE_BROWSER_COOKIES"))
64 self.assertEqual("/tmp/ids.json", out.get("BIRD_QUERY_IDS_CACHE"))
65
66 def test_absent_vars_are_omitted(self):
67 out = self._call(self._ambient(NODE_ENV=None))
68 self.assertNotIn("NODE_ENV", out)
69 out = self._call(self._ambient(LAST30DAYS_DISABLE_BROWSER_COOKIES=None))
70 self.assertNotIn("LAST30DAYS_DISABLE_BROWSER_COOKIES", out)
71
72 def test_injected_credentials_override_ambient(self):
73 out = self._call(self._ambient(), credentials={"AUTH_TOKEN": "injected", "CT0": "injected-ct0"})
74 self.assertEqual("injected", out.get("AUTH_TOKEN"))
75 self.assertEqual("injected-ct0", out.get("CT0"))
76
77 def test_disable_flag_always_hard_set(self):
78 out = self._call(self._ambient(), credentials={"AUTH_TOKEN": "t", "CT0": "c"})
79 self.assertEqual("1", out.get("BIRD_DISABLE_BROWSER_COOKIES"))
80 # ambient 0 is overridden to 1
81 out = self._call(self._ambient(BIRD_DISABLE_BROWSER_COOKIES="0"))
82 self.assertEqual("1", out.get("BIRD_DISABLE_BROWSER_COOKIES"))
83
84 def test_ambient_bird_vars_pass_through(self):
85 out = self._call(self._ambient(BIRD_FEATURES_PATH="/tmp/features.json"))
86 self.assertEqual("/tmp/features.json", out.get("BIRD_FEATURES_PATH"))
87
88 def test_allowlist_covers_vendored_client_env_reads(self):
89 """Every process.env name the vendored client reads is reachable.
90
91 Guards the allowlist against vendor drift: a future bird-search bump
92 that reads a new non-BIRD_ env var must either be added to the
93 allowlist or fail here, keeping the child env surface explicit
94 (issue #1063).
95 """
96 import re
97
98 from lib import bird_x
99
100 vendor_dir = REPO_ROOT / "skills" / "last30days" / "scripts" / "lib" / "vendor" / "bird-search"
101 reads = set()
102 for path in list(vendor_dir.rglob("*.js")) + list(vendor_dir.rglob("*.mjs")):
103 text = path.read_text(encoding="utf-8")
104 for m in re.finditer(
105 r"process\.env\[\s*['\"]([A-Z0-9_]+)['\"]\s*\]|process\.env\.([A-Z0-9_]+)",
106 text,
107 ):
108 reads.add(m.group(1) or m.group(2))
109 # cookies.js reads via helpers with the keys passed as arguments:
110 # envFlagEnabled('NAME') and readEnvCookie(cookies, ['A', 'B'], ...).
111 for m in re.finditer(r"envFlagEnabled\(\s*['\"]([A-Z0-9_]+)['\"]\s*\)", text):
112 reads.add(m.group(1))
113 for m in re.finditer(r"readEnvCookie\(\s*\w+\s*,\s*\[([^\]]*)\]", text):
114 reads.update(re.findall(r"['\"]([A-Z0-9_]+)['\"]", m.group(1)))
115 self.assertTrue(reads, "vendored client env reads not found")
116 allowlist = set(bird_x._SUBPROCESS_ENV_ALLOWLIST)
117 uncovered = {
118 name for name in reads
119 if not name.startswith("BIRD_") and name not in allowlist
120 }
121 self.assertEqual(set(), uncovered)
122
123
124 class TestBirdXEngagementZero(unittest.TestCase):
125 def test_zero_likes_preserved(self):
126 tweets = [
127 {
128 "id": "1",
129 "text": "test",
130 "permanent_url": "https://x.com/u/status/1",
131 "likeCount": 0,
132 "retweetCount": 5,
133 }
134 ]
135 items = parse_bird_response(tweets, "test query")
136 self.assertEqual(0, items[0]["engagement"]["likes"])
137 self.assertEqual(5, items[0]["engagement"]["reposts"])
138
139 @unittest.skipUnless(shutil.which("node"), "node is required for vendored Bird tests")
140 class TestVendoredBirdRuntime(unittest.TestCase):
141 def test_check_uses_env_credentials_without_browser_cookie_dependency(self):
142 env = os.environ.copy()
143 env["AUTH_TOKEN"] = "dummy-auth"
144 env["CT0"] = "dummy-ct0"
145
146 result = subprocess.run(
147 ["node", str(VENDORED_BIRD), "--check"],
148 cwd=REPO_ROOT,
149 env=env,
150 capture_output=True,
151 text=True,
152 check=False,
153 )
154
155 self.assertEqual(0, result.returncode, result.stderr)
156 payload = json.loads(result.stdout)
157 self.assertTrue(payload["authenticated"])
158 self.assertEqual("env AUTH_TOKEN", payload["source"])
159
160 def test_check_with_browser_lookup_disabled_returns_json_warnings(self):
161 env = os.environ.copy()
162 env.pop("AUTH_TOKEN", None)
163 env.pop("CT0", None)
164 env["BIRD_DISABLE_BROWSER_COOKIES"] = "1"
165
166 result = subprocess.run(
167 ["node", str(VENDORED_BIRD), "--check"],
168 cwd=REPO_ROOT,
169 env=env,
170 capture_output=True,
171 text=True,
172 check=False,
173 )
174
175 self.assertEqual(1, result.returncode, result.stderr)
176 payload = json.loads(result.stdout)
177 self.assertFalse(payload["authenticated"])
178 self.assertTrue(payload["warnings"])
179 self.assertIn("Missing auth_token", " ".join(payload["warnings"]))
180
181 def _search_products(self, *flags):
182 """Run a search with fetch stubbed; return each SearchTimeline product."""
183 import tempfile
184 stub = textwrap.dedent("""
185 globalThis.fetch = async (url) => {
186 const u = String(url);
187 if (u.includes('SearchTimeline')) {
188 const v = JSON.parse(new URL(u).searchParams.get('variables'));
189 process.stderr.write(`PRODUCT=${v.product}\\n`);
190 const body = {data: {search_by_raw_query: {search_timeline: {timeline: {instructions: []}}}}};
191 return new Response(JSON.stringify(body), {status: 200, headers: {'content-type': 'application/json'}});
192 }
193 return new Response('', {status: 404});
194 };
195 """)
196 with tempfile.TemporaryDirectory() as tmp:
197 stub_path = Path(tmp) / "stub.mjs"
198 stub_path.write_text(stub)
199 env = os.environ.copy()
200 env.update(AUTH_TOKEN="dummy-auth", CT0="dummy-ct0", BIRD_DISABLE_BROWSER_COOKIES="1")
201 result = subprocess.run(
202 ["node", "--import", stub_path.as_uri(), str(VENDORED_BIRD), "q", "--count", "1", "--json", *flags],
203 cwd=REPO_ROOT, env=env, capture_output=True, text=True, check=False,
204 )
205 self.assertEqual(0, result.returncode, result.stderr)
206 return [line.split("=", 1)[1] for line in result.stderr.splitlines() if line.startswith("PRODUCT=")]
207
208 def test_search_requests_latest_by_default(self):
209 self.assertEqual(["Latest"], self._search_products())
210
211 def test_top_flag_requests_the_top_tab(self):
212 self.assertEqual(["Top"], self._search_products("--top"))
213
214 def test_browser_cookie_helpers_lazy_load_sweet_cookie(self):
215 sweet_cookie_dir = (
216 REPO_ROOT
217 / "skills"
218 / "last30days"
219 / "scripts"
220 / "lib"
221 / "vendor"
222 / "bird-search"
223 / "lib"
224 / "node_modules"
225 / "@steipete"
226 / "sweet-cookie"
227 )
228 if sweet_cookie_dir.exists():
229 self.skipTest("vendored sweet-cookie test stub already exists")
230
231 sweet_cookie_dir.mkdir(parents=True)
232 (sweet_cookie_dir / "package.json").write_text(
233 json.dumps(
234 {
235 "name": "@steipete/sweet-cookie",
236 "type": "module",
237 "exports": "./index.js",
238 }
239 ),
240 encoding="utf-8",
241 )
242 (sweet_cookie_dir / "index.js").write_text(
243 textwrap.dedent(
244 """
245 export async function getCookies(options) {
246 const browser = options.browsers?.[0] ?? "unknown";
247 return {
248 cookies: [
249 { name: "auth_token", value: `${browser}-auth`, domain: "x.com" },
250 { name: "ct0", value: `${browser}-ct0`, domain: "x.com" },
251 ],
252 warnings: [],
253 };
254 }
255 """
256 ),
257 encoding="utf-8",
258 )
259
260 try:
261 result = subprocess.run(
262 [
263 "node",
264 "--input-type=module",
265 "-e",
266 textwrap.dedent(
267 """
268 import {
269 extractCookiesFromSafari,
270 extractCookiesFromChrome,
271 extractCookiesFromFirefox,
272 } from "./skills/last30days/scripts/lib/vendor/bird-search/lib/cookies.js";
273
274 const payload = await Promise.all([
275 extractCookiesFromSafari(),
276 extractCookiesFromChrome("Profile 1"),
277 extractCookiesFromFirefox("default-release"),
278 ]);
279 process.stdout.write(JSON.stringify(payload));
280 """
281 ),
282 ],
283 cwd=REPO_ROOT,
284 capture_output=True,
285 text=True,
286 check=False,
287 )
288
289 self.assertEqual(0, result.returncode, result.stderr)
290 payload = json.loads(result.stdout)
291 self.assertEqual("Safari", payload[0]["cookies"]["source"])
292 self.assertEqual('Chrome profile "Profile 1"', payload[1]["cookies"]["source"])
293 self.assertEqual(
294 'Firefox profile "default-release"', payload[2]["cookies"]["source"]
295 )
296 self.assertEqual("safari-auth", payload[0]["cookies"]["authToken"])
297 self.assertEqual("chrome-auth", payload[1]["cookies"]["authToken"])
298 self.assertEqual("firefox-auth", payload[2]["cookies"]["authToken"])
299 finally:
300 shutil.rmtree(sweet_cookie_dir, ignore_errors=True)
301 for path in [sweet_cookie_dir.parent, sweet_cookie_dir.parent.parent]:
302 try:
303 path.rmdir()
304 except OSError:
305 pass
306
307 def test_none_likes_when_missing(self):
308 tweets = [
309 {
310 "id": "1",
311 "text": "test tweet with no engagement fields",
312 "permanent_url": "https://x.com/u/status/1",
313 # no likeCount, like_count, or favorite_count
314 }
315 ]
316 items = parse_bird_response(tweets, "test query")
317 self.assertIsNone(items[0]["engagement"])
318
319 def test_fallback_to_second_key(self):
320 tweets = [
321 {
322 "id": "1",
323 "text": "test",
324 "permanent_url": "https://x.com/u/status/1",
325 "like_count": 7,
326 }
327 ]
328 items = parse_bird_response(tweets, "test query")
329 self.assertEqual(7, items[0]["engagement"]["likes"])
330
331 def test_zero_does_not_fall_through(self):
332 """likeCount=0 should not fall through to like_count=10."""
333 tweets = [
334 {
335 "id": "1",
336 "text": "test",
337 "permanent_url": "https://x.com/u/status/1",
338 "likeCount": 0,
339 "like_count": 10,
340 }
341 ]
342 items = parse_bird_response(tweets, "test query")
343 self.assertEqual(0, items[0]["engagement"]["likes"])
344
345 def test_engagement_none_when_all_fields_missing(self):
346 """All-None engagement dict should become None, not propagate."""
347 tweets = [
348 {
349 "id": "1",
350 "text": "test",
351 "permanent_url": "https://x.com/u/status/1",
352 }
353 ]
354 items = parse_bird_response(tweets, "test query")
355 self.assertIsNone(items[0]["engagement"])
356
357 def test_engagement_preserved_when_any_field_present(self):
358 """Engagement dict kept when at least one metric exists."""
359 tweets = [
360 {
361 "id": "1",
362 "text": "test",
363 "permanent_url": "https://x.com/u/status/1",
364 "likeCount": 5,
365 }
366 ]
367 items = parse_bird_response(tweets, "test query")
368 self.assertIsNotNone(items[0]["engagement"])
369 self.assertEqual(5, items[0]["engagement"]["likes"])
370
371
372 class TestRunBirdSearchJsonDecodeRetry(unittest.TestCase):
373 """When bird-search returns non-JSON stdout, retry the subprocess.
374
375 Twitter's edge sometimes serves an HTML anti-bot interstitial in place of
376 JSON. Before this fix, that response made json.loads raise JSONDecodeError
377 and the function returned {"items": []} with no diagnostic — silent-empty
378 against an orchestrator that can't distinguish "Twitter blocked us" from
379 "no tweets matched the query."
380 """
381
382 def _make_result(self, stdout: str, stderr: str = "", returncode: int = 0):
383 from lib.subproc import SubprocResult
384 return SubprocResult(returncode=returncode, stdout=stdout, stderr=stderr)
385
386 def test_retries_subprocess_on_html_interstitial_then_succeeds(self):
387 """First subprocess attempt returns HTML; second returns JSON → success."""
388 from unittest import mock
389 from lib import bird_x
390
391 html_interstitial = "<!DOCTYPE html><html><body>Rate limited</body></html>"
392 json_success = '[{"id": "1", "text": "tweet"}]'
393
394 results = [
395 (self._make_result(stdout=html_interstitial), None),
396 (self._make_result(stdout=json_success), None),
397 ]
398
399 with mock.patch.object(bird_x, "_invoke_bird_subprocess", side_effect=results), \
400 mock.patch.object(bird_x.time, "sleep") as mock_sleep:
401 response = bird_x._run_bird_search("test", count=10, timeout=30)
402
403 self.assertNotIn("error", response)
404 self.assertEqual(response["items"], [{"id": "1", "text": "tweet"}])
405 # Should have slept between the failed first attempt and the retry.
406 mock_sleep.assert_called_once_with(bird_x.JSON_DECODE_RETRY_DELAY)
407
408 def test_returns_error_after_all_retries_exhausted(self):
409 """All attempts return HTML → error dict with diagnostic + items=[]."""
410 from unittest import mock
411 from lib import bird_x
412
413 html_interstitial = "<!DOCTYPE html><html>blocked</html>"
414 results = [
415 (self._make_result(stdout=html_interstitial), None),
416 (self._make_result(stdout=html_interstitial), None),
417 ]
418
419 with mock.patch.object(bird_x, "_invoke_bird_subprocess", side_effect=results), \
420 mock.patch.object(bird_x.time, "sleep"):
421 response = bird_x._run_bird_search("test", count=10, timeout=30)
422
423 self.assertIn("error", response)
424 self.assertIn("Invalid JSON response", response["error"])
425 # Diagnostic message names the anti-bot interstitial so it's
426 # distinguishable from a genuine no-results case in logs.
427 self.assertIn("anti-bot interstitial", response["error"].lower())
428 self.assertEqual(response["items"], [])
429
430 def test_terminal_subprocess_error_is_not_retried(self):
431 """Subprocess timeout / spawn failure → terminal error, no retry."""
432 from unittest import mock
433 from lib import bird_x
434
435 timeout_error = {"error": "Search timed out after 30s", "items": []}
436 results = [(None, timeout_error)]
437
438 with mock.patch.object(bird_x, "_invoke_bird_subprocess", side_effect=results), \
439 mock.patch.object(bird_x.time, "sleep") as mock_sleep:
440 response = bird_x._run_bird_search("test", count=10, timeout=30)
441
442 self.assertEqual(response, timeout_error)
443 mock_sleep.assert_not_called()
444
445 if __name__ == "__main__":
446 unittest.main()
447
448
449 class TestXFromAndAboutLanes(unittest.TestCase):
450 """U7/U8: FROM lane drops the topic-AND; ABOUT lane queries @handle and
451 excludes the handle's own tweets."""
452
453 def _result(self, body_items):
454 import json as _j
455 class _R:
456 returncode = 0
457 stderr = ""
458 r = _R()
459 r.stdout = _j.dumps({"items": body_items})
460 return r
461
462 def test_from_lane_drops_topic_and(self):
463 from unittest import mock
464 from lib import bird_x
465 captured = []
466
467 def fake_run(cmd, timeout=None, env=None, **_kwargs):
468 self.assertEqual("--", cmd[-2])
469 captured.append(cmd[-1]) # the query string arg after `--`
470 return self._result([])
471
472 with mock.patch.object(bird_x.subproc, "run_with_timeout", side_effect=fake_run):
473 bird_x.search_handles(["xuezhao"], "lan xuezhao", "2026-05-19", count_per=1)
474 self.assertEqual(captured[0], "from:xuezhao since:2026-05-19")
475 self.assertNotIn("lan xuezhao", captured[0])
476
477 def test_mention_lane_queries_at_handle(self):
478 from unittest import mock
479 from lib import bird_x
480 captured = []
481
482 def fake_run(cmd, timeout=None, env=None, **_kwargs):
483 self.assertEqual("--", cmd[-2])
484 captured.append(cmd[-1])
485 return self._result([])
486
487 with mock.patch.object(bird_x.subproc, "run_with_timeout", side_effect=fake_run):
488 bird_x.search_mentions(["xuezhao"], "2026-05-19", count_per=1)
489 self.assertEqual(captured[0], "@xuezhao since:2026-05-19")
490
491 def test_mention_lane_excludes_own_tweets(self):
492 from unittest import mock
493 from lib import bird_x
494 parsed = [
495 {"url": "https://x.com/xuezhao/status/1", "title": "own tweet"},
496 {"url": "https://twitter.com/xuezhao/status/3", "title": "own legacy-domain tweet"},
497 {"url": "https://x.com/fan99/status/2", "title": "mention of them"},
498 ]
499 with mock.patch.object(bird_x.subproc, "run_with_timeout",
500 return_value=self._result([{"id": "x"}])), \
501 mock.patch.object(bird_x, "parse_bird_response", return_value=parsed):
502 out = bird_x.search_mentions(["xuezhao"], "2026-05-19", count_per=5)
503 urls = [it["url"] for it in out]
504 self.assertNotIn("https://x.com/xuezhao/status/1", urls) # own (x.com) excluded
505 self.assertNotIn("https://twitter.com/xuezhao/status/3", urls) # own (twitter.com) excluded
506 self.assertIn("https://x.com/fan99/status/2", urls) # mention kept
507
508 def test_mention_lane_empty_when_no_mentions(self):
509 from unittest import mock
510 from lib import bird_x
511 with mock.patch.object(bird_x.subproc, "run_with_timeout",
512 return_value=self._result([])), \
513 mock.patch.object(bird_x, "parse_bird_response", return_value=[]):
514 out = bird_x.search_mentions(["xuezhao"], "2026-05-19")
515 self.assertEqual(out, [])
516 class TestProbeAndDiagnoseHonesty(unittest.TestCase):
517 """U5: --diagnose probe + true auth lane; X is not reported green when dead."""
518
519 def setUp(self):
520 from lib import bird_x
521 bird_x._probe_cache = "unset"
522 bird_x._credentials = {"AUTH_TOKEN": "t", "CT0": "c"} # injected creds present
523
524 def tearDown(self):
525 from lib import bird_x
526 bird_x._probe_cache = "unset"
527 bird_x._credentials = {}
528
529 def test_probe_true_when_response_ok(self):
530 from unittest import mock
531 from lib import bird_x
532 with mock.patch.object(bird_x, "_run_bird_search", return_value={"items": [{"id": "1"}]}):
533 self.assertTrue(bird_x.probe_works())
534
535 def test_probe_false_on_auth_error(self):
536 from unittest import mock
537 from lib import bird_x
538 with mock.patch.object(bird_x, "_run_bird_search",
539 return_value={"error": "Missing auth_token", "items": []}):
540 self.assertIs(bird_x.probe_works(), False)
541
542 def test_probe_none_on_timeout_inconclusive(self):
543 from unittest import mock
544 from lib import bird_x
545 with mock.patch.object(bird_x, "_run_bird_search",
546 return_value={"error": "Search timed out after 8s", "items": []}):
547 self.assertIsNone(bird_x.probe_works())
548
549 def test_probe_false_when_no_credentials(self):
550 from unittest import mock
551 from lib import bird_x
552 bird_x._credentials = {}
553 with mock.patch.dict(os.environ, {}, clear=True):
554 self.assertIs(bird_x.probe_works(), False)
555
556 def test_probe_cached_per_process(self):
557 from unittest import mock
558 from lib import bird_x
559 with mock.patch.object(bird_x, "_run_bird_search",
560 return_value={"items": [{"id": "1"}]}) as m:
561 bird_x.probe_works()
562 bird_x.probe_works()
563 self.assertEqual(m.call_count, 1) # cached, not re-run
564
565 def test_get_x_source_status_reports_true_lane(self):
566 from unittest import mock
567 from lib import env, bird_x
568 cfg = {"AUTH_TOKEN": "t", "CT0": "c", "_AUTH_TOKEN_SOURCE": "browser"}
569 with mock.patch.object(bird_x, "get_bird_status",
570 return_value={"installed": True, "authenticated": True,
571 "username": "env AUTH_TOKEN", "can_install": True}):
572 status = env.get_x_source_status(cfg, probe=False)
573 self.assertEqual(status["bird_username"], "browser AUTH_TOKEN")
574
575 def test_diagnose_probe_downgrades_when_dead(self):
576 from unittest import mock
577 from lib import env, bird_x
578 cfg = {"AUTH_TOKEN": "t", "CT0": "c", "_AUTH_TOKEN_SOURCE": "browser"}
579 with mock.patch.object(bird_x, "get_bird_status",
580 return_value={"installed": True, "authenticated": True,
581 "username": "env AUTH_TOKEN", "can_install": True}), \
582 mock.patch.object(bird_x, "probe_works", return_value=False):
583 status = env.get_x_source_status(cfg, probe=True)
584 self.assertFalse(status["bird_authenticated"])
585 self.assertIn("no working X auth", status["bird_username"])
586
587
588 class TestHandleSearchLogsOnSuccess(unittest.TestCase):
589 """U6: handle searches log query + count on success, not only on failure."""
590
591 def test_search_handles_logs_on_success(self):
592 from unittest import mock
593 from lib import bird_x
594
595 class _R:
596 returncode = 0
597 stdout = '{"items": [{"id": "1"}]}'
598 stderr = ""
599
600 logged = []
601 with mock.patch.object(bird_x.subproc, "run_with_timeout", return_value=_R()), \
602 mock.patch.object(bird_x, "_log", side_effect=lambda m: logged.append(m)):
603 bird_x.search_handles(["mvanhorn"], "matt van horn", "2026-05-19", count_per=1)
604 self.assertTrue(any("Searching:" in m for m in logged),
605 f"expected a Searching: log on success, got {logged}")
606
607
608 class TestTopicSearchReadsTopTab(unittest.TestCase):
609 """Topic searches read X's Top tab; handle and mention lanes keep Latest.
610
611 Latest is time-ordered, so on a busy topic ("taylor swift") its first page
612 is the last few minutes of zero-engagement posts, and handle expansion then
613 promoted whoever posted in those minutes.
614 """
615
616 def _result(self):
617 class _R:
618 returncode = 0
619 stderr = ""
620 stdout = json.dumps([])
621 return _R()
622
623 def test_every_topic_search_tier_asks_for_top(self):
624 tops = []
625
626 def fake_run(query, count, timeout, deadline=None, top=False):
627 tops.append(top)
628 return {"items": []} # 0 results forces every retry tier
629
630 with mock.patch.object(bird_x, "_run_bird_search", side_effect=fake_run):
631 bird_x.search_x("trevin chow ai agents compound", "2026-05-19", "2026-06-18")
632 self.assertGreater(len(tops), 1)
633 self.assertTrue(all(tops), tops)
634
635 def test_top_flag_reaches_the_bird_command_line(self):
636 cmds = []
637
638 def fake_run(cmd, timeout=None, env=None, **_kwargs):
639 cmds.append(cmd)
640 return self._result()
641
642 with mock.patch.object(bird_x.subproc, "run_with_timeout", side_effect=fake_run):
643 bird_x.search_x("taylor swift", "2026-10-16", "2026-11-15")
644 bird_x.search_handles(["taylorswift13"], "taylor swift", "2026-10-16", count_per=1)
645 bird_x.search_mentions(["taylorswift13"], "2026-10-16", count_per=1)
646 topic = [c for c in cmds if c[-1].startswith("taylor swift")]
647 lanes = [c for c in cmds if c[-1].startswith(("from:", "@"))]
648 self.assertTrue(topic and lanes)
649 self.assertTrue(all(c[-2] == "--" for c in cmds), cmds)
650 self.assertTrue(all("--top" in c[:c.index("--")] for c in topic), topic)
651 self.assertFalse(any("--top" in c[:c.index("--")] for c in lanes), lanes)
652
653
654 class TestStrongestTokenRetryAnchored(unittest.TestCase):
655 """The last-chance retry must keep an entity anchor, not collapse to a bare
656 generic token (e.g. 'compound') that floods the X pool with off-topic noise.
657 """
658
659 def test_last_chance_retry_keeps_entity_anchor(self):
660 from unittest import mock
661 from lib import bird_x
662
663 queries = []
664
665 def fake_run(query, count, timeout, deadline=None, top=False):
666 queries.append(query)
667 return {"items": []} # always 0 → forces every retry tier
668
669 # extract_compound_terms may run; let it. Force all bird calls empty.
670 with mock.patch.object(bird_x, "_run_bird_search", side_effect=fake_run):
671 bird_x.search_x("trevin chow ai agents compound", "2026-05-19", "2026-06-18")
672
673 self.assertTrue(queries, "expected at least one bird query")
674 last = queries[-1]
675 # The final (last-chance) query keeps the entity anchor ...
676 self.assertIn("trevin", last)
677 # ... and is NOT a bare generic token query.
678 self.assertFalse(last.startswith("compound "), f"bare generic retry: {last!r}")
679 self.assertNotEqual(last, "compound since:2026-05-19")
680
681 def test_retry_with_single_distinctive_token_no_crash(self):
682 from unittest import mock
683 from lib import bird_x
684
685 queries = []
686
687 def fake_run(query, count, timeout, deadline=None, top=False):
688 queries.append(query)
689 return {"items": []}
690
691 with mock.patch.object(bird_x, "_run_bird_search", side_effect=fake_run):
692 # 'trending tools' is all low-signal except nothing distinctive ->
693 # whatever survives, the retry must not crash and stays anchored.
694 bird_x.search_x("agentcookie", "2026-05-19", "2026-06-18")
695
696 self.assertTrue(queries)
697 self.assertIn("agentcookie", queries[-1])
698
699
700 class TestBirdRetryQueryCorrectness(unittest.TestCase):
701 def test_quoted_topic_only_generates_balanced_retry_queries(self):
702 from lib import bird_x
703
704 queries = []
705
706 def fake_run(query, count, timeout, deadline=None, top=False):
707 queries.append(query)
708 if len(queries) == 1:
709 return {"items": []}
710 return {"error": "Bird search failed", "items": []}
711
712 with mock.patch.object(
713 bird_x,
714 "_extract_core_subject",
715 return_value='immobilienmakler(berlin "mixed-use',
716 ), mock.patch(
717 "lib.query.extract_compound_terms",
718 return_value=['"immobilienmakler berlin"'],
719 ), mock.patch.object(bird_x, "_run_bird_search", side_effect=fake_run):
720 response = bird_x.search_x(
721 '"Immobilienmakler Berlin" competitors',
722 "2026-07-12",
723 "2026-07-19",
724 )
725
726 self.assertGreaterEqual(len(queries), 2)
727 self.assertEqual(
728 "immobilienmakler berlin mixed-use since:2026-07-12 until:2026-07-20",
729 queries[0],
730 )
731 for query in queries:
732 self.assertEqual(0, query.count('"') % 2, query)
733 self.assertEqual(query.count("("), query.count(")"), query)
734 self.assertNotIn("error", response)
735 self.assertEqual([], response["items"])
736
737 def test_every_failed_attempt_still_reports_backend_failure(self):
738 from lib import bird_x
739
740 with mock.patch.object(
741 bird_x, "_extract_core_subject", return_value="immobilienmakler berlin market"
742 ), mock.patch.object(
743 bird_x,
744 "_run_bird_search",
745 return_value={"error": "Bird search failed", "items": []},
746 ):
747 response = bird_x.search_x(
748 "Immobilienmakler Berlin market", "2026-07-12", "2026-07-19"
749 )
750
751 self.assertEqual("Bird search failed", response["error"])
752
753
754 class LeadingMentionsTests(unittest.TestCase):
755 """U5: leading @mentions parsed from post text identify reply targets."""
756
757 def test_single_leading_mention(self):
758 from lib import bird_x
759 self.assertEqual(["alpha"], bird_x._leading_mentions("@alpha thanks so much!"))
760
761 def test_multiple_leading_mentions(self):
762 from lib import bird_x
763 self.assertEqual(["alpha", "beta"], bird_x._leading_mentions("@alpha @beta hi"))
764
765 def test_in_body_mention_not_collected(self):
766 from lib import bird_x
767 self.assertEqual([], bird_x._leading_mentions("hello @gamma nice work"))
768
769 def test_punctuation_stripped(self):
770 from lib import bird_x
771 self.assertEqual(["alpha"], bird_x._leading_mentions("@alpha, nice"))
772
773 def test_empty_text(self):
774 from lib import bird_x
775 self.assertEqual([], bird_x._leading_mentions(""))
776 self.assertEqual([], bird_x._leading_mentions(None))
777
778
779 if __name__ == "__main__":
780 unittest.main()
781
782
783 class CredentialScrubInFailureDetailTests(unittest.TestCase):
784 """A handle-lane failure reason is recorded in the run's source_status and
785 rendered in the report, so subprocess stderr must not carry the X session
786 cookies into user-facing output."""
787
788 def tearDown(self):
789 bird_x._credentials.clear()
790
791 def test_injected_cookie_values_are_redacted_from_notes(self):
792 bird_x.set_credentials("auth-token-sentinel-value", "ct0-sentinel-value")
793 failures: list[str] = []
794 proc = mock.Mock(
795 returncode=1,
796 stdout="",
797 stderr="rejected cookie auth_token=auth-token-sentinel-value ct0=ct0-sentinel-value",
798 )
799 with mock.patch.object(bird_x.subproc, "run_with_timeout", return_value=proc):
800 bird_x.search_handles(
801 ["someone"], "topic", "2026-05-19", count_per=1,
802 failure_out=failures,
803 )
804 joined = " ".join(failures)
805 assert failures, "a non-zero exit must be reported"
806 self.assertNotIn("auth-token-sentinel-value", joined)
807 self.assertNotIn("ct0-sentinel-value", joined)
808 self.assertIn("<redacted>", joined)
809 # The actionable part of the reason survives.
810 self.assertIn("exited 1", joined)
811
812 def test_scrub_leaves_ordinary_stderr_intact(self):
813 bird_x.set_credentials("auth-token-sentinel-value", "ct0-sentinel-value")
814 self.assertEqual(
815 "connect ETIMEDOUT 104.244.42.1:443",
816 bird_x._scrub_credentials("connect ETIMEDOUT 104.244.42.1:443"),
817 )
818
818 lines PYTHON