返回 last30days-skill
test_shortform_oss.py
根目录 / tests / test_shortform_oss.py
1 """Pin the keyless short-form fallback gate: yt-dlp + web discovery.
2
3 TikTok and Instagram are no longer purely key-gated. Without
4 SCRAPECREATORS_API_KEY they can still run when yt-dlp is installed and a
5 discovery source (SearXNG / Serper / Exa / Brave / the keyless floor, or
6 on a native-search host the host's own search via --shortform-urls) is
7 available. This file pins BOTH branches of that gate so a later
8 change to is_tiktok_available() / is_instagram_available() cannot silently
9 collapse the fallback back to key-only, and so a keyless run does not keep
10 telling the user to buy a ScrapeCreators key it will never need.
11
12 The gate reads yt-dlp presence through youtube_yt.is_ytdlp_installed(), not
13 through the env.is_ytdlp_available() wrapper, so that is the symbol patched
14 below -- same reason tests/test_doctor.py::_Hermetic pins it.
15 """
16
17 import os
18 import threading
19 import time
20 from types import SimpleNamespace
21 from unittest import mock
22
23 import pytest
24
25 from lib import env, health, shortform_oss
26
27 from tests.test_doctor import _build
28
29
30 # Each of these alone must be enough to arm the fallback.
31 DISCOVERY_BACKENDS = [
32 {"LAST30DAYS_SEARXNG_URL": "https://searx.example"},
33 {"SERPER_API_KEY": "sp"},
34 {"EXA_API_KEY": "ex"},
35 {"BRAVE_API_KEY": "br"},
36 ]
37
38 # Host that has its own web search: the keyless floor is suppressed, paid
39 # keys are not. Set this to isolate "no backend at all" from "no keyless".
40 NATIVE_SEARCH_HOST = {"LAST30DAYS_NATIVE_SEARCH": "1"}
41
42 SOURCES = [env.is_tiktok_available, env.is_instagram_available]
43
44
45 def _gate(config, ytdlp):
46 """is_shortform_oss_available() with yt-dlp presence pinned."""
47 with mock.patch("lib.youtube_yt.is_ytdlp_installed", return_value=ytdlp):
48 return env.is_shortform_oss_available(config)
49
50
51 def _source_available(fn, config, ytdlp):
52 """A source-availability predicate with yt-dlp presence pinned."""
53 with mock.patch("lib.youtube_yt.is_ytdlp_installed", return_value=ytdlp):
54 return fn(config)
55
56
57 class TestShortformGate:
58 def test_ytdlp_missing_closes_the_gate_even_with_a_paid_backend(self):
59 for cfg in DISCOVERY_BACKENDS:
60 assert _gate(cfg, False) is False, cfg
61
62 def test_blank_searxng_url_is_not_listed_as_a_discovery_source(self):
63 # A whitespace-only URL is a misconfiguration, not a backend.
64 cfg = {"LAST30DAYS_SEARXNG_URL": " ", **NATIVE_SEARCH_HOST}
65 assert env.shortform_discovery_sources(cfg) == ["host search"]
66
67 @pytest.mark.parametrize("cfg", DISCOVERY_BACKENDS)
68 def test_paid_backend_arms_the_gate_on_a_native_search_host(self, cfg):
69 # Native-search hosts suppress only the keyless floor, never a paid key.
70 assert _gate({**cfg, **NATIVE_SEARCH_HOST}, True) is True
71
72 def test_keyless_floor_arms_the_gate_without_native_search(self):
73 assert _gate({}, True) is True
74 assert env.shortform_discovery_sources({}) == ["keyless floor"]
75
76 def test_native_search_host_arms_the_gate_through_host_search(self):
77 # The keyless floor is off there; the host's own search hands the
78 # engine URLs through --shortform-urls instead.
79 assert _gate(dict(NATIVE_SEARCH_HOST), True) is True
80 assert env.shortform_discovery_sources(dict(NATIVE_SEARCH_HOST)) == ["host search"]
81
82 def test_exa_is_a_discovery_source_only_for_tiktok(self):
83 # Exa returns 0 Instagram posts; its key must not be listed there.
84 cfg = {"EXA_API_KEY": "ex", **NATIVE_SEARCH_HOST}
85 assert env.shortform_discovery_sources(cfg, "tiktok") == ["Exa", "host search"]
86 assert env.shortform_discovery_sources(cfg, "instagram") == ["host search"]
87
88 def test_discovery_sources_list_every_armed_rung_in_lane_order(self):
89 cfg = {"LAST30DAYS_SEARXNG_URL": "https://searx.example", "SERPER_API_KEY": "sp",
90 "EXA_API_KEY": "ex", "BRAVE_API_KEY": "br"}
91 assert env.shortform_discovery_sources(cfg, "tiktok") == [
92 "SearXNG", "Serper", "Exa", "Brave", "keyless floor",
93 ]
94
95
96 class TestSourceAvailability:
97 @pytest.mark.parametrize("fn", SOURCES)
98 def test_scrapecreators_key_is_enough_without_ytdlp(self, fn):
99 assert _source_available(fn, {"SCRAPECREATORS_API_KEY": "sc"}, False) is True
100
101 @pytest.mark.parametrize("fn", SOURCES)
102 def test_oss_fallback_keeps_the_source_available_keyless(self, fn):
103 assert _source_available(fn, {}, True) is True
104
105 @pytest.mark.parametrize("fn", SOURCES)
106 def test_source_stays_unavailable_with_no_key_and_no_fallback(self, fn):
107 assert _source_available(fn, dict(NATIVE_SEARCH_HOST), False) is False
108
109 @pytest.mark.parametrize("fn", SOURCES)
110 def test_tiktok_and_instagram_never_diverge(self, fn):
111 # They share one gate; a divergence is a bug, not a feature.
112 other = SOURCES[1] if fn is SOURCES[0] else SOURCES[0]
113 for cfg, ytdlp in (({}, True), (dict(NATIVE_SEARCH_HOST), True),
114 (dict(NATIVE_SEARCH_HOST), False),
115 ({"SCRAPECREATORS_API_KEY": "sc"}, False)):
116 assert _source_available(fn, cfg, ytdlp) is _source_available(other, cfg, ytdlp)
117
118
119 class TestTokens:
120 """APIFY_API_TOKEN is a legacy alias only; it was never wired to an actor."""
121
122 def test_tiktok_token_never_falls_back_to_apify(self):
123 assert env.get_tiktok_token({"APIFY_API_TOKEN": "legacy"}) == ""
124 assert env.get_tiktok_token({"APIFY_API_TOKEN": "legacy",
125 "SCRAPECREATORS_API_KEY": "sc"}) == "sc"
126
127 def test_instagram_token_never_falls_back_to_apify(self):
128 assert env.get_instagram_token({"APIFY_API_TOKEN": "legacy"}) == ""
129 assert env.get_instagram_token({"SCRAPECREATORS_API_KEY": "sc"}) == "sc"
130
131
132 class TestDoctorSurface:
133 """The user-visible half: doctor's verdict must follow the gate."""
134
135 def test_doctor_reports_the_fallback_armed_when_ytdlp_is_present(self):
136 record = _build({}, probe_map={"yt-dlp": health.OK})["sources"]["tiktok"]
137 assert record["status"] == "ok"
138 assert "yt-dlp + web discovery" in record["requires"]
139
140 def test_doctor_stops_prescribing_a_scrapecreators_key_when_armed(self):
141 # The old key-gated wording is the failure mode worth pinning.
142 record = _build({}, probe_map={"yt-dlp": health.OK})["sources"]["tiktok"]
143 assert record["requires"] != "SCRAPECREATORS_API_KEY"
144
145 def test_doctor_names_the_armed_discovery_sources(self):
146 report = _build({"SERPER_API_KEY": "sp", "EXA_API_KEY": "ex", **NATIVE_SEARCH_HOST},
147 probe_map={"yt-dlp": health.OK})
148 tiktok = report["sources"]["tiktok"]["detail"]
149 assert "keyless lane armed via Serper, Exa, host search" in tiktok
150 instagram = report["sources"]["instagram"]["detail"]
151 assert "via Serper, host search" in instagram and "Exa" not in instagram
152
153 def test_doctor_calls_instagram_best_effort(self):
154 report = _build({}, probe_map={"yt-dlp": health.OK})
155 assert "best effort, low recall" in report["sources"]["instagram"]["detail"]
156 assert "best effort" not in report["sources"]["tiktok"]["detail"]
157 assert "keyless floor" in report["sources"]["tiktok"]["detail"]
158
159 def test_doctor_keeps_the_key_gated_verdict_when_ytdlp_is_absent(self):
160 report = _build({}, probe_map={"yt-dlp": health.MISSING})
161 for name in ("tiktok", "instagram"):
162 record = report["sources"][name]
163 assert record["tier"] == "off", name
164 assert record["requires"] == "SCRAPECREATORS_API_KEY", name
165
166 class TestDeadlineAndCancel:
167 """The fallback must stop starting work once the run is cancelled."""
168
169 def _no_work(self):
170 return mock.patch.multiple(
171 "lib.shortform_oss",
172 discover_urls=mock.DEFAULT,
173 enrich_urls=mock.DEFAULT,
174 creator_urls=mock.DEFAULT,
175 )
176
177 def test_past_deadline_returns_error_without_discovery(self):
178 with mock.patch("lib.youtube_yt.is_ytdlp_installed", return_value=True), \
179 mock.patch("lib.shortform_oss.discover_urls") as disc, \
180 mock.patch("lib.shortform_oss.enrich_urls") as enrich:
181 result = shortform_oss.search(
182 "tiktok", "topic", "2026-01-01", "2026-12-31", "default", {},
183 deadline=time.monotonic() - 1.0,
184 )
185 assert result["items"] == []
186 assert "deadline" in result["error"]
187 disc.assert_not_called()
188 enrich.assert_not_called()
189
190 def test_cancelled_event_returns_error_without_discovery(self):
191 cancel = threading.Event()
192 cancel.set()
193 with mock.patch("lib.youtube_yt.is_ytdlp_installed", return_value=True), \
194 mock.patch("lib.shortform_oss.discover_urls") as disc, \
195 mock.patch("lib.shortform_oss.enrich_urls") as enrich:
196 result = shortform_oss.search(
197 "instagram", "topic", "2026-01-01", "2026-12-31", "default", {},
198 cancel=cancel,
199 )
200 assert result["items"] == []
201 assert result["error"]
202 disc.assert_not_called()
203 enrich.assert_not_called()
204
205 def test_enrich_skips_when_deadline_passes_during_discovery(self):
206 with mock.patch("lib.shortform_oss.discover_urls",
207 return_value=(["https://www.tiktok.com/@u/video/1"], "searxng")), \
208 mock.patch("lib.shortform_oss.enrich_urls") as enrich:
209 result = shortform_oss.search(
210 "tiktok", "topic", "2026-01-01", "2026-12-31", "default", {},
211 deadline=time.monotonic() - 1.0,
212 )
213 enrich.assert_not_called()
214 assert result["items"] == []
215
216
217 class TestKeylessRungPolicy:
218 """Discovery must follow the same keyless policy the availability gate used."""
219
220 def test_keyless_rung_is_skipped_on_native_search_hosts(self):
221 with mock.patch("lib.web_search_keyless.keyless_search",
222 side_effect=AssertionError("keyless ran on a native-search host")):
223 urls, backend = shortform_oss.discover_urls(
224 "tiktok", "topic", {"LAST30DAYS_NATIVE_SEARCH": "1"}, 5,
225 )
226 assert urls == []
227 assert backend == "none"
228
229 def test_keyless_rung_is_skipped_when_the_host_passed_urls(self):
230 from lib import shortform_envelope
231
232 env = shortform_envelope.Envelope(
233 path="x.json", sha256="0", topic="topic", tiktok_posts=[], instagram_posts=[],
234 tiktok_creators=[], counters={}, total=0, notes=[],
235 )
236 with mock.patch("lib.web_search_keyless.keyless_search",
237 side_effect=AssertionError("keyless ran after the host searched")):
238 urls, backend = shortform_oss.discover_urls(
239 "tiktok", "topic", {"_shortform_envelope": env}, 5,
240 )
241 assert (urls, backend) == ([], "none")
242
243 def test_keyless_rung_runs_when_policy_allows_it(self):
244 canned = ({"url": "https://www.tiktok.com/@u/video/1"},)
245 with mock.patch("lib.web_search_keyless.keyless_search",
246 return_value=(list(canned), {"keyless_backend": "ddg"})) as ks:
247 urls, backend = shortform_oss.discover_urls("tiktok", "topic", {}, 5)
248 ks.assert_called_once()
249 assert urls == ["https://www.tiktok.com/@u/video/1"]
250 assert backend == "ddg"
251
252
253 class TestInstagramFallbackErrorSurfaces:
254 """Without a token the paid loop never runs, so the OSS error must surface."""
255
256 def test_no_token_oss_error_is_returned(self):
257 from lib import instagram as ig
258
259 with mock.patch("lib.shortform_oss.search",
260 return_value={"items": [], "error": "oss discovery empty"}):
261 result = ig.search_and_enrich(
262 "topic", "2026-01-01", "2026-12-31", "default", None, config={},
263 )
264 assert result["error"] == "oss discovery empty"
265
266
267 class TestSshRoutedExtraction:
268 """SSH-routed hosts (LAST30DAYS_YOUTUBE_SSH_HOST) extract remotely.
269
270 The availability gate follows youtube_yt.is_ytdlp_installed(), which is
271 True on SSH-routed hosts without a local binary — so extraction must run
272 through the same SSH wrapper instead of a local FileNotFoundError.
273 """
274
275 SSH_ENV = {"LAST30DAYS_YOUTUBE_SSH_HOST": "macmini"}
276
277 def test_gate_opens_on_ssh_routed_host_without_local_binary(self):
278 with mock.patch("lib.youtube_yt.is_ytdlp_installed", return_value=True) as inst, \
279 mock.patch.dict(os.environ, self.SSH_ENV):
280 # is_ytdlp_installed is what the gate reads; on SSH hosts it
281 # returns True without a local binary, and extraction must
282 # therefore route over ssh (pinned below).
283 assert env.is_shortform_oss_available({"SERPER_API_KEY": "sp"}) is True
284 inst.assert_called_once()
285
286 def test_enrich_urls_wrap_the_command_with_ssh(self):
287 from lib import subproc as subproc_mod
288
289 captured = {}
290
291 def fake_run(cmd, timeout=None, input_text=None, **_kw):
292 captured["cmd"] = cmd
293 captured["input"] = input_text
294 return SimpleNamespace(stdout="")
295
296 url = "https://www.tiktok.com/@u/video/1"
297 with mock.patch.dict(os.environ, self.SSH_ENV), \
298 mock.patch("lib.youtube_yt.is_ytdlp_installed", return_value=True), \
299 mock.patch.object(subproc_mod, "run_with_timeout", side_effect=fake_run):
300 items = shortform_oss.enrich_urls("tiktok", [url], "topic")
301 assert items == []
302 cmd = captured["cmd"]
303 assert cmd[0] == "ssh"
304 assert "macmini" in cmd
305 assert "yt-dlp" in " ".join(cmd)
306 assert "--dump-json" in " ".join(cmd)
307 assert url in (captured["input"] or "")
308
309 def test_creator_urls_wrap_the_command_with_ssh(self):
310 from lib import subproc as subproc_mod
311
312 captured = {}
313
314 def fake_run(cmd, timeout=None, input_text=None, **_kw):
315 captured["cmd"] = cmd
316 return SimpleNamespace(stdout='{"id": "1234567890", "title": "t"}')
317
318 with mock.patch.dict(os.environ, self.SSH_ENV), \
319 mock.patch.object(subproc_mod, "run_with_timeout", side_effect=fake_run):
320 urls = shortform_oss.creator_urls("tiktok", "creator", 3)
321 assert urls == ["https://www.tiktok.com/@creator/video/1234567890"]
322 assert captured["cmd"][0] == "ssh"
323
324 def test_local_hosts_still_run_yt_dlp_directly(self):
325 from lib import subproc as subproc_mod
326
327 captured = {}
328
329 def fake_run(cmd, timeout=None, input_text=None, **_kw):
330 captured["cmd"] = cmd
331 return SimpleNamespace(stdout="")
332
333 # Pin yt-dlp presence: CI runners do not have yt-dlp on PATH, and
334 # enrich_urls gates on is_ytdlp_installed() before building the
335 # command — unpinned, the fake never runs there. The SSH var is also
336 # unset (not empty-string-set) so _ytdlp_ssh_host() cannot wrap.
337 saved = os.environ.pop("LAST30DAYS_YOUTUBE_SSH_HOST", None)
338 try:
339 with mock.patch.dict(os.environ, {}, clear=False), \
340 mock.patch("lib.youtube_yt.is_ytdlp_installed", return_value=True), \
341 mock.patch.object(subproc_mod, "run_with_timeout", side_effect=fake_run):
342 shortform_oss.enrich_urls(
343 "tiktok", ["https://www.tiktok.com/@u/video/1"], "topic",
344 )
345 finally:
346 if saved is not None:
347 os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = saved
348 assert captured["cmd"][0] == "yt-dlp"
349
349 lines PYTHON