返回 last30days-skill
test_xquik.py
根目录 / tests / test_xquik.py
1 import unittest
2 from unittest.mock import patch
3 from urllib.parse import parse_qs, urlsplit
4
5 from lib import health
6 from lib.xquik import (
7 DEPTH_CONFIG,
8 _parse_tweet,
9 _safe_int,
10 expand_xquik_queries,
11 parse_xquik_response,
12 search_xquik,
13 )
14
15
16 class TestExpandXquikQueries(unittest.TestCase):
17 def test_quick_returns_one_query(self):
18 queries = expand_xquik_queries("latest trends in AI agents", "quick")
19 self.assertEqual(len(queries), 1)
20
21 def test_default_returns_up_to_two_queries(self):
22 queries = expand_xquik_queries("multi-agent systems research", "default")
23 self.assertLessEqual(len(queries), 2)
24 self.assertGreaterEqual(len(queries), 1)
25
26 def test_deep_returns_up_to_three_queries(self):
27 queries = expand_xquik_queries("best AI coding assistants 2026", "deep")
28 self.assertLessEqual(len(queries), 3)
29 self.assertGreaterEqual(len(queries), 1)
30
31 def test_single_word_topic(self):
32 queries = expand_xquik_queries("Bitcoin", "quick")
33 self.assertEqual(len(queries), 1)
34 self.assertIn("bitcoin", queries[0].lower())
35
36
37 class TestParseTweet(unittest.TestCase):
38 def test_valid_tweet(self):
39 tweet = {
40 "id": "123456",
41 "text": "This is a test tweet about AI agents",
42 "createdAt": "2026-03-15T12:00:00Z",
43 "likeCount": 42,
44 "retweetCount": 10,
45 "replyCount": 5,
46 "quoteCount": 2,
47 "viewCount": 5000,
48 "bookmarkCount": 8,
49 "author": {"username": "testuser", "name": "Test User"},
50 }
51 item = _parse_tweet(tweet, 0, "AI agents")
52 self.assertIsNotNone(item)
53 self.assertEqual(item["id"], "XQ1")
54 self.assertEqual(item["url"], "https://x.com/testuser/status/123456")
55 self.assertEqual(item["author_handle"], "testuser")
56 self.assertEqual(item["date"], "2026-03-15")
57 self.assertEqual(item["engagement"]["likes"], 42)
58 self.assertEqual(item["engagement"]["reposts"], 10)
59 self.assertEqual(item["engagement"]["replies"], 5)
60 self.assertEqual(item["engagement"]["quotes"], 2)
61 self.assertEqual(item["engagement"]["views"], 5000)
62 self.assertEqual(item["engagement"]["bookmarks"], 8)
63 self.assertGreater(item["relevance"], 0)
64
65 def test_missing_author_returns_none(self):
66 tweet = {"id": "123", "text": "test"}
67 item = _parse_tweet(tweet, 0, "test")
68 self.assertIsNone(item)
69
70 def test_at_prefix_stripped(self):
71 tweet = {
72 "id": "456",
73 "text": "hello",
74 "author": {"username": "@someone"},
75 }
76 item = _parse_tweet(tweet, 0, "hello")
77 self.assertIsNotNone(item)
78 self.assertEqual(item["author_handle"], "someone")
79
80 def test_zero_engagement_preserved(self):
81 tweet = {
82 "id": "789",
83 "text": "zero likes tweet",
84 "author": {"username": "user"},
85 "likeCount": 0,
86 "retweetCount": 0,
87 "replyCount": 0,
88 "quoteCount": 0,
89 "viewCount": 0,
90 "bookmarkCount": 0,
91 }
92 item = _parse_tweet(tweet, 0, "test")
93 self.assertIsNotNone(item)
94 self.assertEqual(item["engagement"]["likes"], 0)
95 self.assertEqual(item["engagement"]["reposts"], 0)
96 self.assertEqual(item["engagement"]["views"], 0)
97
98 def test_none_engagement_values(self):
99 tweet = {
100 "id": "101",
101 "text": "minimal tweet",
102 "author": {"username": "user"},
103 }
104 item = _parse_tweet(tweet, 0, "test")
105 self.assertIsNotNone(item)
106 self.assertIsNone(item["engagement"]["likes"])
107 self.assertIsNone(item["engagement"]["views"])
108
109 def test_text_truncated_at_500(self):
110 tweet = {
111 "id": "102",
112 "text": "x" * 600,
113 "author": {"username": "user"},
114 }
115 item = _parse_tweet(tweet, 0, "test")
116 self.assertIsNotNone(item)
117 self.assertEqual(len(item["text"]), 500)
118
119 def test_twitter_date_format(self):
120 tweet = {
121 "id": "103",
122 "text": "old format",
123 "createdAt": "Wed Jan 15 14:30:00 +0000 2026",
124 "author": {"username": "user"},
125 }
126 item = _parse_tweet(tweet, 0, "test")
127 self.assertIsNotNone(item)
128 self.assertEqual(item["date"], "2026-01-15")
129
130 def test_invalid_date_graceful(self):
131 tweet = {
132 "id": "104",
133 "text": "bad date",
134 "createdAt": "not-a-date",
135 "author": {"username": "user"},
136 }
137 item = _parse_tweet(tweet, 0, "test")
138 self.assertIsNotNone(item)
139 self.assertIsNone(item["date"])
140
141 def test_empty_author_dict(self):
142 tweet = {"id": "105", "text": "test", "author": {}}
143 item = _parse_tweet(tweet, 0, "test")
144 self.assertIsNone(item)
145
146 def test_index_offset(self):
147 tweet = {
148 "id": "106",
149 "text": "test",
150 "author": {"username": "user"},
151 }
152 item = _parse_tweet(tweet, 4, "test")
153 self.assertIsNotNone(item)
154 self.assertEqual(item["id"], "XQ5")
155
156
157 class TestSafeInt(unittest.TestCase):
158 def test_int_passthrough(self):
159 self.assertEqual(_safe_int(42), 42)
160
161 def test_string_int(self):
162 self.assertEqual(_safe_int("100"), 100)
163
164 def test_none_returns_none(self):
165 self.assertIsNone(_safe_int(None))
166
167 def test_invalid_string(self):
168 self.assertIsNone(_safe_int("abc"))
169
170 def test_zero(self):
171 self.assertEqual(_safe_int(0), 0)
172
173 def test_float_truncates(self):
174 self.assertEqual(_safe_int(3.7), 3)
175
176
177 class TestParseXquikResponse(unittest.TestCase):
178 def test_extracts_items(self):
179 response = {"items": [{"id": "1"}, {"id": "2"}]}
180 items = parse_xquik_response(response)
181 self.assertEqual(len(items), 2)
182
183 def test_empty_response(self):
184 self.assertEqual(parse_xquik_response({}), [])
185
186 def test_error_response(self):
187 response = {"items": [], "error": "something went wrong"}
188 self.assertEqual(parse_xquik_response(response), [])
189
190
191 class TestSearchXquik(unittest.TestCase):
192 def test_no_token_returns_error(self):
193 result = search_xquik("test", "2026-01-01", "2026-03-01", token="")
194 self.assertEqual(result["items"], [])
195 self.assertIn("XQUIK_API_KEY", result["error"])
196
197 @patch("lib.xquik.http.get")
198 def test_successful_search(self, mock_get):
199 mock_get.return_value = {
200 "tweets": [
201 {
202 "id": "111",
203 "text": "AI agents are amazing",
204 "createdAt": "2026-02-15T10:00:00Z",
205 "likeCount": 50,
206 "retweetCount": 12,
207 "replyCount": 3,
208 "quoteCount": 1,
209 "viewCount": 2000,
210 "bookmarkCount": 5,
211 "author": {"username": "aidev"},
212 },
213 ],
214 "has_next_page": False,
215 }
216 result = search_xquik("AI agents", "2026-02-01", "2026-03-01", token="test-key")
217 self.assertEqual(len(result["items"]), 1)
218 self.assertEqual(result["items"][0]["author_handle"], "aidev")
219 self.assertEqual(result["items"][0]["engagement"]["likes"], 50)
220 self.assertNotIn("error", result)
221
222 @patch("lib.xquik.http.get")
223 def test_deduplicates_across_queries(self, mock_get):
224 tweet = {
225 "id": "222",
226 "text": "duplicate tweet",
227 "author": {"username": "user"},
228 }
229 distinct = {
230 "id": "333",
231 "text": "another relevant post",
232 "author": {"username": "other"},
233 }
234 mock_get.side_effect = [
235 {"tweets": [tweet]},
236 {"tweets": [tweet, distinct]},
237 ]
238 with patch("lib.xquik.expand_xquik_queries", return_value=["test topic", "topic variant"]):
239 result = search_xquik("test topic", "2026-01-01", "2026-03-01", depth="default", token="key")
240 self.assertEqual(
241 [parse_qs(urlsplit(call.args[0]).query)["q"][0] for call in mock_get.call_args_list],
242 [
243 "test topic since:2026-01-01 until:2026-03-02",
244 "topic variant since:2026-01-01 until:2026-03-02",
245 ],
246 )
247 self.assertEqual(
248 [item["url"] for item in result["items"]],
249 ["https://x.com/user/status/222", "https://x.com/other/status/333"],
250 )
251 ids = [item.get("id") for item in result["items"]]
252 self.assertEqual(len(ids), len(set(ids)))
253
254 @patch("lib.xquik.http.get")
255 def test_auth_error_returns_error(self, mock_get):
256 from lib import http as http_mod
257 mock_get.side_effect = http_mod.HTTPError("Unauthorized", status_code=401)
258 result = search_xquik("test", "2026-01-01", "2026-03-01", token="bad-key")
259 self.assertEqual(result["items"], [])
260 self.assertIn("auth failed", result.get("error", ""))
261
262 @patch("lib.xquik.http.get")
263 def test_unpaid_402_surfaces_error_on_real_path(self, mock_get):
264 # An unpaid key (402) must surface an error on the normal search path,
265 # not settle silently empty — diagnose is opt-in.
266 from lib import http as http_mod
267 mock_get.side_effect = http_mod.HTTPError("Payment Required", status_code=402)
268 result = search_xquik("test", "2026-01-01", "2026-03-01", token="unpaid-key")
269 self.assertEqual(result["items"], [])
270 self.assertIn("unpaid", result.get("error", "").lower())
271 # The X retrieval branch classifies by message text only, so the fixed
272 # detail must carry a payment-required classifier marker (KTD6).
273 self.assertEqual("Xquik key unpaid: payment required (402)", result["error"])
274 self.assertEqual(
275 http_mod.classify_failure(message=result["error"]), health.PAYMENT_REQUIRED
276 )
277
278 @patch("lib.env.x_backend_chain", return_value=["xquik"])
279 @patch("lib.xquik.http.get")
280 def test_unpaid_402_yields_payment_required_source_outcome(self, mock_get, _chain):
281 # End to end through the X backend loop: a 402 from xquik as the sole
282 # backend settles the x source as payment-required, not auth-failed.
283 from lib import http as http_mod, pipeline, schema
284 mock_get.side_effect = http_mod.HTTPError("Payment Required", status_code=402)
285 sq = schema.SubQuery(label="primary", search_query="q", ranking_query="q?", sources=["x"])
286 runtime = schema.ProviderRuntime(
287 reasoning_provider="mock", planner_model="mock", rerank_model="mock",
288 x_search_backend=None,
289 )
290 with self.assertRaises(pipeline.SourceRunError) as ctx:
291 pipeline._retrieve_stream(
292 topic="q", subquery=sq, source="x", config={"XQUIK_API_KEY": "k"},
293 depth="default", date_range=("2026-05-19", "2026-06-18"),
294 runtime=runtime, mock=False,
295 )
296 self.assertEqual(health.PAYMENT_REQUIRED, ctx.exception.outcome_state)
297 state, attempted = pipeline._classify_source_failure(ctx.exception)
298 self.assertEqual((health.PAYMENT_REQUIRED, True), (state, attempted))
299
300 @patch("lib.xquik.http.get")
301 def test_empty_tweets_list(self, mock_get):
302 mock_get.return_value = {"tweets": []}
303 result = search_xquik("obscure topic", "2026-01-01", "2026-03-01", token="key")
304 self.assertEqual(result["items"], [])
305 self.assertNotIn("error", result)
306
307 @patch("lib.xquik.http.get")
308 def test_non_list_tweets_skipped(self, mock_get):
309 mock_get.return_value = {"tweets": "not a list"}
310 result = search_xquik("test", "2026-01-01", "2026-03-01", token="key")
311 self.assertEqual(result["items"], [])
312
313
314 class TestDepthConfig(unittest.TestCase):
315 def test_all_depths_have_limit_and_queries(self):
316 for depth_name, cfg in DEPTH_CONFIG.items():
317 self.assertIn("limit", cfg, f"{depth_name} missing 'limit'")
318 self.assertIn("queries", cfg, f"{depth_name} missing 'queries'")
319
320 def test_deep_has_highest_limit(self):
321 self.assertGreater(DEPTH_CONFIG["deep"]["limit"], DEPTH_CONFIG["default"]["limit"])
322 self.assertGreater(DEPTH_CONFIG["default"]["limit"], DEPTH_CONFIG["quick"]["limit"])
323
324 def test_deep_has_most_queries(self):
325 self.assertGreater(DEPTH_CONFIG["deep"]["queries"], DEPTH_CONFIG["quick"]["queries"])
326
327 class TestIsOwn(unittest.TestCase):
328 def test_own_tweet_detected(self):
329 from lib.xquik import _is_own
330 self.assertTrue(_is_own("https://x.com/elonmusk/status/123", "elonmusk"))
331 self.assertTrue(_is_own("https://twitter.com/elonmusk/status/123", "@elonmusk"))
332
333 def test_other_author_not_own(self):
334 from lib.xquik import _is_own
335 self.assertFalse(_is_own("https://x.com/someoneelse/status/123", "elonmusk"))
336
337 def test_empty_handle_or_url(self):
338 from lib.xquik import _is_own
339 self.assertFalse(_is_own("", "elonmusk"))
340 self.assertFalse(_is_own("https://x.com/a/status/1", ""))
341
342
343 class TestFromLane(unittest.TestCase):
344 def _resp(self, username, tid="1"):
345 return {"tweets": [{
346 "id": tid, "text": "anything", "createdAt": "2026-06-15T12:00:00Z",
347 "likeCount": 10, "author": {"username": username},
348 }]}
349
350 def test_from_query_shape_and_no_topic_anded(self):
351 from lib import xquik
352 with patch("lib.xquik.http.get", return_value=self._resp("elonmusk")) as m:
353 items = xquik.search_handles(["@elonmusk"], "Grok 4", "2026-05-19", "2026-06-18",
354 count_per=8, token="k")
355 url = m.call_args[0][0]
356 self.assertIn("from%3Aelonmusk", url) # from:elonmusk url-encoded
357 self.assertIn("since%3A2026-05-19", url)
358 self.assertNotIn("Grok", url) # topic must NOT be AND'd into query
359 self.assertEqual(1, len(items))
360 self.assertEqual("XF1", items[0]["id"]) # FROM-lane id prefix
361
362 def test_no_token_or_no_handles_returns_empty(self):
363 from lib import xquik
364 self.assertEqual([], xquik.search_handles(["@x"], "t", "a", "b", token=""))
365 self.assertEqual([], xquik.search_handles([], "t", "a", "b", token="k"))
366
367 def test_item_ids_unique_across_handles(self):
368 # Different tweets across two handles must not collide on item id.
369 from lib import xquik
370 responses = [
371 {"tweets": [{"id": "1", "text": "a", "createdAt": "2026-06-15T12:00:00Z",
372 "author": {"username": "h1"}}]},
373 {"tweets": [{"id": "2", "text": "b", "createdAt": "2026-06-15T12:00:00Z",
374 "author": {"username": "h2"}}]},
375 ]
376 with patch("lib.xquik.http.get", side_effect=responses):
377 items = xquik.search_handles(["h1", "h2"], "topic", "2026-05-19", "2026-06-18", token="k")
378 ids = [it["id"] for it in items]
379 self.assertEqual(len(ids), len(set(ids)))
380
381
382 class TestHandleLaneNonFatalFailures(unittest.TestCase):
383 """A 429/5xx, a network error, or a junk payload emptied the lane without
384 appending anything to failure_out, so the pipeline recorded a genuine
385 no-results and the report said the subject posted nothing."""
386
387 def test_rate_limit_is_reported_not_silent(self):
388 from lib import http as http_mod
389 from lib import xquik
390 failures: list[str] = []
391 with patch("lib.xquik.http.get",
392 side_effect=http_mod.HTTPError("HTTP 429: Too Many Requests", status_code=429)):
393 items = xquik.search_handles(["h1"], "topic", "2026-05-19", "2026-06-18",
394 token="k", failure_out=failures)
395 self.assertEqual([], items)
396 self.assertEqual(1, len(failures))
397 self.assertIn("from:h1", failures[0])
398 self.assertIn("429", failures[0])
399
400 def test_network_error_is_reported_not_silent(self):
401 from lib import xquik
402 failures: list[str] = []
403 with patch("lib.xquik.http.get", side_effect=OSError("connection reset")):
404 items = xquik.search_mentions(["h1"], "2026-05-19", "2026-06-18",
405 topic="topic", token="k", failure_out=failures)
406 self.assertEqual([], items)
407 self.assertEqual(1, len(failures))
408 self.assertIn("@h1", failures[0])
409 self.assertIn("connection reset", failures[0])
410
411 def test_unparseable_payload_is_reported_not_silent(self):
412 from lib import xquik
413 failures: list[str] = []
414 with patch("lib.xquik.http.get", return_value={"tweets": "not-a-list"}):
415 items = xquik.search_handles(["h1"], "topic", "2026-05-19", "2026-06-18",
416 token="k", failure_out=failures)
417 self.assertEqual([], items)
418 self.assertEqual(1, len(failures))
419 self.assertIn("from:h1", failures[0])
420
421 def test_one_bad_handle_does_not_stop_the_next(self):
422 # Non-fatal failures must be noted without aborting the lane, or a
423 # transient error on the first handle would discard the second's items.
424 from lib import http as http_mod
425 from lib import xquik
426 failures: list[str] = []
427 responses = [
428 http_mod.HTTPError("HTTP 503: Service Unavailable", status_code=503),
429 {"tweets": [{"id": "2", "text": "b", "createdAt": "2026-06-15T12:00:00Z",
430 "author": {"username": "h2"}}]},
431 ]
432 with patch("lib.xquik.http.get", side_effect=responses):
433 items = xquik.search_handles(["h1", "h2"], "topic", "2026-05-19",
434 "2026-06-18", token="k", failure_out=failures)
435 self.assertEqual(1, len(items))
436 self.assertEqual(1, len(failures))
437 self.assertIn("from:h1", failures[0])
438
439 def test_fatal_auth_failure_still_stops_the_lane(self):
440 # The pre-existing fatal path must keep its break semantics: an unpaid
441 # key is not worth retrying per handle.
442 from lib import http as http_mod
443 from lib import xquik
444 failures: list[str] = []
445 with patch("lib.xquik.http.get",
446 side_effect=http_mod.HTTPError("Payment Required", status_code=402)) as m:
447 items = xquik.search_handles(["h1", "h2"], "topic", "2026-05-19",
448 "2026-06-18", token="k", failure_out=failures)
449 self.assertEqual([], items)
450 self.assertEqual(1, m.call_count)
451 self.assertEqual(["Xquik key unpaid: payment required (402)"], failures)
452
453
454 class TestAboutLane(unittest.TestCase):
455 def test_mentions_drop_own_tweets(self):
456 from lib import xquik
457 resp = {"tweets": [
458 {"id": "1", "text": "@elonmusk nice", "createdAt": "2026-06-15T12:00:00Z",
459 "author": {"username": "fan"}},
460 {"id": "2", "text": "my own post", "createdAt": "2026-06-15T12:00:00Z",
461 "author": {"username": "elonmusk"}},
462 ]}
463 with patch("lib.xquik.http.get", return_value=resp) as m:
464 items = xquik.search_mentions(["elonmusk"], "2026-05-19", "2026-06-18",
465 topic="Grok 4", count_per=5, token="k")
466 url = m.call_args[0][0]
467 self.assertIn("%40elonmusk", url) # @elonmusk url-encoded
468 authors = {it["author_handle"] for it in items}
469 self.assertIn("fan", authors)
470 self.assertNotIn("elonmusk", authors) # own tweet dropped
471
472
473 class TestExpandGuard(unittest.TestCase):
474 @patch("lib.xquik._extract_core_subject", return_value="news")
475 def test_bare_generic_core_falls_back_to_topic(self, _m):
476 # #607: a single bare generic core must not be the query for a
477 # multi-word topic — fall back to the full topic.
478 qs = expand_xquik_queries("Grok 4 news", "quick")
479 self.assertEqual(["Grok 4 news"], qs)
480
481 @patch("lib.xquik._extract_core_subject", return_value="Grok 4")
482 def test_multiword_core_kept(self, _m):
483 qs = expand_xquik_queries("Grok 4 latest", "quick")
484 self.assertEqual(["Grok 4"], qs)
485
486
487 class TestProbeWorks(unittest.TestCase):
488 """U5: honest diagnose probe — tri-state, surfaces the unpaid (402) case."""
489
490 def setUp(self):
491 import lib.xquik as xq
492 xq._probe_cache = ("unset", "")
493
494 @patch("lib.xquik.http.get")
495 def test_funded_key_works(self, mock_get):
496 from lib import xquik
497 mock_get.return_value = {"tweets": [{"id": "1"}]}
498 self.assertIs(True, xquik.probe_works("k"))
499 self.assertEqual("ok", xquik.probe_reason())
500
501 @patch("lib.xquik.http.get")
502 def test_unpaid_402_is_false_with_reason(self, mock_get):
503 from lib import xquik, http as http_mod
504 mock_get.side_effect = http_mod.HTTPError("Payment Required", status_code=402)
505 self.assertIs(False, xquik.probe_works("k"))
506 self.assertIn("unpaid", xquik.probe_reason())
507
508 @patch("lib.xquik.http.get")
509 def test_auth_401_is_false(self, mock_get):
510 from lib import xquik, http as http_mod
511 mock_get.side_effect = http_mod.HTTPError("Unauthorized", status_code=401)
512 self.assertIs(False, xquik.probe_works("k"))
513 self.assertIn("auth failed", xquik.probe_reason())
514
515 @patch("lib.xquik.http.get")
516 def test_timeout_is_inconclusive_fail_open(self, mock_get):
517 from lib import xquik
518 mock_get.side_effect = TimeoutError("timed out")
519 self.assertIsNone(xquik.probe_works("k"))
520
521 def test_no_token_is_false(self):
522 from lib import xquik
523 self.assertIs(False, xquik.probe_works(""))
524 self.assertIn("no XQUIK_API_KEY", xquik.probe_reason())
525
526 @patch("lib.xquik.http.get")
527 def test_result_is_cached(self, mock_get):
528 from lib import xquik
529 mock_get.return_value = {"tweets": [{"id": "1"}]}
530 xquik.probe_works("k")
531 xquik.probe_works("k")
532 self.assertEqual(1, mock_get.call_count)
533
534
535 class TestDiagnoseSurfacesXquik(unittest.TestCase):
536 """U5: get_x_source_status reports xquik as the active X source when bird/
537 xAI/xurl are absent, and surfaces the probe reason."""
538
539 def setUp(self):
540 import lib.xquik as xq
541 xq._probe_cache = ("unset", "")
542
543 @patch("lib.xquik.http.get")
544 @patch("lib.xurl_x.is_available", return_value=False)
545 @patch("lib.bird_x.get_bird_status")
546 def test_xquik_is_active_x_source_when_only_key(self, mock_bird, _xurl, mock_get):
547 from lib import env
548 mock_bird.return_value = {"installed": False, "authenticated": False,
549 "username": "", "can_install": False}
550 mock_get.return_value = {"tweets": [{"id": "1"}]}
551 status = env.get_x_source_status({"XQUIK_API_KEY": "k"}, probe=True)
552 self.assertEqual("xquik", status["source"])
553 self.assertTrue(status["xquik_available"])
554 self.assertIs(True, status["xquik_working"])
555
556 @patch("lib.xurl_x.is_available", return_value=False)
557 @patch("lib.bird_x.get_bird_status")
558 def test_unpaid_xquik_not_active_source(self, mock_bird, _xurl):
559 from lib import env, http as http_mod
560 import lib.xquik as xq
561 mock_bird.return_value = {"installed": False, "authenticated": False,
562 "username": "", "can_install": False}
563 with patch("lib.xquik.http.get", side_effect=http_mod.HTTPError("pay", status_code=402)):
564 status = env.get_x_source_status({"XQUIK_API_KEY": "k"}, probe=True)
565 self.assertIsNone(status["source"]) # unpaid key is not a usable X source
566 self.assertIs(False, status["xquik_working"])
567 self.assertIn("unpaid", status["xquik_status"])
568
569
570 class TestMentionedHandles(unittest.TestCase):
571 """U3: xquik items carry leading-run @mentions so the first-party
572 interaction signal fires (shared parser with bird)."""
573
574 def _tweet(self, text):
575 return {
576 "id": "1", "text": text, "createdAt": "2026-06-15T12:00:00Z",
577 "author": {"username": "subject"},
578 }
579
580 def test_leading_mentions_captured(self):
581 item = _parse_tweet(self._tweet("@jack @pmarca thoughts on this"), 0, "topic")
582 self.assertEqual(["jack", "pmarca"], item["mentioned_handles"])
583
584 def test_midbody_mention_ignored(self):
585 item = _parse_tweet(self._tweet("I think @jack is right"), 0, "topic")
586 self.assertEqual([], item["mentioned_handles"])
587
588 def test_no_mentions(self):
589 item = _parse_tweet(self._tweet("Grok 4 just shipped"), 0, "topic")
590 self.assertEqual([], item["mentioned_handles"])
591
592
593 class TestNormalizePropagatesMentions(unittest.TestCase):
594 """U3: _normalize_x carries xquik mentioned_handles into metadata so rerank
595 can read them."""
596
597 def test_mentioned_handles_reach_metadata(self):
598 from lib import normalize
599 item = _parse_tweet(
600 {"id": "1", "text": "@jack hi", "createdAt": "2026-06-15T12:00:00Z",
601 "author": {"username": "subject"}}, 0, "topic")
602 normalized = normalize.normalize_source_items("xquik", [item], "2026-05-19", "2026-06-18")
603 self.assertEqual(["jack"], normalized[0].metadata.get("mentioned_handles"))
604
605
606 if __name__ == "__main__":
607 unittest.main()
608
608 lines PYTHON