返回 last30days-skill
test_web_search_keyless.py
根目录 / tests / test_web_search_keyless.py
1 """Tests for scripts/lib/web_search_keyless.py — keyless web search floor."""
2
3 import datetime as _dt
4 from pathlib import Path
5 from unittest import mock
6
7 import pytest
8
9 from lib import health, http, web_search_keyless
10
11 _DDG_HTML = """
12 <div class="result">
13 <a rel="nofollow" class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com%2Fpost&amp;rut=x">First &amp; Best</a>
14 <a class="result__snippet" href="//x">A snippet about the <b>topic</b>.</a>
15 </div>
16 <div class="result">
17 <a rel="nofollow" class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fnews.example.org%2Fa">Second result</a>
18 <a class="result__snippet" href="//y">Second snippet.</a>
19 </div>
20 """
21
22
23 class TestKeylessSearch:
24 def test_ddg_parsing_happy_path(self):
25 with mock.patch.object(web_search_keyless.http, "get_text", return_value=_DDG_HTML):
26 items, artifact = web_search_keyless.keyless_search(
27 "topic", ("2026-02-25", "2026-03-27"), {})
28 assert len(items) == 2
29 assert items[0]["url"] == "https://example.com/post"
30 assert items[0]["title"] == "First & Best"
31 assert items[0]["source_domain"] == "example.com"
32 assert "snippet about the topic" in items[0]["snippet"]
33 assert artifact["keyless_backend"] == "ddg"
34 # Floor relevance is below the paid backends' 0.8.
35 assert items[0]["relevance"] < 0.8
36
37 def test_item_shape_matches_grounding_backends(self):
38 with mock.patch.object(web_search_keyless.http, "get_text", return_value=_DDG_HTML):
39 items, _ = web_search_keyless.keyless_search("topic", ("2026-02-25", "2026-03-27"), {})
40 required = {"id", "title", "url", "source_domain", "snippet", "date", "relevance", "why_relevant"}
41 assert required.issubset(items[0].keys())
42
43 def test_current_window_tags_undated_items_for_normalize(self):
44 with mock.patch.object(web_search_keyless.http, "get_text", return_value=_DDG_HTML):
45 items, _ = web_search_keyless.keyless_search("topic", ("2026-02-25", "2999-12-31"), {})
46 assert all(item["metadata"] == {"date_window_basis": "keyless_current"} for item in items)
47
48 def test_historical_window_leaves_items_untagged(self):
49 with mock.patch.object(web_search_keyless.http, "get_text", return_value=_DDG_HTML):
50 items, _ = web_search_keyless.keyless_search("topic", ("2020-01-01", "2020-01-31"), {})
51 assert items and all("metadata" not in item for item in items)
52
53 def test_count_cap(self):
54 with mock.patch.object(web_search_keyless.http, "get_text", return_value=_DDG_HTML):
55 items, _ = web_search_keyless.keyless_search("topic", ("2026-02-25", "2026-03-27"), {}, count=1)
56 assert len(items) == 1
57
58 def test_ddg_down_no_searxng_returns_degraded(self):
59 with mock.patch.object(web_search_keyless.http, "get_text", return_value=None):
60 items, artifact = web_search_keyless.keyless_search("topic", ("2026-02-25", "2026-03-27"), {})
61 assert items == []
62 assert artifact["reason"] == "keyless-search-unavailable"
63
64 def test_searxng_fallback_when_ddg_empty(self):
65 searxng_payload = {"results": [
66 {"url": "https://searxng.example/a", "title": "SX A", "content": "sx snippet"},
67 ]}
68 with mock.patch.object(web_search_keyless.http, "get_text", return_value=None), \
69 mock.patch.object(web_search_keyless.http, "get", return_value=searxng_payload):
70 items, artifact = web_search_keyless.keyless_search(
71 "topic", ("2026-02-25", "2026-03-27"),
72 {"LAST30DAYS_SEARXNG_URL": "https://searxng.example"})
73 assert len(items) == 1
74 assert items[0]["url"] == "https://searxng.example/a"
75 assert artifact["keyless_backend"] == "searxng"
76
77 @staticmethod
78 def _thread_only(item):
79 return "reddit.com/r/" in item["url"]
80
81 def test_searxng_filter_runs_before_the_result_cap(self):
82 junk = [{"url": f"https://example.com/{i}", "title": "x", "content": "x"} for i in range(30)]
83 threads = [
84 {"url": f"https://www.reddit.com/r/LocalLLaMA/comments/t{i}/", "title": "t", "content": "t"}
85 for i in range(3)
86 ]
87 with mock.patch.object(web_search_keyless.http, "get_text", return_value=""), \
88 mock.patch.object(web_search_keyless.http, "get", return_value={"results": junk + threads}):
89 items, artifact = web_search_keyless.keyless_search(
90 "site:reddit.com topic", ("2026-02-25", "2026-03-27"),
91 {"LAST30DAYS_SEARXNG_URL": "https://searxng.example"},
92 count=2, accept_result=self._thread_only,
93 )
94 # The first 30 links are not threads, yet the threads that follow are kept, in order, up to the cap.
95 assert [item["url"] for item in items] == [t["url"] for t in threads[:2]]
96 assert artifact["keyless_backend"] == "searxng"
97
98 def test_searxng_scan_stays_bounded_when_nothing_is_accepted(self):
99 junk = [{"url": f"https://example.com/{i}", "title": "x", "content": "x"} for i in range(400)]
100 late = {"url": "https://www.reddit.com/r/LocalLLaMA/comments/late/", "title": "t", "content": "t"}
101 with mock.patch.object(web_search_keyless.http, "get_text", return_value=""), \
102 mock.patch.object(web_search_keyless.http, "get", return_value={"results": junk + [late]}):
103 items, _ = web_search_keyless.keyless_search(
104 "site:reddit.com topic", ("2026-02-25", "2026-03-27"),
105 {"LAST30DAYS_SEARXNG_URL": "https://searxng.example"},
106 count=5, accept_result=self._thread_only,
107 )
108 assert items == []
109
110 @pytest.mark.parametrize("failure, state", [
111 (http.HTTPError("HTTP 403: refused", 403), "blocked"),
112 (http.HTTPError("HTTP 429: slow down", 429), "throttled"),
113 (http.HTTPError("HTTP 500: broken", 500), "error"),
114 (http.DeadlineExceeded(), "timeout"),
115 ])
116 def test_searxng_failure_is_reported_on_its_own_rung(self, failure, state):
117 def fail(*args, **kwargs):
118 http._record_failure(failure)
119 raise failure
120
121 with mock.patch.object(web_search_keyless.http, "get_text", return_value=""), \
122 mock.patch.object(web_search_keyless.http, "get", side_effect=fail):
123 items, artifact = web_search_keyless.keyless_search(
124 "site:reddit.com topic", ("2026-02-25", "2026-03-27"),
125 {"LAST30DAYS_SEARXNG_URL": "https://searxng.example"},
126 accept_result=self._thread_only,
127 )
128 assert items == []
129 assert artifact["keyless_searxng"] == state
130 # The HTML rungs keep their own states and the rung map stays HTML-only.
131 assert "searxng" not in artifact["keyless_rungs"]
132 assert all(artifact["keyless_rungs"][rung] == "empty" for rung in web_search_keyless.RUNGS)
133
134 def test_ordinary_http_timeout_is_a_searxng_timeout_but_not_a_run_cutoff(self):
135 failure = http.HTTPError("request timed out", outcome_state=health.TIMEOUT)
136 with mock.patch.object(web_search_keyless.http, "get_text", return_value=""), mock.patch.object(web_search_keyless.http, "get", side_effect=failure):
137 items, artifact = web_search_keyless.keyless_search(
138 "site:reddit.com topic", ("2026-02-25", "2026-03-27"),
139 {"LAST30DAYS_SEARXNG_URL": "https://searxng.example"},
140 )
141 assert items == [] and artifact["keyless_searxng"] == "timeout"
142 # Only the shared deadline ends the run, so this stays an ordinary unavailable result.
143 assert artifact["reason"] == "keyless-search-unavailable"
144 assert "_source_outcome" not in artifact
145
146 @pytest.mark.parametrize("status, state", [(403, "blocked"), (429, "throttled")])
147 def test_refusal_statuses_win_over_a_timeout_outcome(self, status, state):
148 failure = http.HTTPError(f"HTTP {status}", status, outcome_state=health.TIMEOUT)
149 with mock.patch.object(web_search_keyless.http, "get_text", return_value=""), mock.patch.object(web_search_keyless.http, "get", side_effect=failure):
150 _, artifact = web_search_keyless.keyless_search(
151 "topic", ("2026-02-25", "2026-03-27"),
152 {"LAST30DAYS_SEARXNG_URL": "https://searxng.example"},
153 )
154 assert artifact["keyless_searxng"] == state
155
156 def test_searxng_clean_miss_is_reported_as_empty(self):
157 with mock.patch.object(web_search_keyless.http, "get_text", return_value=""), \
158 mock.patch.object(web_search_keyless.http, "get", return_value={"results": []}):
159 items, artifact = web_search_keyless.keyless_search(
160 "site:reddit.com topic", ("2026-02-25", "2026-03-27"),
161 {"LAST30DAYS_SEARXNG_URL": "https://searxng.example"},
162 )
163 assert items == [] and artifact["keyless_searxng"] == "empty"
164 assert "searxng" not in artifact["keyless_rungs"]
165
166 def test_searxng_rung_never_enters_the_shared_rung_health(self):
167 with mock.patch.object(web_search_keyless.http, "get_text", return_value=""), \
168 mock.patch.object(web_search_keyless.http, "get",
169 side_effect=http.HTTPError("HTTP 403: refused", 403)):
170 web_search_keyless.keyless_search(
171 "topic", ("2026-02-25", "2026-03-27"),
172 {"LAST30DAYS_SEARXNG_URL": "https://searxng.example"},
173 )
174 assert "searxng" not in web_search_keyless.rung_health()
175
176 def test_skips_non_http_results(self):
177 html = '<a class="result__a" href="//duckduckgo.com/l/?uddg=javascript%3Avoid(0)">bad</a>'
178 with mock.patch.object(web_search_keyless.http, "get_text", return_value=html):
179 items, _ = web_search_keyless.keyless_search("topic", ("2026-02-25", "2026-03-27"), {})
180 assert items == []
181
182
183 # Startpage marks each hit with an <a class="result-title result-link …"> whose
184 # href is the target and whose <h2> is the title; the emotion <style> block
185 # (inline CSS) must never leak into the parsed title. Description follows in a
186 # <p class="…description…">.
187 _STARTPAGE_HTML = """
188 <a class="result-title result-link css-1bggj8v" href="https://example.com/post" data-testid="gl-title-link">
189 <style data-emotion="css i3irj7">.css-i3irj7{line-height:18px;color:#2E39B3;}</style>
190 <h2 class="wgl-title css-i3irj7">First &amp; Best Result</h2>
191 </a>
192 <p class="description css-abc">A snippet about the topic.</p>
193 <a class="result-title result-link css-1bggj8v" href="https://news.example.org/a" data-testid="gl-title-link">
194 <h2 class="wgl-title css-i3irj7">Second result</h2>
195 </a>
196 <p class="description css-abc">Second snippet.</p>
197 """
198
199
200 class TestStartpageFallback:
201 def _get_text(self, startpage_html):
202 # DuckDuckGo yields nothing (its datacenter-IP 202 challenge page has no
203 # result anchors); Startpage yields real results.
204 def side_effect(url, *args, **kwargs):
205 return startpage_html if "startpage.com" in url else ""
206 return side_effect
207
208 def test_startpage_used_when_ddg_empty(self):
209 with mock.patch.object(
210 web_search_keyless.http, "get_text",
211 side_effect=self._get_text(_STARTPAGE_HTML),
212 ):
213 items, artifact = web_search_keyless.keyless_search(
214 "topic", ("2026-02-25", "2026-03-27"), {})
215 assert artifact["keyless_backend"] == "startpage"
216 assert artifact.get("reason") is None
217 assert len(items) == 2
218 assert items[0]["url"] == "https://example.com/post"
219 # The inline <style> CSS must not bleed into the title.
220 assert items[0]["title"] == "First & Best Result"
221 assert "css-" not in items[0]["title"]
222 assert items[0]["snippet"] == "A snippet about the topic."
223 assert items[0]["source_domain"] == "example.com"
224
225 def test_ddg_preferred_over_startpage(self):
226 # When DuckDuckGo returns results, Startpage is not consulted.
227 with mock.patch.object(web_search_keyless.http, "get_text", return_value=_DDG_HTML):
228 _, artifact = web_search_keyless.keyless_search(
229 "topic", ("2026-02-25", "2026-03-27"), {})
230 assert artifact["keyless_backend"] == "ddg"
231
232
233 class TestStripHtml:
234 def test_strips_style_block_contents(self):
235 got = web_search_keyless._strip_html(
236 "<style>.a{color:red}</style><h2>Title</h2>")
237 assert got == "Title"
238
239
240 # --- Brave HTML rung -------------------------------------------------------
241
242 _BRAVE_FIXTURE = (
243 Path(__file__).resolve().parent.parent / "fixtures" / "brave_reddit_serp.html"
244 ).read_text(encoding="utf-8")
245 _REDDIT_QUERY = "site:reddit.com kanye west"
246 _WINDOW = ("2026-10-16", "2026-11-15")
247
248
249 @pytest.fixture(autouse=True)
250 def _fresh_rung_health():
251 web_search_keyless.reset_rung_health()
252 yield
253 web_search_keyless.reset_rung_health()
254
255
256 def _failing(status):
257 """A get_text stand-in that fails the way the transport does: the
258 HTTPError reaches the failure sink and the call returns None."""
259 def fail():
260 http._record_failure(http.HTTPError(f"HTTP {status}", status))
261 return None
262 return fail
263
264
265 def _by_host(brave=None, ddg="", startpage=""):
266 """Route get_text by host; a callable answers for its rung."""
267 calls = []
268
269 def side_effect(url, *args, **kwargs):
270 calls.append(url)
271 for host, answer in (("search.brave.com", brave), ("duckduckgo.com", ddg),
272 ("startpage.com", startpage)):
273 if host in url:
274 return answer() if callable(answer) else answer
275 raise AssertionError(f"unexpected url {url}")
276 return side_effect, calls
277
278
279 class TestBraveParse:
280 def test_captured_serp_yields_dated_reddit_results(self):
281 now = _dt.datetime(2026, 11, 15, tzinfo=_dt.timezone.utc)
282 items = web_search_keyless.parse_brave(_BRAVE_FIXTURE, 50, now=now)
283 urls = [i["url"] for i in items]
284 assert len(items) >= 10
285 assert "https://www.reddit.com/r/Kanye/comments/1xattdz/debunked_north_west_is_not_pregnant_with_ken/" in urls
286 # Each web result is read once: the inline comment cards under a result
287 # repeat its link and are not results of their own.
288 assert len(urls) == len(set(urls))
289 first = next(i for i in items if "1xattdz" in i["url"])
290 assert first["title"].endswith(
291 "Debunked: North West is not pregnant with Ken Carson’s baby and they never dated")
292 assert "Kanye's daughter" in first["snippet"]
293 # "1 month ago" on the capture day.
294 assert first["date"] == "2026-10-16"
295 assert first["source_domain"] == "www.reddit.com"
296
297 def test_count_caps_results(self):
298 assert len(web_search_keyless.parse_brave(_BRAVE_FIXTURE, 3)) == 3
299
300 def test_page_with_no_results_parses_empty(self):
301 assert web_search_keyless.parse_brave("<html><body>nothing</body></html>", 10) == []
302
303
304 class TestBraveRung:
305 def test_reddit_query_tries_brave_first(self):
306 side_effect, calls = _by_host(brave=_BRAVE_FIXTURE, ddg=_DDG_HTML)
307 with mock.patch.object(web_search_keyless.http, "get_text", side_effect=side_effect):
308 items, artifact = web_search_keyless.keyless_search(
309 _REDDIT_QUERY, _WINDOW, {}, count=20)
310 assert artifact["keyless_backend"] == "brave"
311 assert all("search.brave.com" in url for url in calls)
312 assert items and all("reddit.com" in i["url"] for i in items)
313 assert artifact["keyless_rungs"] == {"brave": "ok"}
314
315 def test_other_queries_never_use_brave(self):
316 side_effect, calls = _by_host(brave=_BRAVE_FIXTURE, ddg=_DDG_HTML)
317 with mock.patch.object(web_search_keyless.http, "get_text", side_effect=side_effect):
318 _, artifact = web_search_keyless.keyless_search("kanye west", _WINDOW, {})
319 assert artifact["keyless_backend"] == "ddg"
320 assert not any("brave" in url for url in calls)
321
322 def test_month_freshness_reaches_every_rung(self):
323 side_effect, calls = _by_host(brave="", ddg="", startpage="")
324 with mock.patch.object(web_search_keyless.http, "get_text", side_effect=side_effect):
325 web_search_keyless.keyless_search(_REDDIT_QUERY, _WINDOW, {}, freshness="month")
326 brave, ddg, startpage = calls
327 assert "tf=pm" in brave
328 assert "df=m" in ddg
329 assert "with_date=m" in startpage
330
331 def test_brave_429_falls_through_to_ddg_then_startpage(self):
332 side_effect, calls = _by_host(brave=_failing(429), ddg="", startpage=_STARTPAGE_HTML)
333 with mock.patch.object(web_search_keyless.http, "get_text", side_effect=side_effect):
334 items, artifact = web_search_keyless.keyless_search(_REDDIT_QUERY, _WINDOW, {})
335 assert [u.split("/")[2] for u in calls] == [
336 "search.brave.com", "html.duckduckgo.com", "www.startpage.com"]
337 assert artifact["keyless_backend"] == "startpage"
338 assert items
339 assert artifact["keyless_rungs"] == {
340 "brave": "throttled", "ddg": "empty", "startpage": "ok"}
341 assert web_search_keyless.rung_health()["brave"] == "throttled"
342
343 def test_brave_403_skips_brave_for_the_rest_of_the_run(self):
344 side_effect, calls = _by_host(brave=_failing(403), ddg=_DDG_HTML)
345 with mock.patch.object(web_search_keyless.http, "get_text", side_effect=side_effect):
346 web_search_keyless.keyless_search(_REDDIT_QUERY, _WINDOW, {})
347 calls.clear()
348 _, artifact = web_search_keyless.keyless_search(
349 "site:reddit.com another topic", _WINDOW, {})
350 assert not any("brave" in url for url in calls)
351 assert artifact["keyless_backend"] == "ddg"
352 assert artifact["keyless_rungs"]["brave"] == "skipped"
353 assert web_search_keyless.rung_health()["brave"] == "blocked"
354
355 def test_seeded_brave_skip_goes_straight_to_ddg_and_startpage(self):
356 # The seam a persisted health cache seeds at run start.
357 web_search_keyless.seed_rung_health({"brave": "blocked"})
358 side_effect, calls = _by_host(brave=_BRAVE_FIXTURE, ddg="", startpage=_STARTPAGE_HTML)
359 with mock.patch.object(web_search_keyless.http, "get_text", side_effect=side_effect):
360 _, artifact = web_search_keyless.keyless_search(_REDDIT_QUERY, _WINDOW, {})
361 assert [u.split("/")[2] for u in calls] == ["html.duckduckgo.com", "www.startpage.com"]
362 assert artifact["keyless_rungs"]["brave"] == "skipped"
363
364 def test_one_failed_page_does_not_skip_a_rung(self):
365 side_effect, calls = _by_host(brave=_failing(500), ddg=_DDG_HTML)
366 with mock.patch.object(web_search_keyless.http, "get_text", side_effect=side_effect):
367 web_search_keyless.keyless_search(_REDDIT_QUERY, _WINDOW, {})
368 calls.clear()
369 web_search_keyless.keyless_search(_REDDIT_QUERY, _WINDOW, {})
370 assert any("brave" in url for url in calls)
371 assert web_search_keyless.rung_health()["brave"] == "error"
372
373 def test_ddg_challenge_page_counts_as_throttled(self):
374 challenge = '<div class="anomaly-modal__title">Unfortunately, bots use DuckDuckGo too.</div>'
375 side_effect, calls = _by_host(ddg=challenge, startpage=_STARTPAGE_HTML)
376 with mock.patch.object(web_search_keyless.http, "get_text", side_effect=side_effect):
377 web_search_keyless.keyless_search("topic", _WINDOW, {})
378 calls.clear()
379 _, artifact = web_search_keyless.keyless_search("topic", _WINDOW, {})
380 assert not any("duckduckgo" in url for url in calls)
381 assert artifact["keyless_rungs"] == {"ddg": "skipped", "startpage": "ok"}
382
383 def test_startpage_proof_of_work_page_counts_as_throttled(self):
384 challenge = (
385 '"v1.26.4" {"rules":{"algorithm":"fast","difficulty":4},'
386 '"challenge":{"issuedAt":"2026-11-16T02:47:50Z","difficulty":4}}'
387 )
388 side_effect, _calls = _by_host(ddg=_DDG_HTML, startpage=challenge)
389 with mock.patch.object(web_search_keyless, "_ddg_rung", return_value=([], "empty")), \
390 mock.patch.object(web_search_keyless.http, "get_text", side_effect=side_effect):
391 web_search_keyless.keyless_search("topic", _WINDOW, {})
392 assert web_search_keyless.rung_health()["startpage"] == "throttled"
393
394 def test_rung_failures_still_reach_the_callers_sink(self):
395 side_effect, _calls = _by_host(brave=_failing(429), ddg=_DDG_HTML)
396 with http.capture_failures() as failures, \
397 mock.patch.object(web_search_keyless.http, "get_text", side_effect=side_effect):
398 web_search_keyless.keyless_search(_REDDIT_QUERY, _WINDOW, {})
399 assert [f.status_code for f in failures] == [429]
400
400 lines PYTHON