返回 last30days-skill
test_x_api.py
根目录 / tests / test_x_api.py
1 """xapi: the direct X API v2 backend and the shared v2 parser (U4).
2
3 Every test mocks ``lib.http.get`` (or urlopen for the fixture seam); no test
4 makes a live X call. The dummy token below is obvious fake data and must
5 never appear in any error string, source_log line, or recorded fixture.
6 """
7
8 from __future__ import annotations
9
10 import io
11 import json
12 import threading
13 from contextlib import redirect_stderr
14 from datetime import datetime, timezone
15 from unittest import mock
16 from unittest.mock import MagicMock
17
18 import pytest
19
20 from lib import env, health, http, pipeline, schema, x_api, xurl_x
21
22 DUMMY_TOKEN = "dummy-x-bearer-secret-000"
23 ACCOUNT_ID = "acct-1234567890"
24 FIXED_NOW = datetime(2026, 9, 8, 12, 0, 0, tzinfo=timezone.utc)
25 FROM = "2026-08-10"
26 TO = "2026-09-08"
27
28
29 def _tweet(id_, text, author_id="u1", created_at="2026-08-20T12:00:00Z", metrics=None, **extra):
30 t = {"id": id_, "text": text, "author_id": author_id}
31 if created_at:
32 t["created_at"] = created_at
33 if metrics is not None:
34 t["public_metrics"] = metrics
35 t.update(extra)
36 return t
37
38
39 def _v2(tweets, users=None, next_token=None):
40 resp = {"data": tweets, "meta": {"result_count": len(tweets)}}
41 if users:
42 resp["includes"] = {"users": users}
43 if next_token:
44 resp["meta"]["next_token"] = next_token
45 return resp
46
47
48 def _users(*pairs):
49 return [{"id": uid, "username": name} for uid, name in pairs]
50
51
52 def _http_error(status, body="", message=None):
53 return http.HTTPError(message or f"HTTP {status}: Error", status_code=status, body=body)
54
55
56 @pytest.fixture
57 def fixed_now(monkeypatch):
58 monkeypatch.setattr(x_api, "_utcnow", lambda: FIXED_NOW)
59 return FIXED_NOW
60
61
62 @pytest.fixture
63 def get_mock(monkeypatch):
64 m = MagicMock(name="http.get")
65 monkeypatch.setattr(x_api.http, "get", m)
66 return m
67
68
69 def _params(call):
70 return call.kwargs.get("params") or {}
71
72
73 def _url(call):
74 return call.args[0] if call.args else call.kwargs["url"]
75
76
77 # ---------------------------------------------------------------------------
78 # parse_v2_response
79 # ---------------------------------------------------------------------------
80
81
82 class TestParseV2Response:
83 def test_fixture_with_users_parses_all_fields(self):
84 metrics = {
85 "like_count": 42, "retweet_count": 10, "reply_count": 5,
86 "quote_count": 2, "bookmark_count": 7, "impression_count": 9000,
87 }
88 resp = _v2(
89 [_tweet("1956158892141441450", "Claude Code agents are great", metrics=metrics)],
90 users=_users(("u1", "alice")),
91 )
92 items = x_api.parse_v2_response(resp, "Claude Code", (FROM, TO))
93 assert len(items) == 1
94 item = items[0]
95 assert item["id"] == "XAPI1"
96 assert item["post_id"] == "1956158892141441450"
97 assert item["author_handle"] == "alice"
98 assert item["url"] == "https://x.com/alice/status/1956158892141441450"
99 assert item["date"] == "2026-08-20"
100 assert item["engagement"] == {
101 "likes": 42, "reposts": 10, "replies": 5, "quotes": 2,
102 "bookmarks": 7, "views": 9000,
103 }
104 assert item["why_relevant"] == ""
105 assert item["relevance"] > 0.5
106 assert item["mentioned_handles"] == []
107
108 def test_without_users_keeps_item_with_i_status_url(self):
109 resp = _v2([_tweet("999", "text here", author_id="unknown")])
110 items = x_api.parse_v2_response(resp, "text", (FROM, TO))
111 assert len(items) == 1
112 assert items[0]["url"] == "https://x.com/i/status/999"
113 assert items[0]["author_handle"] == ""
114
115 def test_note_tweet_replaces_truncated_text(self):
116 resp = _v2([_tweet("5", "truncated...", note_tweet={"text": "the full long-form post text"})])
117 items = x_api.parse_v2_response(resp, "", None)
118 assert items[0]["text"] == "the full long-form post text"
119
120 def test_url_is_built_from_id_never_from_response_url_fields(self):
121 resp = _v2(
122 [_tweet("7", "hi", url="https://evil.example/phish",
123 entities={"urls": [{"expanded_url": "https://evil.example/x"}]})],
124 users=_users(("u1", "bob")),
125 )
126 items = x_api.parse_v2_response(resp, "", None)
127 assert items[0]["url"] == "https://x.com/bob/status/7"
128 assert "evil.example" not in json.dumps(items)
129
130 def test_username_outside_handle_grammar_falls_back_to_i_status(self):
131 resp = _v2([_tweet("8", "hi")], users=[{"id": "u1", "username": "bad name/../x"}])
132 items = x_api.parse_v2_response(resp, "", None)
133 assert items[0]["author_handle"] == ""
134 assert items[0]["url"] == "https://x.com/i/status/8"
135
136 def test_leading_mentions_become_mentioned_handles(self):
137 resp = _v2([_tweet("9", "@steipete @alice thanks for this")])
138 items = x_api.parse_v2_response(resp, "", None)
139 assert items[0]["mentioned_handles"] == ["steipete", "alice"]
140
141 def test_engagement_none_without_metrics_and_bookmarks_views_only_when_present(self):
142 resp = _v2([
143 _tweet("1", "a"),
144 _tweet("2", "b", metrics={"like_count": 1, "retweet_count": 0, "reply_count": 0, "quote_count": 0}),
145 ])
146 items = x_api.parse_v2_response(resp, "", None)
147 assert items[0]["engagement"] is None
148 assert items[1]["engagement"] == {"likes": 1, "reposts": 0, "replies": 0, "quotes": 0}
149
150 def test_non_numeric_ids_are_dropped(self):
151 resp = _v2([_tweet("abc", "x"), _tweet("12", "y")])
152 items = x_api.parse_v2_response(resp, "", None)
153 assert [i["post_id"] for i in items] == ["12"]
154
155 def test_window_drops_dated_items_outside_it(self):
156 resp = _v2([
157 _tweet("1", "old", created_at="2026-07-01T00:00:00Z"),
158 _tweet("2", "in", created_at="2026-08-20T00:00:00Z"),
159 ])
160 items = x_api.parse_v2_response(resp, "", (FROM, TO))
161 assert [i["post_id"] for i in items] == ["2"]
162
163 def test_error_response_yields_nothing(self):
164 assert x_api.parse_v2_response({"error": "x"}, "", None) == []
165 assert x_api.parse_v2_response({}, "", None) == []
166
167 def test_xurl_delegates_to_shared_parser_and_depth_config(self):
168 resp = _v2([_tweet("3", "hello")], users=_users(("u1", "alice")))
169 items = xurl_x.parse_x_response(resp, topic="hello")
170 assert items[0]["id"] == "XURL1"
171 assert items[0]["url"] == "https://x.com/alice/status/3"
172 assert items[0]["post_id"] == "3"
173 assert xurl_x.DEPTH_CONFIG is x_api.DEPTH_CONFIG
174 assert x_api.DEPTH_CONFIG == {"quick": 10, "default": 30, "deep": 60}
175
176
177 # ---------------------------------------------------------------------------
178 # Query compilation (R8a)
179 # ---------------------------------------------------------------------------
180
181
182 class TestBuildQuery:
183 def test_wraps_core_in_one_quote_pair_and_appends_no_retweets(self):
184 q = x_api.build_query('Claude Code "agents"')
185 assert q == '"Claude Code agents" -is:retweet'
186
187 def test_operator_injection_is_stripped(self):
188 q = x_api.build_query('foo" OR from:attacker since:2015-01-01 "')
189 assert q == '"foo" -is:retweet'
190 assert "from:" not in q and "since:" not in q and " OR " not in q
191 assert q.count('"') == 2
192
193 def test_negation_and_grouping_characters_are_stripped(self):
194 q = x_api.build_query("(Peter Steinberger) -steipete “quoted” [x] {y}")
195 assert q == '"Peter Steinberger quoted x y" -is:retweet'
196
197 def test_trailing_colon_handling_stays_out_of_phrase_query(self):
198 assert x_api.build_query("Python: what's new") == '"what\'s new" -is:retweet'
199
200 def test_600_char_topic_compiles_under_512_with_balanced_quotes(self):
201 topic = " ".join(f"word{i}" for i in range(100))
202 assert len(topic) >= 600
203 q = x_api.build_query(topic)
204 assert len(q) <= x_api.MAX_QUERY_CHARS
205 assert q.count('"') == 2
206 assert q.endswith('" -is:retweet')
207 assert not q.startswith('"word') or q.startswith('"word0 ')
208 # Cut at a token boundary: the last kept token is intact.
209 core = q[1:q.index('" -is:retweet')]
210 assert all(tok.startswith("word") and tok[4:].isdigit() for tok in core.split())
211
212 def test_single_giant_token_is_truncated_not_dropped(self):
213 q = x_api.build_query("a" * 700)
214 assert 0 < len(q) <= x_api.MAX_QUERY_CHARS
215 assert q.count('"') == 2
216
217 def test_only_operators_yields_empty_query(self):
218 assert x_api.build_query("from:attacker OR -is:reply lang:en") == ""
219
220
221 class TestBuildKeywordQuery:
222 def test_space_joined_keywords_without_phrase_or_retweet_filter(self):
223 assert x_api.build_keyword_query("Claude Code agents") == "Claude Code agents"
224
225 def test_bare_and_or_are_dropped_in_any_case(self):
226 q = x_api.build_keyword_query("review and security Or tools AND codex or x")
227 assert q == "review security tools codex x"
228
229 def test_operators_negation_grouping_and_quotes_are_stripped(self):
230 q = x_api.build_keyword_query('(foo) "bar from:attacker -baz lang:en')
231 assert q == "foo bar"
232
233 def test_capped_at_token_boundary(self):
234 q = x_api.build_keyword_query(" ".join(f"word{i}" for i in range(200)))
235 assert len(q) <= x_api.MAX_QUERY_CHARS
236 assert all(tok.startswith("word") and tok[4:].isdigit() for tok in q.split())
237
238 def test_single_giant_token_is_truncated(self):
239 q = x_api.build_keyword_query("a" * 700)
240 assert len(q) == x_api.MAX_QUERY_CHARS
241
242 def test_only_operators_yields_empty_query(self):
243 assert x_api.build_keyword_query("and from:x -y ()") == ""
244
245
246 # ---------------------------------------------------------------------------
247 # Request shape (KTD4)
248 # ---------------------------------------------------------------------------
249
250
251 class TestRequestShape:
252 def test_full_archive_request_shape(self, get_mock, fixed_now):
253 get_mock.return_value = _v2([_tweet("1", "Claude Code rocks")], users=_users(("u1", "a")))
254 result = x_api.search_x(DUMMY_TOKEN, "Claude Code", FROM, TO, depth="quick")
255 assert "error" not in result
256 assert [i["id"] for i in result["items"]] == ["XAPI1"]
257 call = get_mock.call_args
258 assert _url(call) == "https://api.x.com/2/tweets/search/all"
259 p = _params(call)
260 assert p["query"] == '"Claude Code" -is:retweet'
261 assert p["start_time"] == "2026-08-10T00:00:00Z"
262 # to_date is "today" relative to the fixed clock: end_time keeps a
263 # 30 second safety margin before now.
264 assert p["end_time"] == "2026-09-08T11:59:30Z"
265 assert p["sort_order"] == "recency"
266 assert p["max_results"] == 10
267 assert p["expansions"] == "author_id"
268 assert p["tweet.fields"] == "created_at,public_metrics,note_tweet,entities"
269 assert p["user.fields"] == "username"
270 assert "lang:" not in p["query"]
271 assert call.kwargs["headers"]["Authorization"] == f"Bearer {DUMMY_TOKEN}"
272 assert call.kwargs["timeout"] == 30
273 assert call.kwargs["retries"] == 2
274
275 def test_past_end_date_uses_end_of_day(self, get_mock, fixed_now):
276 get_mock.return_value = _v2([])
277 x_api.search_x(DUMMY_TOKEN, "topic", "2026-08-01", "2026-08-31", depth="quick")
278 assert _params(get_mock.call_args)["end_time"] == "2026-08-31T23:59:59Z"
279
280 def test_max_results_clamped_to_10_and_100(self, get_mock, fixed_now, monkeypatch):
281 get_mock.return_value = _v2([])
282 x_api.search_handles(["steipete"], "t", FROM, TO, count_per=3, token=DUMMY_TOKEN)
283 assert _params(get_mock.call_args)["max_results"] == 10
284 monkeypatch.setitem(x_api.DEPTH_CONFIG, "deep", 150)
285 x_api.search_x(DUMMY_TOKEN, "topic", FROM, TO, depth="deep")
286 assert _params(get_mock.call_args)["max_results"] == 100
287
288 def test_pagination_stops_at_depth_count(self, get_mock, fixed_now):
289 page = lambda start, n, nxt: _v2(
290 [_tweet(str(1000 + start + i), f"post {i}") for i in range(n)], next_token=nxt,
291 )
292 get_mock.side_effect = [page(0, 20, "p2"), page(20, 20, "p3"), page(40, 20, "p4")]
293 result = x_api.search_x(DUMMY_TOKEN, "topic", FROM, TO, depth="default")
294 assert get_mock.call_count == 2, "30 posts reached after two pages; the third is never fetched"
295 assert len(result["items"]) == 30
296 assert "next_token" not in _params(get_mock.call_args_list[0])
297 assert _params(get_mock.call_args_list[1])["next_token"] == "p2"
298 assert len({i["id"] for i in result["items"]}) == 30
299
300 def test_pagination_stops_at_the_wall_clock_deadline(self, get_mock, fixed_now, monkeypatch):
301 page = lambda start, n, nxt: _v2(
302 [_tweet(str(1000 + start + i), f"post {i}") for i in range(n)], next_token=nxt,
303 )
304 get_mock.side_effect = [page(0, 20, "p2"), page(20, 20, "p3"), page(40, 20, "p4")]
305 clock = iter([0.0, x_api.DEADLINE_SECONDS + 1.0, x_api.DEADLINE_SECONDS + 2.0, x_api.DEADLINE_SECONDS + 3.0])
306 monkeypatch.setattr(x_api.time, "monotonic", lambda: next(clock))
307 result = x_api.search_x(DUMMY_TOKEN, "topic", FROM, TO, depth="deep")
308 assert get_mock.call_count == 1, "the first page always runs; the second is skipped past the deadline"
309 assert len(result["items"]) == 20
310 assert "error" not in result
311 assert result["warning"] == x_api.DEADLINE_DETAIL
312
313 def test_deadline_reaches_the_transport_and_keeps_pages_collected_before_it(self, get_mock, fixed_now, monkeypatch):
314 """The lane deadline is the transport's wall deadline (no full 30s
315 timeout plus retries past it), and a deadline hit mid-walk returns
316 the pages already collected."""
317 page = lambda start, n, nxt: _v2(
318 [_tweet(str(1000 + start + i), f"post {i}") for i in range(n)], next_token=nxt,
319 )
320 monkeypatch.setattr(x_api.time, "monotonic", lambda: 100.0)
321 get_mock.side_effect = [page(0, 20, "p2"), http.DeadlineExceeded()]
322 result = x_api.search_handles(["steipete"], "t", FROM, TO, count_per=60, token=DUMMY_TOKEN, deadline=130.0)
323 assert get_mock.call_count == 2
324 for call in get_mock.call_args_list:
325 assert call.kwargs["deadline_monotonic"] == 130.0
326 assert len(result) == 20 and "error" not in result[0]
327 get_mock.reset_mock()
328 # The same stop on the topic search is a warning receipt, never a
329 # healthy-looking complete result.
330 get_mock.side_effect = [page(0, 20, "p2"), http.DeadlineExceeded()]
331 topic = x_api.search_x(DUMMY_TOKEN, "topic", FROM, TO, depth="deep")
332 assert len(topic["items"]) == 20
333 assert topic["warning"] == x_api.DEADLINE_DETAIL
334 get_mock.reset_mock()
335 get_mock.side_effect = [http.DeadlineExceeded()]
336 assert x_api.search_x(DUMMY_TOKEN, "topic", FROM, TO, depth="quick")["error"] == x_api.ERR_TIMED_OUT
337
338 def test_pagination_stops_without_next_token(self, get_mock, fixed_now):
339 get_mock.return_value = _v2([_tweet("1", "only one")])
340 result = x_api.search_x(DUMMY_TOKEN, "topic", FROM, TO, depth="deep")
341 assert get_mock.call_count == 1
342 assert len(result["items"]) == 1
343
344 def test_every_request_targets_api_x_com_and_carries_no_token_outside_the_header(self, get_mock, fixed_now):
345 get_mock.side_effect = [
346 _http_error(403, body='{"reason":"client-not-enrolled"}'),
347 _v2([_tweet("1", "a")], next_token="n"),
348 _v2([_tweet("2", "b")]),
349 ]
350 x_api.search_x(DUMMY_TOKEN, "topic", FROM, TO, depth="quick")
351 x_api.search_mentions(["steipete"], FROM, TO, topic="t", token=DUMMY_TOKEN)
352 assert get_mock.call_count >= 3
353 for call in get_mock.call_args_list:
354 url = _url(call)
355 assert url.startswith("https://api.x.com/2/tweets/search/")
356 assert DUMMY_TOKEN not in url
357 assert DUMMY_TOKEN not in json.dumps(_params(call))
358 headers = dict(call.kwargs["headers"])
359 headers.pop("Authorization")
360 assert DUMMY_TOKEN not in json.dumps(headers)
361
362 def test_operator_injection_still_carries_engine_window(self, get_mock, fixed_now):
363 get_mock.return_value = _v2([])
364 x_api.search_x(DUMMY_TOKEN, 'foo" OR from:attacker since:2015-01-01 "', FROM, TO)
365 p = _params(get_mock.call_args)
366 assert p["query"] == '"foo" -is:retweet'
367 assert p["start_time"] == "2026-08-10T00:00:00Z"
368 assert p["end_time"] == "2026-09-08T11:59:30Z"
369
370 def test_empty_query_after_sanitizing_makes_no_request(self, get_mock, fixed_now):
371 result = x_api.search_x(DUMMY_TOKEN, "from:attacker OR", FROM, TO)
372 assert result["items"] == []
373 assert result["error"] == x_api.ERR_EMPTY_QUERY
374 get_mock.assert_not_called()
375
376 def test_missing_token_makes_no_request(self, get_mock):
377 result = x_api.search_x("", "topic", FROM, TO)
378 assert result["items"] == [] and result["error"]
379 get_mock.assert_not_called()
380
381
382 # ---------------------------------------------------------------------------
383 # 403 enrollment fallback (KTD4)
384 # ---------------------------------------------------------------------------
385
386
387 class TestEnrollmentFallback:
388 def test_enrollment_403_retries_recent_once_with_clamped_window(self, get_mock, fixed_now):
389 get_mock.side_effect = [
390 _http_error(403, body='{"reason":"client-not-enrolled","detail":"...","client_id":"' + ACCOUNT_ID + '"}'),
391 _v2([_tweet("1", "recent post", created_at="2026-09-05T00:00:00Z")], users=_users(("u1", "a"))),
392 ]
393 result = x_api.search_x(DUMMY_TOKEN, "topic", FROM, TO, depth="quick")
394 assert get_mock.call_count == 2
395 assert _url(get_mock.call_args_list[0]) == "https://api.x.com/2/tweets/search/all"
396 assert _url(get_mock.call_args_list[1]) == "https://api.x.com/2/tweets/search/recent"
397 p2 = _params(get_mock.call_args_list[1])
398 assert p2["start_time"] == "2026-09-01T12:00:30Z", "start clamped to now minus 7 days"
399 assert p2["end_time"] == "2026-09-08T11:59:30Z"
400 assert "error" not in result
401 assert result["warning"] == x_api.TRUNCATION_DETAIL == "window truncated to 7 days"
402 assert len(result["items"]) == 1
403
404 def test_enrollment_fallback_keeps_start_when_window_already_recent(self, get_mock, fixed_now):
405 get_mock.side_effect = [
406 _http_error(403, body="not enrolled"),
407 _v2([]),
408 ]
409 x_api.search_x(DUMMY_TOKEN, "topic", "2026-09-06", TO, depth="quick")
410 assert _params(get_mock.call_args_list[1])["start_time"] == "2026-09-06T00:00:00Z"
411
412 def test_plain_403_does_not_retry(self, get_mock, fixed_now):
413 get_mock.side_effect = [_http_error(403, body="Forbidden")]
414 result = x_api.search_x(DUMMY_TOKEN, "topic", FROM, TO, depth="quick")
415 assert get_mock.call_count == 1
416 assert result["items"] == []
417 assert result["error"] == x_api.ERR_FORBIDDEN
418 assert http.classify_failure(message=result["error"]) == health.AUTH_FAILED
419
420 def test_enrollment_fallback_with_window_before_the_floor_sends_no_request(self, get_mock, fixed_now):
421 """A window that ends before now-7d cannot be served by recent search:
422 no second request with start_time after end_time."""
423 get_mock.side_effect = [_http_error(403, body="client-not-enrolled")]
424 result = x_api.search_x(DUMMY_TOKEN, "topic", "2026-08-01", "2026-08-20", depth="quick")
425 assert get_mock.call_count == 1
426 assert result == {"items": [], "warning": x_api.TRUNCATION_DETAIL}
427
428 def test_second_403_on_recent_is_a_fixed_forbidden_error(self, get_mock, fixed_now):
429 get_mock.side_effect = [
430 _http_error(403, body="client-not-enrolled"),
431 _http_error(403, body="client-not-enrolled " + DUMMY_TOKEN),
432 ]
433 result = x_api.search_x(DUMMY_TOKEN, "topic", FROM, TO, depth="quick")
434 assert get_mock.call_count == 2
435 assert result["error"] == x_api.ERR_FORBIDDEN
436
437
438 # ---------------------------------------------------------------------------
439 # Fixed-string errors (R8, KTD6)
440 # ---------------------------------------------------------------------------
441
442 # A body that echoes the token and an account id but carries no status
443 # marker of its own, so the status code alone decides the fixed string.
444 _LEAKY_BODY = json.dumps({
445 "title": "Client Error",
446 "detail": f"request for account {ACCOUNT_ID} rejected; token {DUMMY_TOKEN}",
447 "client_id": ACCOUNT_ID,
448 })
449
450
451 def _run_capturing_stderr(fn):
452 buf = io.StringIO()
453 with redirect_stderr(buf):
454 with mock.patch("sys.stderr.isatty", return_value=False, create=True):
455 out = fn()
456 return out, buf.getvalue()
457
458
459 class TestFixedErrors:
460 @pytest.mark.parametrize("status,expected,state", [
461 (402, x_api.ERR_PAYMENT_REQUIRED, health.PAYMENT_REQUIRED),
462 (403, x_api.ERR_FORBIDDEN, health.AUTH_FAILED),
463 (401, x_api.ERR_UNAUTHORIZED, health.AUTH_FAILED),
464 (429, x_api.ERR_RATE_LIMITED, health.RATE_LIMITED),
465 ])
466 def test_status_maps_to_fixed_string_without_body(self, get_mock, fixed_now, status, expected, state):
467 get_mock.side_effect = _http_error(status, body=_LEAKY_BODY, message=f"HTTP {status}: {ACCOUNT_ID}")
468 result, stderr = _run_capturing_stderr(
469 lambda: x_api.search_x(DUMMY_TOKEN, "topic", FROM, TO, depth="quick")
470 )
471 assert result["items"] == []
472 assert result["error"] == expected
473 assert http.classify_failure(message=result["error"]) == state
474 for leak in (DUMMY_TOKEN, ACCOUNT_ID, "Client Error", "request for account"):
475 assert leak not in result["error"]
476 assert leak not in stderr
477 assert "[xapi]" in stderr or "xapi" in stderr
478
479 def test_fixed_strings_are_the_planned_literals(self):
480 assert x_api.ERR_PAYMENT_REQUIRED == "xapi: payment required (X API credits exhausted)"
481 assert x_api.ERR_UNAUTHORIZED == "xapi: unauthorized (bearer token rejected)"
482 assert x_api.ERR_FORBIDDEN == "xapi: forbidden (bearer token lacks access)"
483 assert x_api.ERR_RATE_LIMITED == "xapi: rate limit exceeded (X API)"
484 assert x_api.ERR_TIMED_OUT == "xapi: timed out"
485
486 def test_credit_marker_in_body_maps_to_payment_required_on_any_status(self, get_mock, fixed_now):
487 get_mock.side_effect = _http_error(403, body='{"detail":"insufficient credits"}')
488 result = x_api.search_x(DUMMY_TOKEN, "topic", FROM, TO, depth="quick")
489 assert result["error"] == x_api.ERR_PAYMENT_REQUIRED
490
491 def test_other_http_status_is_fixed_http_n(self, get_mock, fixed_now):
492 get_mock.side_effect = _http_error(503, body=_LEAKY_BODY)
493 result = x_api.search_x(DUMMY_TOKEN, "topic", FROM, TO, depth="quick")
494 assert result["error"] == "xapi: http 503"
495
496 def test_timeout_is_fixed_string(self, get_mock, fixed_now):
497 get_mock.side_effect = http.HTTPError(
498 f"URL Error: timed out reading {ACCOUNT_ID}", outcome_state=health.TIMEOUT,
499 )
500 result = x_api.search_x(DUMMY_TOKEN, "topic", FROM, TO, depth="quick")
501 assert result["error"] == x_api.ERR_TIMED_OUT
502 assert http.classify_failure(message=result["error"]) == health.TIMEOUT
503
504 def test_unexpected_exception_never_carries_its_message(self, get_mock, fixed_now):
505 get_mock.side_effect = ValueError(f"boom {DUMMY_TOKEN} {ACCOUNT_ID}")
506 result, stderr = _run_capturing_stderr(
507 lambda: x_api.search_x(DUMMY_TOKEN, "topic", FROM, TO, depth="quick")
508 )
509 assert result["error"] == "xapi: request failed (ValueError)"
510 assert DUMMY_TOKEN not in stderr and ACCOUNT_ID not in stderr
511
512 @pytest.mark.parametrize("status,state", [(402, health.PAYMENT_REQUIRED), (403, health.AUTH_FAILED)])
513 def test_pipeline_outcome_carries_only_the_fixed_string(self, get_mock, fixed_now, status, state):
514 get_mock.side_effect = _http_error(status, body=_LEAKY_BODY, message=f"HTTP {status}: {ACCOUNT_ID}")
515 sq = schema.SubQuery(label="primary", search_query="q", ranking_query="q?", sources=["x"])
516 runtime = schema.ProviderRuntime(
517 reasoning_provider="mock", planner_model="mock", rerank_model="mock",
518 x_search_backend=None,
519 )
520
521 def run():
522 with mock.patch("lib.env.x_backend_chain", return_value=["xapi"]):
523 with pytest.raises(pipeline.SourceRunError) as ctx:
524 pipeline._retrieve_stream(
525 topic="q", subquery=sq, source="x",
526 config={"X_BEARER_TOKEN": DUMMY_TOKEN},
527 depth="quick", date_range=(FROM, TO),
528 runtime=runtime, mock=False,
529 )
530 return ctx.value
531
532 exc, stderr = _run_capturing_stderr(run)
533 assert exc.outcome_state == state
534 rendered = str(exc)
535 assert DUMMY_TOKEN not in rendered and ACCOUNT_ID not in rendered
536 assert DUMMY_TOKEN not in stderr and ACCOUNT_ID not in stderr
537 detail_state, attempted = pipeline._classify_source_failure(exc)
538 assert (detail_state, attempted) == (state, True)
539
540
541 # ---------------------------------------------------------------------------
542 # Handle lanes (R7)
543 # ---------------------------------------------------------------------------
544
545
546 class TestHandleLanes:
547 def test_from_lane_query_excludes_topic(self, get_mock, fixed_now):
548 get_mock.return_value = _v2(
549 [_tweet("1", "anything", created_at="2026-08-20T00:00:00Z")], users=_users(("u1", "steipete")),
550 )
551 items = x_api.search_handles(["@steipete"], "Grok 4", FROM, TO, count_per=8, token=DUMMY_TOKEN)
552 p = _params(get_mock.call_args)
553 assert p["query"] == "from:steipete -is:retweet"
554 assert "Grok" not in p["query"]
555 assert p["start_time"] == "2026-08-10T00:00:00Z"
556 assert [i["id"] for i in items] == ["XF1"]
557 assert items[0]["relevance"] >= 0
558
559 def test_mention_lane_excludes_subjects_own_posts(self, get_mock, fixed_now):
560 get_mock.return_value = _v2(
561 [
562 _tweet("1", "@steipete nice", author_id="fan"),
563 _tweet("2", "my own post", author_id="me"),
564 ],
565 users=_users(("fan", "fanuser"), ("me", "steipete")),
566 )
567 items = x_api.search_mentions(["steipete"], FROM, TO, topic="Grok 4", count_per=5, token=DUMMY_TOKEN)
568 p = _params(get_mock.call_args)
569 assert p["query"] == "@steipete -from:steipete -is:retweet"
570 assert {i["author_handle"] for i in items} == {"fanuser"}
571 assert items[0]["id"].startswith("XA")
572
573 def test_invalid_handle_skips_lane_with_receipt(self, get_mock, fixed_now):
574 items, stderr = _run_capturing_stderr(
575 lambda: x_api.search_handles(["x OR from:elonmusk"], "t", FROM, TO, token=DUMMY_TOKEN)
576 )
577 assert items == []
578 get_mock.assert_not_called()
579 assert "skip" in stderr.lower()
580 mentions, _ = _run_capturing_stderr(
581 lambda: x_api.search_mentions(["bad'; drop", "a" * 16], FROM, TO, token=DUMMY_TOKEN)
582 )
583 assert mentions == []
584 get_mock.assert_not_called()
585
586 def test_item_ids_unique_across_handles(self, get_mock, fixed_now):
587 get_mock.side_effect = [
588 _v2([_tweet("1", "a")], users=_users(("u1", "h1"))),
589 _v2([_tweet("2", "b")], users=_users(("u1", "h2"))),
590 ]
591 items = x_api.search_handles(["h1", "h2"], "topic", FROM, TO, token=DUMMY_TOKEN)
592 ids = [i["id"] for i in items]
593 assert len(ids) == len(set(ids)) == 2
594
595 def test_fatal_auth_failure_stops_remaining_handles(self, get_mock, fixed_now):
596 # Handles fan out on a bounded pool (five in flight), so the handles
597 # already scheduled beside the failing one may still be called; the
598 # ones beyond the pool window are not, and nothing leaks.
599 handles = [f"h{i}" for i in range(1, 8)]
600 get_mock.side_effect = _http_error(401, body=_LEAKY_BODY)
601 items, stderr = _run_capturing_stderr(
602 lambda: x_api.search_handles(handles, "topic", FROM, TO, token=DUMMY_TOKEN)
603 )
604 assert items == []
605 assert 1 <= get_mock.call_count <= x_api._MAX_LANE_WORKERS
606 called = {_params(c)["query"] for c in get_mock.call_args_list}
607 assert called <= {f"from:{h} -is:retweet" for h in handles}
608 assert DUMMY_TOKEN not in stderr and ACCOUNT_ID not in stderr
609
610 def test_handle_results_merge_in_handle_order(self, get_mock, fixed_now):
611 def _by_query(url, headers=None, params=None, **kwargs):
612 handle = params["query"].split(":")[1].split(" ")[0]
613 return _v2([_tweet(str(ord(handle[-1])), handle)], users=_users(("u1", handle)))
614
615 get_mock.side_effect = _by_query
616 handles = ["h3", "h1", "h2"]
617 items = x_api.search_handles(handles, "topic", FROM, TO, token=DUMMY_TOKEN)
618 assert [i["author_handle"] for i in items] == handles
619 assert [i["id"] for i in items] == ["XF1", "XF2", "XF3"]
620
621 def test_transient_failure_continues_to_next_handle(self, get_mock, fixed_now):
622 get_mock.side_effect = [_http_error(500), _v2([_tweet("2", "b")], users=_users(("u1", "h2")))]
623 items = x_api.search_handles(["h1", "h2"], "topic", FROM, TO, token=DUMMY_TOKEN)
624 assert [i["author_handle"] for i in items] == ["h2"]
625
626 def test_no_token_or_handles_returns_empty(self, get_mock):
627 assert x_api.search_handles(["a"], "t", FROM, TO, token="") == []
628 assert x_api.search_handles([], "t", FROM, TO, token=DUMMY_TOKEN) == []
629 assert x_api.search_mentions([], FROM, TO, token=DUMMY_TOKEN) == []
630 get_mock.assert_not_called()
631
632
633 # ---------------------------------------------------------------------------
634 # Moved helpers (KTD3)
635 # ---------------------------------------------------------------------------
636
637
638 class TestSharedHelpers:
639 def test_grok_x_imports_helpers_from_x_api(self):
640 from lib import grok_x
641 assert grok_x._decode_snowflake is x_api._decode_snowflake
642 assert grok_x._clean_handle is x_api._clean_handle
643 assert grok_x._looks_generated is x_api._looks_generated
644 assert grok_x._HANDLE_RE is x_api._HANDLE_RE
645
646 def test_snowflake_decodes_to_utc_datetime(self):
647 when = x_api._decode_snowflake("1956158892141441450")
648 assert when is not None and when.tzinfo is not None
649 assert when.year == 2025
650 assert x_api._decode_snowflake("nope") is None
651 assert x_api._decode_snowflake("0") is None
652
653 def test_clean_handle_grammar(self):
654 assert x_api._clean_handle("@steipete") == "steipete"
655 assert x_api._clean_handle("Peter Steinberger") == ""
656 assert x_api._clean_handle("a" * 16) == ""
657 assert x_api._clean_handle("x OR from:elonmusk") == ""
658
659 def test_looks_generated_flags_uniform_runs(self):
660 assert x_api._looks_generated(["100", "200", "300", "400"]) is True
661 assert x_api._looks_generated(["100", "250", "300", "900"]) is False
662 assert x_api._looks_generated(["1", "2"]) is False
663
664
665 # ---------------------------------------------------------------------------
666 # Pipeline wiring (R7): lane selection and failover line
667 # ---------------------------------------------------------------------------
668
669
670 def _make_source_item(source, item_id, url, author=None, body=""):
671 return schema.SourceItem(
672 item_id=item_id, source=source, title=f"Item {item_id}", body=body, url=url, author=author,
673 )
674
675
676 def _make_plan(topic):
677 return schema.QueryPlan(
678 intent="exploration", freshness_mode="balanced_recent", cluster_mode="topic",
679 raw_topic=topic,
680 subqueries=[schema.SubQuery(
681 label="primary", search_query=topic,
682 ranking_query=f"What recent evidence matters for {topic}?", sources=["x"],
683 )],
684 source_weights={"x": 1.0},
685 )
686
687
688 class TestPipelineWiring:
689 def test_chain_xapi_yields_primary_xapi_and_runs_both_lanes(self):
690 bundle = schema.RetrievalBundle()
691 bundle.items_by_source["x"] = [
692 _make_source_item("x", "X1", "https://x.com/analyst1/status/1", author="analyst1", body="AI safety analysis"),
693 _make_source_item("x", "X2", "https://x.com/analyst1/status/2", author="analyst1", body="AI safety research"),
694 ]
695 from_items = [{
696 "id": "XF1", "text": "from analyst1", "url": "https://x.com/analyst1/status/777",
697 "author_handle": "analyst1", "date": "2026-03-15",
698 "engagement": {"likes": 30}, "relevance": 0.8, "why_relevant": "",
699 }]
700 runtime = schema.ProviderRuntime(
701 reasoning_provider="mock", planner_model="mock", rerank_model="mock", x_search_backend=None,
702 )
703 with mock.patch("lib.env.x_backend_chain", return_value=["xapi"]), \
704 mock.patch("lib.entity_extract.extract_entities",
705 return_value={"x_handles": ["analyst1"], "x_hashtags": [], "reddit_subreddits": []}), \
706 mock.patch("lib.x_api.search_handles", return_value=from_items) as from_lane, \
707 mock.patch("lib.x_api.search_mentions", return_value=[]) as about_lane, \
708 mock.patch("lib.bird_x.search_handles") as bird_lane, \
709 mock.patch("lib.xquik.search_handles") as xquik_lane:
710 pipeline._run_supplemental_searches(
711 topic="AI safety", bundle=bundle, plan=_make_plan("AI safety"),
712 config={"X_BEARER_TOKEN": DUMMY_TOKEN}, depth="default",
713 date_range=("2026-02-15", "2026-03-17"), runtime=runtime, mock=False,
714 rate_limited_sources=set(), rate_limit_lock=threading.Lock(),
715 )
716 from_lane.assert_called_once()
717 about_lane.assert_called_once()
718 assert from_lane.call_args.kwargs["token"] == DUMMY_TOKEN
719 assert about_lane.call_args.kwargs["token"] == DUMMY_TOKEN
720 bird_lane.assert_not_called()
721 xquik_lane.assert_not_called()
722 x_urls = {item.url for item in bundle.items_by_source.get("x", [])}
723 assert "https://x.com/analyst1/status/777" in x_urls
724
725 def test_xapi_lanes_share_one_deadline(self):
726 """Explicit-from, extracted-from, about, and related lanes must draw
727 on one wall-clock budget, never a fresh 90s each (review finding)."""
728 bundle = schema.RetrievalBundle()
729 bundle.items_by_source["x"] = [
730 _make_source_item("x", "X1", "https://x.com/analyst1/status/1", author="analyst1", body="AI safety analysis"),
731 ]
732 runtime = schema.ProviderRuntime(
733 reasoning_provider="mock", planner_model="mock", rerank_model="mock", x_search_backend=None,
734 )
735 with mock.patch("lib.env.x_backend_chain", return_value=["xapi"]), \
736 mock.patch("lib.entity_extract.extract_entities",
737 return_value={"x_handles": ["analyst1"], "x_hashtags": [], "reddit_subreddits": []}), \
738 mock.patch("lib.x_api.search_handles", return_value=[]) as from_lane, \
739 mock.patch("lib.x_api.search_mentions", return_value=[]) as about_lane:
740 pipeline._run_supplemental_searches(
741 topic="AI safety", bundle=bundle, plan=_make_plan("AI safety"),
742 config={"X_BEARER_TOKEN": DUMMY_TOKEN}, depth="default",
743 date_range=("2026-02-15", "2026-03-17"), runtime=runtime, mock=False,
744 rate_limited_sources=set(), rate_limit_lock=threading.Lock(),
745 x_handle="steipete", x_related=["peer1"],
746 )
747 calls = from_lane.call_args_list + about_lane.call_args_list
748 assert len(calls) >= 3, "explicit from, extracted from, about, related"
749 deadlines = {c.kwargs.get("deadline") for c in calls}
750 assert len(deadlines) == 1 and None not in deadlines, deadlines
751
752 def test_xapi_lane_deadline_stop_reaches_report_warnings(self):
753 """A lane cut short by the deadline is reported as partial coverage,
754 not presented as complete (review finding)."""
755 bundle = schema.RetrievalBundle()
756 bundle.items_by_source["x"] = [
757 _make_source_item("x", "X1", "https://x.com/analyst1/status/1", author="analyst1", body="AI safety analysis"),
758 ]
759 runtime = schema.ProviderRuntime(
760 reasoning_provider="mock", planner_model="mock", rerank_model="mock", x_search_backend=None,
761 )
762
763 def cut_short(*args, **kwargs):
764 kwargs["warnings"].append(x_api.DEADLINE_DETAIL)
765 return []
766
767 with mock.patch("lib.env.x_backend_chain", return_value=["xapi"]), \
768 mock.patch("lib.entity_extract.extract_entities",
769 return_value={"x_handles": [], "x_hashtags": [], "reddit_subreddits": []}), \
770 mock.patch("lib.x_api.search_handles", side_effect=cut_short), \
771 mock.patch("lib.x_api.search_mentions", side_effect=cut_short):
772 pipeline._run_supplemental_searches(
773 topic="AI safety", bundle=bundle, plan=_make_plan("AI safety"),
774 config={"X_BEARER_TOKEN": DUMMY_TOKEN}, depth="default",
775 date_range=("2026-02-15", "2026-03-17"), runtime=runtime, mock=False,
776 rate_limited_sources=set(), rate_limit_lock=threading.Lock(),
777 x_handle="steipete",
778 )
779 receipts = [w for w in bundle.artifacts.get("x_partial_coverage", []) if x_api.DEADLINE_DETAIL in w]
780 assert receipts == [f"X handle lanes: {x_api.DEADLINE_DETAIL}"], bundle.artifacts.get("x_partial_coverage")
781
782 def test_lane_search_past_a_shared_deadline_sends_no_request(self, get_mock, fixed_now, monkeypatch):
783 monkeypatch.setattr(x_api.time, "monotonic", lambda: 1000.0)
784 notes: list[str] = []
785 assert x_api.search_handles(["steipete", "peer1"], "t", FROM, TO, token=DUMMY_TOKEN, deadline=999.0, warnings=notes) == []
786 assert x_api.search_mentions(["steipete"], FROM, TO, token=DUMMY_TOKEN, deadline=999.0, warnings=notes) == []
787 get_mock.assert_not_called()
788 assert notes == [x_api.DEADLINE_DETAIL], "one receipt per lane call, deduped across handles"
789 get_mock.return_value = _v2([_tweet("1", "hi")], users=_users(("u1", "steipete")))
790 assert len(x_api.search_handles(["steipete"], "t", FROM, TO, token=DUMMY_TOKEN, deadline=1001.0)) == 1
791
792 def test_all_backends_failed_keeps_the_payment_required_state(self):
793 """xapi's 402 must not be masked by a later backend's generic failure:
794 the outcome that reaches doctor says top up, not re-authenticate."""
795 plan = {
796 "intent": "general", "freshness_mode": "balanced_recent", "cluster_mode": "story",
797 "subqueries": [{
798 "label": "primary", "search_query": "topic",
799 "ranking_query": "What are people saying about topic?", "sources": ["x"],
800 }],
801 "source_weights": {"x": 1.0},
802 }
803 answers = iter([
804 ([], x_api.ERR_PAYMENT_REQUIRED),
805 ([], "request failed (HTTPError)"),
806 ])
807 with mock.patch("lib.env.x_backend_chain", return_value=["xapi", "xai"]), \
808 mock.patch("lib.pipeline._fetch_x_backend", side_effect=lambda *a, **k: next(answers)):
809 report = pipeline.run(
810 topic="topic", config={"X_BEARER_TOKEN": DUMMY_TOKEN, "XAI_API_KEY": "dummy-xai"},
811 depth="quick", requested_sources=["x"], mock=False,
812 external_plan=plan, web_backend="none", save_dir="",
813 )
814 assert report.source_status["x"].state == health.PAYMENT_REQUIRED
815 assert "payment required" in report.source_status["x"].detail
816
817 def test_fetch_x_backend_registers_xapi(self, get_mock, fixed_now):
818 get_mock.return_value = _v2([_tweet("1", "hello topic")], users=_users(("u1", "a")))
819 items, err = pipeline._fetch_x_backend(
820 "xapi", "topic", FROM, TO, "quick", {"X_BEARER_TOKEN": DUMMY_TOKEN},
821 )
822 assert err == ""
823 assert [i["id"] for i in items] == ["XAPI1"]
824 assert get_mock.call_args.kwargs["headers"]["Authorization"] == f"Bearer {DUMMY_TOKEN}"
825
826 def test_fetch_x_backend_surfaces_truncation_warning(self, get_mock, fixed_now):
827 get_mock.side_effect = [
828 _http_error(403, body="client-not-enrolled"),
829 _v2([_tweet("1", "hello topic", created_at="2026-09-05T00:00:00Z")]),
830 ]
831 warnings: list[str] = []
832 items, err = pipeline._fetch_x_backend(
833 "xapi", "topic", FROM, TO, "quick", {"X_BEARER_TOKEN": DUMMY_TOKEN}, warnings=warnings,
834 )
835 assert err == "" and len(items) == 1
836 assert warnings and "window truncated to 7 days" in warnings[0]
837
838 def test_truncation_receipt_reaches_the_stream_artifact(self, get_mock, fixed_now):
839 get_mock.side_effect = [
840 _http_error(403, body="client-not-enrolled"),
841 _v2([_tweet("1", "hello topic", created_at="2026-09-05T00:00:00Z")]),
842 ]
843 sq = schema.SubQuery(label="primary", search_query="q", ranking_query="q?", sources=["x"])
844 runtime = schema.ProviderRuntime(
845 reasoning_provider="mock", planner_model="mock", rerank_model="mock", x_search_backend=None,
846 )
847
848 def run():
849 with mock.patch("lib.env.x_backend_chain", return_value=["xapi"]):
850 return pipeline._retrieve_stream(
851 topic="q", subquery=sq, source="x", config={"X_BEARER_TOKEN": DUMMY_TOKEN},
852 depth="quick", date_range=(FROM, TO), runtime=runtime, mock=False,
853 )
854
855 (items, artifact), stderr = _run_capturing_stderr(run)
856 assert len(items) == 1
857 assert artifact["x_receipts"] == ["X: xapi window truncated to 7 days"]
858 assert "window truncated to 7 days" in stderr
859
860 def test_failover_stderr_line_names_xapi_and_credits(self):
861 sq = schema.SubQuery(label="primary", search_query="q", ranking_query="q?", sources=["x"])
862 runtime = schema.ProviderRuntime(
863 reasoning_provider="mock", planner_model="mock", rerank_model="mock", x_search_backend=None,
864 )
865 good = [{"id": "XAPI1", "text": "t", "url": "https://x.com/a/status/1", "author_handle": "a",
866 "date": "2026-08-20", "engagement": None, "relevance": 0.5, "why_relevant": ""}]
867
868 def fetch(backend, *_args, **_kwargs):
869 return (good, "") if backend == "xapi" else ([], "")
870
871 def run():
872 with mock.patch("lib.env.x_backend_chain", return_value=["xai", "xapi"]), \
873 mock.patch("lib.pipeline._fetch_x_backend", side_effect=fetch):
874 return pipeline._retrieve_stream(
875 topic="q", subquery=sq, source="x", config={"X_BEARER_TOKEN": DUMMY_TOKEN},
876 depth="quick", date_range=(FROM, TO), runtime=runtime, mock=False,
877 )
878
879 (items, _artifact), stderr = _run_capturing_stderr(run)
880 assert len(items) == 1
881 assert "used fallback 'xapi'" in stderr
882 assert "X API credits" in stderr
883
884
885 # ---------------------------------------------------------------------------
886 # Fixture redaction at both seams (R8)
887 # ---------------------------------------------------------------------------
888
889
890 def _urlopen_response(body: str):
891 response = MagicMock()
892 response.__enter__.return_value = response
893 response.__exit__.return_value = False
894 response.read.return_value = body.encode("utf-8")
895 response.status = 200
896 return response
897
898
899 def test_fixture_redacts_bearer_loaded_only_from_env_file(tmp_path, monkeypatch):
900 env_file = tmp_path / ".env"
901 env_file.write_text(f"X_BEARER_TOKEN={DUMMY_TOKEN}\n", encoding="utf-8")
902 env_file.chmod(0o600)
903 monkeypatch.setattr(env, "CONFIG_FILE", env_file)
904 monkeypatch.delenv("X_BEARER_TOKEN", raising=False)
905 monkeypatch.setenv("LAST30DAYS_SKIP_KEYCHAIN", "1")
906 monkeypatch.setattr(env, "_load_pass", lambda *a, **k: {})
907 monkeypatch.setattr(env, "_find_project_env", lambda: None)
908 monkeypatch.setattr(
909 http.urllib.request, "urlopen",
910 lambda *_a, **_k: _urlopen_response(json.dumps({"detail": f"token {DUMMY_TOKEN} rejected"})),
911 )
912 fixture_dir = tmp_path / "fixture"
913
914 with http.recording_requests(fixture_dir):
915 config = env.get_config()
916 assert config["X_BEARER_TOKEN"] == DUMMY_TOKEN
917 http.get(
918 "https://api.x.com/2/tweets/search/all",
919 headers={"Authorization": f"Bearer {DUMMY_TOKEN}"},
920 params={"query": "topic"},
921 )
922 http.fixture_source_record(
923 {"source": "x", "topic": "t", "search_query": "t", "date_range": [FROM, TO], "depth": "quick"},
924 [[{"text": f"echo {DUMMY_TOKEN}"}], {}],
925 )
926
927 payload = json.loads((fixture_dir / "http.json").read_text(encoding="utf-8"))
928 text = json.dumps(payload)
929 assert DUMMY_TOKEN not in text
930 assert "<redacted>" in json.dumps(payload["exchanges"])
931 assert "<redacted>" in json.dumps(payload["source_exchanges"])
932
933
934 def test_http_seam_redacts_bare_bearer_without_any_config(tmp_path, monkeypatch):
935 monkeypatch.delenv("X_BEARER_TOKEN", raising=False)
936 monkeypatch.setattr(
937 http.urllib.request, "urlopen",
938 lambda *_a, **_k: _urlopen_response(json.dumps({"echo": DUMMY_TOKEN})),
939 )
940 fixture_dir = tmp_path / "fixture"
941 with http.recording_requests(fixture_dir):
942 http.get("https://api.x.com/2/tweets/search/all", headers={"Authorization": f"Bearer {DUMMY_TOKEN}"})
943 text = (fixture_dir / "http.json").read_text(encoding="utf-8")
944 assert DUMMY_TOKEN not in text
945 assert '"echo": "<redacted>"' in text
946
947
948 # ---------------------------------------------------------------------------
949 # xurl fixed strings (same rule as xapi)
950 # ---------------------------------------------------------------------------
951
952
953 class TestXurlFixedStrings:
954 def _run(self, returncode, stderr="", stdout=""):
955 completed = mock.Mock(returncode=returncode, stdout=stdout, stderr=stderr)
956 with mock.patch("subprocess.run", return_value=completed):
957 return xurl_x.search_x("test")
958
959 def test_rate_limited_stderr_with_token_maps_to_fixed_string(self):
960 result = self._run(1, stderr=f"429 rate limit exceeded for {DUMMY_TOKEN} ({ACCOUNT_ID})")
961 assert result["error"] == xurl_x.ERR_RATE_LIMITED
962 assert DUMMY_TOKEN not in result["error"] and ACCOUNT_ID not in result["error"]
963 assert http.classify_failure(message=result["error"]) == health.RATE_LIMITED
964
965 @pytest.mark.parametrize("stderr,expected,state", [
966 ("401 Unauthorized", "ERR_UNAUTHORIZED", health.AUTH_FAILED),
967 ("403 Forbidden: client-not-enrolled", "ERR_FORBIDDEN", health.AUTH_FAILED),
968 ("402 Payment Required", "ERR_PAYMENT_REQUIRED", health.PAYMENT_REQUIRED),
969 ("400 Invalid Request: Ambiguous use of and", "ERR_INVALID_REQUEST", health.ERROR),
970 ("something else entirely", "ERR_FAILED", health.ERROR),
971 ])
972 def test_status_words_map_to_fixed_strings(self, stderr, expected, state):
973 result = self._run(1, stderr=f"{stderr} {DUMMY_TOKEN}")
974 assert result["error"] == getattr(xurl_x, expected)
975 assert DUMMY_TOKEN not in result["error"]
976 assert http.classify_failure(message=result["error"]) == state
977
978 def test_invalid_json_is_fixed_string(self):
979 result = self._run(0, stdout=f"NOT JSON {DUMMY_TOKEN}")
980 assert result["error"] == xurl_x.ERR_INVALID_JSON
981 assert DUMMY_TOKEN not in result["error"]
982
982 lines PYTHON