返回 last30days-skill
test_shortform_oss_window.py
根目录 / tests / test_shortform_oss_window.py
1 """Keyless TikTok/Instagram: date window, discovery freshness, creator expansion.
2
3 Every test drives the real entry points (``shortform_oss.search`` or
4 ``shortform_oss.discover_urls``) and fakes only the network boundary:
5 ``lib.http.request`` / ``lib.http.get`` for web discovery and
6 ``lib.subproc.run_with_timeout`` for yt-dlp.
7 """
8
9 from __future__ import annotations
10
11 import json
12 import os
13 import threading
14 from datetime import datetime, timedelta, timezone
15 from pathlib import Path
16 from types import SimpleNamespace
17 from unittest import mock
18 from urllib.parse import parse_qs, urlparse
19
20 import pytest
21
22 from lib import shortform_oss
23
24 FIXTURE = Path(__file__).parent / "fixtures" / "tiktok_user_flat_playlist.jsonl"
25
26 FROM, TO = "2026-11-01", "2026-11-21"
27 NATIVE = {"LAST30DAYS_NATIVE_SEARCH": "1"} # keeps the keyless floor out of the way
28 _IG_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
29
30
31 def _unix(day: str) -> int:
32 return int(datetime.strptime(day, "%Y-%m-%d").replace(
33 hour=12, tzinfo=timezone.utc).timestamp())
34
35
36 def tt_id(day: str, low: int = 12345) -> str:
37 return str((_unix(day) << 32) | low)
38
39
40 def tt_url(handle: str, day: str, low: int = 12345) -> str:
41 return f"https://www.tiktok.com/@{handle}/video/{tt_id(day, low)}"
42
43
44 def ig_shortcode(day: str, low: int = 7) -> str:
45 media_id = ((_unix(day) * 1000 - 1314220021721) << 23) | low
46 out = ""
47 while media_id:
48 media_id, r = divmod(media_id, 64)
49 out = _IG_ALPHABET[r] + out
50 return out
51
52
53 def _raw(kind: str, url: str, day: str, text: str = "topic words") -> dict:
54 vid = url.rstrip("/").rsplit("/", 1)[-1]
55 return {
56 "id": vid,
57 "uploader": "u",
58 "timestamp": _unix(day),
59 "view_count": 100,
60 "like_count": 10,
61 "comment_count": 1,
62 "description": text,
63 "webpage_url": url,
64 }
65
66
67 def _listed_handle(cmd) -> str:
68 target = next(a for a in cmd if "tiktok.com/@" in a)
69 return target.rsplit("@", 1)[-1]
70
71
72 class FakeNet:
73 """Fake Serper + yt-dlp. Records every subprocess call."""
74
75 def __init__(self, links, hydrate=None, playlists=None, on_list=None):
76 self.links = links
77 self.hydrate = hydrate or {}
78 self.playlists = playlists or {}
79 self.on_list = on_list
80 self.calls = []
81 self.requests = []
82
83 def request(self, method, url, **kw):
84 self.requests.append((method, url, kw))
85 return {"organic": [{"link": u} for u in self.links]}
86
87 def run(self, cmd, timeout=None, input_text=None, **_kw):
88 self.calls.append((list(cmd), input_text))
89 if "--flat-playlist" in cmd:
90 handle = _listed_handle(cmd)
91 if self.on_list:
92 self.on_list(handle)
93 return SimpleNamespace(stdout=self.playlists.get(handle, ""))
94 lines = []
95 for url in (input_text or "").split():
96 if url in self.hydrate:
97 lines.append(json.dumps(self.hydrate[url]))
98 return SimpleNamespace(stdout="\n".join(lines))
99
100 def hydrated_urls(self):
101 out = []
102 for cmd, inp in self.calls:
103 if "--dump-json" in cmd:
104 out.extend((inp or "").split())
105 return out
106
107 def listed_handles(self):
108 return [_listed_handle(cmd) for cmd, _ in self.calls if "--flat-playlist" in cmd]
109
110
111 def _run_search(net, kind="tiktok", topic="topic words", depth="default",
112 creators=None, cancel=None, config=None, env=None):
113 cfg = {"SERPER_API_KEY": "sp", **NATIVE, **(config or {})}
114 with mock.patch("lib.youtube_yt.is_ytdlp_installed", return_value=True), \
115 mock.patch("lib.http.request", side_effect=net.request), \
116 mock.patch("lib.subproc.run_with_timeout", side_effect=net.run), \
117 mock.patch.dict(os.environ, env or {}):
118 os.environ.pop("LAST30DAYS_YOUTUBE_SSH_HOST", None)
119 return shortform_oss.search(
120 kind, topic, FROM, TO, depth, cfg, creators=creators, cancel=cancel,
121 )
122
123
124 class TestIdDates:
125 def test_tiktok_id_decodes_to_upload_day(self):
126 url = "https://www.tiktok.com/@u/video/7710481357683576094"
127 assert shortform_oss.post_date_from_url("tiktok", url) == "2026-11-21"
128
129 def test_instagram_shortcode_decodes_within_minutes_of_ytdlp_timestamp(self):
130 # yt-dlp -j on this reel reported timestamp 1793923629.
131 ts = shortform_oss.post_timestamp_from_url(
132 "instagram", "https://www.instagram.com/reel/DfYRA2ghafT/")
133 assert ts is not None
134 assert abs(ts - 1793923629) < 15 * 60
135
136 def test_undecodable_ids_return_none(self):
137 assert shortform_oss.post_date_from_url(
138 "tiktok", "https://www.tiktok.com/@u/video/123") is None
139 assert shortform_oss.post_date_from_url(
140 "instagram", "https://www.instagram.com/reel/ABCDEFGHIJKLMNOPQRST/") is None
141 assert shortform_oss.post_date_from_url("tiktok", "not a url") is None
142
143
144 class TestNoStaleLeak:
145 def test_stale_posts_are_never_kept_when_nothing_is_in_window(self):
146 # Undecodable ids reach hydration; yt-dlp then reports 2024 dates.
147 urls = [f"https://www.tiktok.com/@u/video/{n}" for n in (101, 102)]
148 net = FakeNet(urls, hydrate={u: _raw("tiktok", u, "2024-03-01") for u in urls})
149 result = _run_search(net)
150 assert result["items"] == []
151 assert "date" in result["error"]
152
153 def test_stale_ids_are_dropped_before_hydration(self):
154 fresh = tt_url("a", "2026-11-10")
155 stale = tt_url("b", "2025-06-01")
156 net = FakeNet([stale, fresh], hydrate={fresh: _raw("tiktok", fresh, "2026-11-10")})
157 result = _run_search(net)
158 assert stale not in net.hydrated_urls()
159 assert fresh in net.hydrated_urls()
160 assert [i["url"] for i in result["items"]] == [fresh]
161
162 def test_instagram_stale_shortcodes_are_dropped_before_hydration(self):
163 fresh = f"https://www.instagram.com/reel/{ig_shortcode('2026-11-10')}/"
164 stale = f"https://www.instagram.com/reel/{ig_shortcode('2025-01-10')}/"
165 net = FakeNet([stale, fresh],
166 hydrate={fresh: _raw("instagram", fresh, "2026-11-10")})
167 result = _run_search(net, kind="instagram")
168 assert net.hydrated_urls() == [fresh]
169 assert len(result["items"]) == 1
170
171 def test_only_stale_discovery_returns_zero_with_reason_and_no_hydration(self):
172 net = FakeNet([tt_url("b", "2025-06-01")])
173 result = _run_search(net)
174 assert result["items"] == []
175 assert "window" in result["error"]
176 assert net.hydrated_urls() == []
177
178
179 class TestFreshness:
180 def _discover(self, cfg, env=None, kind="tiktok"):
181 seen = {}
182
183 def fake_request(method, url, **kw):
184 seen.setdefault("request", []).append((method, url, kw))
185 return {}
186
187 def fake_get(url, **kw):
188 seen.setdefault("get", []).append(url)
189 return {"results": []}
190
191 with mock.patch("lib.http.request", side_effect=fake_request), \
192 mock.patch("lib.http.get", side_effect=fake_get), \
193 mock.patch.dict(os.environ, env or {}):
194 if env is None:
195 os.environ.pop("LAST30DAYS_SHORTFORM_FRESHNESS", None)
196 shortform_oss.discover_urls(kind, "topic", {**cfg, **NATIVE}, 5, from_date=FROM)
197 return seen
198
199 def test_serper_asks_for_past_month(self):
200 seen = self._discover({"SERPER_API_KEY": "sp"})
201 assert seen["request"][0][2]["json_data"]["tbs"] == "qdr:m"
202
203 def test_brave_asks_for_past_month(self):
204 seen = self._discover({"BRAVE_API_KEY": "br"})
205 q = parse_qs(urlparse(seen["request"][0][1]).query)
206 assert q["freshness"] == ["pm"]
207
208 def test_exa_asks_for_window_start(self):
209 seen = self._discover({"EXA_API_KEY": "ex"})
210 body = seen["request"][0][2]["json_data"]
211 assert body["startPublishedDate"].startswith(FROM)
212
213 def test_searxng_asks_for_past_month(self):
214 seen = self._discover({"LAST30DAYS_SEARXNG_URL": "https://searx.example"})
215 q = parse_qs(urlparse(seen["get"][0]).query)
216 assert q["time_range"] == ["month"]
217
218 def test_off_restores_the_unfiltered_requests(self):
219 env = {"LAST30DAYS_SHORTFORM_FRESHNESS": "off"}
220 serper = self._discover({"SERPER_API_KEY": "sp"}, env)
221 assert "tbs" not in serper["request"][0][2]["json_data"]
222 brave = self._discover({"BRAVE_API_KEY": "br"}, env)
223 q = parse_qs(urlparse(brave["request"][0][1]).query)
224 assert q["freshness"] == ["1970-01-01to2099-12-31"]
225 exa = self._discover({"EXA_API_KEY": "ex"}, env)
226 assert "startPublishedDate" not in exa["request"][0][2]["json_data"]
227 searx = self._discover({"LAST30DAYS_SEARXNG_URL": "https://searx.example"}, env)
228 assert "time_range" not in parse_qs(urlparse(searx["get"][0]).query)
229
230 def test_each_backend_switches_individually(self):
231 env = {"LAST30DAYS_SHORTFORM_FRESHNESS": "serper,exa"}
232 serper = self._discover({"SERPER_API_KEY": "sp"}, env)
233 assert serper["request"][0][2]["json_data"]["tbs"] == "qdr:m"
234 brave = self._discover({"BRAVE_API_KEY": "br"}, env)
235 q = parse_qs(urlparse(brave["request"][0][1]).query)
236 assert q["freshness"] == ["1970-01-01to2099-12-31"]
237
238 def test_search_threads_the_window_start_to_exa(self):
239 net = FakeNet([])
240 cfg = {"EXA_API_KEY": "ex"}
241 with mock.patch("lib.youtube_yt.is_ytdlp_installed", return_value=True), \
242 mock.patch("lib.http.request", side_effect=net.request), \
243 mock.patch("lib.subproc.run_with_timeout", side_effect=net.run):
244 shortform_oss.search("tiktok", "topic", FROM, TO, "default", {**cfg, **NATIVE})
245 exa = [kw for _m, url, kw in net.requests if "exa.ai" in url]
246 assert exa and exa[0]["json_data"]["startPublishedDate"].startswith(FROM)
247
248
249 class TestCreatorExpansion:
250 PLAYLIST = FIXTURE.read_text()
251
252 def test_handle_from_a_stale_video_is_listed_and_filtered_by_window_and_title(self):
253 stale = tt_url("mattpocockuk", "2025-02-01")
254 keep = "https://www.tiktok.com/@mattpocockuk/video/7704672261512449313"
255 net = FakeNet(
256 [stale],
257 hydrate={keep: _raw("tiktok", keep, "2026-11-05", "Is vibe coding an insult?")},
258 playlists={"mattpocockuk": self.PLAYLIST},
259 )
260 result = _run_search(net, topic="vibe coding")
261 assert net.listed_handles() == ["mattpocockuk"]
262 # In-window and on-topic only: off-topic in-window titles and the
263 # stale October videos never reach hydration.
264 assert net.hydrated_urls() == [keep]
265 assert [i["url"] for i in result["items"]] == [keep]
266
267 def test_listing_prints_id_and_title_bounded_per_depth(self):
268 net = FakeNet([tt_url("h", "2025-02-01")], playlists={"h": self.PLAYLIST})
269 _run_search(net, depth="default")
270 cmd = next(c for c, _ in net.calls if "--flat-playlist" in c)
271 fmt = cmd[cmd.index("--print") + 1]
272 assert "id" in fmt and "title" in fmt
273 assert cmd[cmd.index("--playlist-end") + 1] == "24"
274 assert "view_count" in fmt
275
276 @pytest.mark.parametrize("depth,creators", [("quick", 3), ("default", 5), ("deep", 8)])
277 def test_number_of_listed_creators_is_capped(self, depth, creators):
278 links = [tt_url(f"h{n}", "2025-02-01", low=n) for n in range(12)]
279 net = FakeNet(links)
280 _run_search(net, depth=depth)
281 assert net.listed_handles() == [f"h{n}" for n in range(creators)]
282
283 def test_topic_account_keeps_every_in_window_video(self):
284 # "Matt Pocock" is @mattpocockuk: its titles never name it, so the
285 # title bar would drop all of them. Authorship makes them on-topic.
286 net = FakeNet([tt_url("mattpocockuk", "2025-02-01")],
287 playlists={"mattpocockuk": self.PLAYLIST})
288 _run_search(net, topic="Matt Pocock")
289 assert len(net.hydrated_urls()) == 5
290
291 def test_listing_keeps_the_most_viewed_in_window_videos(self):
292 import json as _json
293 rows = [_json.loads(line) for line in self.PLAYLIST.splitlines()]
294 views = [10, 900, 50, 7000, 300, 99999, 99999, 99999] # last three are October
295 playlist = "\n".join(_json.dumps({**r, "view_count": v}) for r, v in zip(rows, views))
296 net = FakeNet([], playlists={"mattpocockuk": playlist})
297 with mock.patch("lib.subproc.run_with_timeout", side_effect=net.run):
298 urls = shortform_oss.creator_urls(
299 "tiktok", "mattpocockuk", 3, from_date=FROM, to_date=TO, topic="Matt Pocock",
300 )
301 ids = [u.rsplit("/", 1)[-1] for u in urls]
302 assert ids == [rows[3]["id"], rows[1]["id"], rows[4]["id"]]
303
304 def test_creator_is_topic_needs_a_real_match(self):
305 assert shortform_oss._creator_is_topic("Sabrina Carpenter", "@sabrinacarpenter")
306 assert shortform_oss._creator_is_topic("Sabrina Carpenter", "Sabrina Carpenter")
307 assert not shortform_oss._creator_is_topic("air fryer recipes", "airfryerguy")
308 assert not shortform_oss._creator_is_topic("AI", "aidaily")
309
310 def test_explicit_creators_are_not_listed_twice(self):
311 net = FakeNet([tt_url("mattpocockuk", "2025-02-01")],
312 playlists={"mattpocockuk": self.PLAYLIST})
313 _run_search(net, creators=["mattpocockuk"])
314 assert net.listed_handles() == ["mattpocockuk"]
315
316 def test_explicit_creator_listing_drops_out_of_window_ids(self):
317 net = FakeNet([], playlists={"mattpocockuk": self.PLAYLIST})
318 _run_search(net, creators=["mattpocockuk"])
319 hydrated = net.hydrated_urls()
320 assert hydrated, "in-window explicit-creator videos must be hydrated"
321 for url in hydrated:
322 assert shortform_oss.post_date_from_url("tiktok", url) >= FROM
323
324 def test_expansion_off_lists_no_harvested_creators(self):
325 net = FakeNet([tt_url("mattpocockuk", "2025-02-01")],
326 playlists={"mattpocockuk": self.PLAYLIST})
327 _run_search(net, config={"LAST30DAYS_SHORTFORM_CREATOR_EXPANSION": "off"})
328 assert net.listed_handles() == []
329
330 def test_instagram_never_lists_creators(self):
331 net = FakeNet([f"https://www.instagram.com/reel/{ig_shortcode('2025-01-10')}/"])
332 _run_search(net, kind="instagram")
333 assert net.listed_handles() == []
334
335 def test_cancel_stops_expansion_between_creators(self):
336 cancel = threading.Event()
337 links = [tt_url(f"h{n}", "2025-02-01", low=n) for n in range(5)]
338 net = FakeNet(links, on_list=lambda _h: cancel.set())
339 _run_search(net, cancel=cancel)
340 assert net.listed_handles() == ["h0"]
341 assert net.hydrated_urls() == []
342
343
344 class TestLaneEntryPoints:
345 """The keyless lanes surface the window error instead of stale posts."""
346
347 @pytest.mark.parametrize("lane", ["tiktok", "instagram"])
348 def test_keyless_lane_returns_zero_with_reason_for_stale_posts(self, lane):
349 from lib import instagram, tiktok
350
351 if lane == "tiktok":
352 urls = [f"https://www.tiktok.com/@u/video/{n}" for n in (101, 102)]
353 else:
354 urls = ["https://www.instagram.com/reel/ABCDEFGHIJKLMNOPQRST/"]
355 net = FakeNet(urls, hydrate={u: _raw(lane, u, "2024-03-01") for u in urls})
356 module = tiktok if lane == "tiktok" else instagram
357 with mock.patch("lib.youtube_yt.is_ytdlp_installed", return_value=True), \
358 mock.patch("lib.http.request", side_effect=net.request), \
359 mock.patch("lib.subproc.run_with_timeout", side_effect=net.run):
360 result = module.search_and_enrich(
361 "topic words", FROM, TO, "default", None,
362 config={"SERPER_API_KEY": "sp", **NATIVE},
363 )
364 assert result["items"] == []
365 assert "date range" in result["error"]
366
367
368 class TestHistoricalWindow:
369 """An --as-of window ending in the past must not get "past month" filters."""
370
371 OLD_FROM, OLD_TO = "2024-02-01", "2024-03-01"
372
373 def _discover(self, cfg, to_date, from_date=None):
374 seen = {}
375
376 def fake_request(method, url, **kw):
377 seen.setdefault("request", []).append((method, url, kw))
378 return {}
379
380 def fake_get(url, **kw):
381 seen.setdefault("get", []).append(url)
382 return {"results": []}
383
384 with mock.patch("lib.http.request", side_effect=fake_request), \
385 mock.patch("lib.http.get", side_effect=fake_get), \
386 mock.patch.dict(os.environ, {}):
387 os.environ.pop("LAST30DAYS_SHORTFORM_FRESHNESS", None)
388 shortform_oss.discover_urls(
389 "tiktok", "topic", {**cfg, **NATIVE}, 5,
390 from_date=from_date or self.OLD_FROM, to_date=to_date,
391 )
392 return seen
393
394 def test_relative_filters_are_dropped_for_a_past_window(self):
395 serper = self._discover({"SERPER_API_KEY": "sp"}, self.OLD_TO)
396 assert "tbs" not in serper["request"][0][2]["json_data"]
397 brave = self._discover({"BRAVE_API_KEY": "br"}, self.OLD_TO)
398 q = parse_qs(urlparse(brave["request"][0][1]).query)
399 assert q.get("freshness") != ["pm"]
400 searx = self._discover({"LAST30DAYS_SEARXNG_URL": "https://searx.example"}, self.OLD_TO)
401 assert "time_range" not in parse_qs(urlparse(searx["get"][0]).query)
402
403 def test_exa_gets_both_window_bounds_for_a_past_window(self):
404 exa = self._discover({"EXA_API_KEY": "ex"}, self.OLD_TO)
405 body = exa["request"][0][2]["json_data"]
406 assert body["startPublishedDate"].startswith(self.OLD_FROM)
407 assert body["endPublishedDate"].startswith(self.OLD_TO)
408
409 def test_a_window_longer_than_a_month_drops_relative_filters(self):
410 today = datetime.now(timezone.utc).date()
411 seen = {}
412
413 def fake_request(method, url, **kw):
414 seen.setdefault("request", []).append(kw)
415 return {}
416
417 with mock.patch("lib.http.request", side_effect=fake_request), \
418 mock.patch.dict(os.environ, {}):
419 os.environ.pop("LAST30DAYS_SHORTFORM_FRESHNESS", None)
420 shortform_oss.discover_urls(
421 "tiktok", "topic", {"SERPER_API_KEY": "sp", **NATIVE}, 5,
422 from_date=(today - timedelta(days=90)).isoformat(),
423 to_date=today.isoformat(),
424 )
425 assert "tbs" not in seen["request"][0]["json_data"]
426
427 def test_a_window_ending_today_keeps_relative_filters(self):
428 now = datetime.now(timezone.utc).date()
429 today, start = now.isoformat(), (now - timedelta(days=20)).isoformat()
430 serper = self._discover({"SERPER_API_KEY": "sp"}, today, start)
431 assert serper["request"][0][2]["json_data"]["tbs"] == "qdr:m"
432 exa = self._discover({"EXA_API_KEY": "ex"}, today, start)
433 assert "endPublishedDate" not in exa["request"][0][2]["json_data"]
434
435
436 class TestBatchedExtraction:
437 def test_a_timed_out_batch_keeps_the_posts_other_batches_read(self):
438 from lib import subproc
439
440 urls = [tt_url("u", "2026-11-10", low=n) for n in range(1, 10)]
441
442 def fake_run(cmd, timeout=None, input_text=None, **_kw):
443 batch = (input_text or "").split()
444 if urls[0] in batch:
445 raise subproc.SubprocTimeout("slow", started=True)
446 return SimpleNamespace(stdout="\n".join(
447 json.dumps(_raw("tiktok", u, "2026-11-10")) for u in batch))
448
449 with mock.patch("lib.youtube_yt.is_ytdlp_installed", return_value=True), \
450 mock.patch("lib.subproc.run_with_timeout", side_effect=fake_run):
451 items = shortform_oss.enrich_urls("tiktok", urls, "topic words")
452 got = {i["url"] for i in items}
453 lost = set(urls[:shortform_oss._ENRICH_BATCH])
454 assert got == set(urls) - lost
455
456 def test_cancel_and_deadline_reach_the_subprocess(self):
457 seen = []
458 cancel = threading.Event()
459
460 def fake_run(cmd, timeout=None, input_text=None, **kw):
461 seen.append(kw)
462 return SimpleNamespace(stdout="")
463
464 with mock.patch("lib.youtube_yt.is_ytdlp_installed", return_value=True), \
465 mock.patch("lib.subproc.run_with_timeout", side_effect=fake_run):
466 shortform_oss.enrich_urls(
467 "tiktok", [tt_url("u", "2026-11-10")], "topic",
468 deadline=10**12, cancel=cancel,
469 )
470 assert seen[0]["cancel"] is cancel
471 assert seen[0]["deadline_monotonic"] == 10**12
472
473
474 def test_creator_listing_passes_cancel_and_deadline_to_the_subprocess():
475 seen = []
476 cancel = threading.Event()
477
478 def fake_run(cmd, timeout=None, input_text=None, **kw):
479 seen.append(kw)
480 return SimpleNamespace(stdout="")
481
482 with mock.patch("lib.subproc.run_with_timeout", side_effect=fake_run):
483 shortform_oss.creator_urls("tiktok", "creator", 3, deadline=10**12, cancel=cancel)
484 assert seen[0]["cancel"] is cancel
485 assert seen[0]["deadline_monotonic"] == 10**12
486
487
488 def test_creator_listing_skips_once_cancelled():
489 cancel = threading.Event()
490 cancel.set()
491 with mock.patch("lib.subproc.run_with_timeout") as run:
492 assert shortform_oss.creator_urls("tiktok", "creator", 3, cancel=cancel) == []
493 run.assert_not_called()
494
495
496 @pytest.mark.parametrize("cfg", [
497 {"SERPER_API_KEY": "sp"},
498 {"EXA_API_KEY": "ex"},
499 {"BRAVE_API_KEY": "br"},
500 {"LAST30DAYS_SEARXNG_URL": "https://searx.example"},
501 ])
502 def test_every_discovery_request_carries_the_run_deadline(cfg):
503 seen = []
504 cancel = threading.Event()
505
506 def fake_request(method, url, **kw):
507 seen.append(kw)
508 return {}
509
510 def fake_get(url, **kw):
511 seen.append(kw)
512 return {"results": []}
513
514 with mock.patch("lib.http.request", side_effect=fake_request), \
515 mock.patch("lib.http.get", side_effect=fake_get):
516 shortform_oss.discover_urls(
517 "tiktok", "topic", {**cfg, **NATIVE}, 5, deadline=10**12, cancel=cancel,
518 )
519 assert seen and seen[0]["deadline_monotonic"] == 10**12
520
521
522 def test_keyless_floor_gets_the_run_deadline_and_cancel():
523 cancel = threading.Event()
524 with mock.patch("lib.web_search_keyless.keyless_search", return_value=([], {})) as floor:
525 shortform_oss.discover_urls("tiktok", "topic", {}, 5, deadline=10**12, cancel=cancel)
526 assert floor.call_args.kwargs["deadline_monotonic"] == 10**12
527 assert floor.call_args.kwargs["cancel"] is cancel
528
529
530 def test_keyless_ladder_starts_no_rung_once_cancelled():
531 from lib import web_search_keyless as wsk
532
533 cancel = threading.Event()
534 cancel.set()
535 with mock.patch("lib.http.get_text") as get_text:
536 items, art = wsk.keyless_search("q", ("2026-11-01", "2026-11-21"), {}, 5, cancel=cancel)
537 assert items == []
538 get_text.assert_not_called()
539 assert set(art["keyless_rungs"].values()) == {wsk.SKIPPED}
540
540 lines PYTHON