返回 last30days-skill
test_shortform_envelope.py
根目录 / tests / test_shortform_envelope.py
1 """The ``--shortform-urls`` host lane: a host's own web search hands the
2 keyless TikTok/Instagram lane post URLs and TikTok creator profiles. The engine
3 reads only each URL, drops stale posts by their id date before any fetch,
4 hydrates the rest with yt-dlp, holds them to the window and the topic bar, and
5 names the lane in the footer. With a ScrapeCreators key the URLs wait unused.
6
7 Network is faked at ``lib.subproc.run_with_timeout`` (yt-dlp) and
8 ``lib.http.request`` (web discovery)."""
9
10 from __future__ import annotations
11
12 import contextlib
13 import io
14 import json
15 import os
16 import sys
17 from contextlib import redirect_stderr, redirect_stdout
18 from pathlib import Path
19 from unittest import mock
20
21 import pytest
22
23 import last30days as cli
24 from lib import dates, pipeline, render, schema, shortform_envelope, shortform_oss
25 from tests.test_shortform_oss_window import FakeNet, _raw, ig_shortcode, tt_url
26
27 TOPIC = "labubu dolls"
28 FROM, TO = dates.get_date_range(30)
29 NATIVE = {"LAST30DAYS_NATIVE_SEARCH": "1"}
30
31
32 def _day(offset: int) -> str:
33 return dates.get_date_range(offset)[0]
34
35
36 FRESH, OLD = _day(5), _day(200)
37
38
39 def _envelope(urls, **over) -> dict:
40 payload = {"schema": shortform_envelope.SCHEMA, "topic": TOPIC,
41 "urls": [u if isinstance(u, dict) else {"url": u} for u in urls]}
42 payload.update(over)
43 return payload
44
45
46 def _write(tmp_path: Path, payload, name: str = "shortform.json") -> str:
47 path = tmp_path / name
48 path.write_text(payload if isinstance(payload, str) else json.dumps(payload), encoding="utf-8")
49 return str(path)
50
51
52 def _read(path: str, topic: str = TOPIC) -> shortform_envelope.Envelope:
53 with redirect_stderr(io.StringIO()):
54 return shortform_envelope.read(path, topic)
55
56
57 def _search(net, envelope, kind="tiktok", config=None):
58 cfg = {**NATIVE, **(config or {})}
59 if envelope is not None:
60 cfg["_shortform_envelope"] = envelope
61 with mock.patch("lib.youtube_yt.is_ytdlp_installed", return_value=True), \
62 mock.patch("lib.http.request", side_effect=net.request), \
63 mock.patch("lib.subproc.run_with_timeout", side_effect=net.run), \
64 mock.patch.dict(os.environ, {}), redirect_stderr(io.StringIO()):
65 os.environ.pop("LAST30DAYS_YOUTUBE_SSH_HOST", None)
66 return shortform_oss.search(kind, TOPIC, FROM, TO, "default", cfg)
67
68
69 # ---------------------------------------------------------------------------
70 # Reading the envelope
71 # ---------------------------------------------------------------------------
72
73
74 class TestReader:
75 def test_posts_and_creators_are_sorted_and_bad_rows_counted(self, tmp_path):
76 tt = tt_url("dollfan", FRESH)
77 ig = f"https://www.instagram.com/p/{ig_shortcode(FRESH)}/?igsh=abc"
78 urls = [
79 tt + "?is_from_webapp=1",
80 ig,
81 "https://www.tiktok.com/@labubu_official",
82 "https://www.instagram.com/labubu_official/",
83 "https://vm.tiktok.com/ZMabc123/",
84 "https://www.google.com/url?q=" + tt,
85 "https://evil.example/?u=" + tt,
86 "https://www.tiktok.com/tag/labubu",
87 {"url": tt, "caption": "HOST CAPTION", "views": 99999999},
88 {"id": "123"},
89 ]
90 envelope = _read(_write(tmp_path, _envelope(urls)))
91 assert envelope.total == 10
92 assert envelope.posts("tiktok") == [tt]
93 assert envelope.posts("instagram") == [f"https://www.instagram.com/reel/{ig_shortcode(FRESH)}/"]
94 assert envelope.creators("tiktok") == ["labubu_official"]
95 assert envelope.creators("instagram") == []
96 c = envelope.counters
97 assert c["instagram-profile"] == 1
98 assert c["not-a-post"] == 2 # vm.tiktok.com short link, tag page
99 assert c["redirect"] == 1
100 assert c["non-shortform"] == 1
101 assert c["duplicate"] == 1
102 assert c["extra-fields"] == 2 # the host's caption/views row, and the id-only row
103 assert c["invalid"] == 1 # an id is not a URL
104
105 def test_only_the_first_40_urls_are_used(self, tmp_path):
106 urls = [tt_url("u", FRESH, low=n) for n in range(45)]
107 envelope = _read(_write(tmp_path, _envelope(urls)))
108 assert envelope.accepted == shortform_envelope.MAX_URLS == 40
109 assert envelope.counters["truncated"] == 5
110 assert "first 40" in envelope.receipt()
111
112 @pytest.mark.parametrize("payload, field", [
113 (_envelope(["https://www.tiktok.com/@a"], schema="last30days-reddit-threads/1"), "schema"),
114 (_envelope(["https://www.tiktok.com/@a"], topic="something else"), "topic"),
115 (_envelope([]), "empty"),
116 ({"schema": shortform_envelope.SCHEMA, "topic": TOPIC, "urls": "x"}, "not a list"),
117 ("not json", "valid JSON"),
118 ])
119 def test_envelope_level_problems_fail_closed(self, tmp_path, payload, field):
120 path = _write(tmp_path, payload)
121 with pytest.raises(shortform_envelope.EnvelopeContractError) as err:
122 _read(path)
123 assert field in err.value.message
124 assert "without --shortform-urls" in err.value.message
125
126 def test_a_non_json_suffix_is_refused(self, tmp_path):
127 path = _write(tmp_path, _envelope(["https://www.tiktok.com/@a"]), "urls.txt")
128 with pytest.raises(shortform_envelope.EnvelopeContractError, match=".json file"):
129 _read(path)
130
131
132 # ---------------------------------------------------------------------------
133 # The keyless lane
134 # ---------------------------------------------------------------------------
135
136
137 class TestKeylessLane:
138 def test_host_posts_are_id_dated_hydrated_and_marked(self, tmp_path):
139 fresh = tt_url("dollfan", FRESH)
140 stale = tt_url("oldfan", OLD)
141 envelope = _read(_write(tmp_path, _envelope([fresh, stale])))
142 net = FakeNet([], hydrate={
143 fresh: _raw("tiktok", fresh, FRESH, text="my labubu dolls haul"),
144 stale: _raw("tiktok", stale, OLD, text="labubu dolls"),
145 })
146 result = _search(net, envelope)
147 assert stale not in net.hydrated_urls() # dropped by its id date, never fetched
148 assert [i["url"] for i in result["items"]] == [fresh]
149 assert result["items"][0]["_host_found"] is True
150
151 def test_off_topic_host_posts_are_dropped(self, tmp_path):
152 on = tt_url("a", FRESH, low=1)
153 off = tt_url("b", FRESH, low=2)
154 envelope = _read(_write(tmp_path, _envelope([on, off])))
155 net = FakeNet([], hydrate={
156 on: _raw("tiktok", on, FRESH, text="labubu dolls restock"),
157 off: _raw("tiktok", off, FRESH, text="sourdough bread recipe"),
158 })
159 result = _search(net, envelope)
160 assert [i["url"] for i in result["items"]] == [on]
161
162 def test_host_urls_merge_with_engine_discovery_deduped_by_id(self, tmp_path):
163 shared = tt_url("a", FRESH, low=1)
164 engine_only = tt_url("c", FRESH, low=3)
165 envelope = _read(_write(tmp_path, _envelope([shared])))
166 net = FakeNet([shared, engine_only], hydrate={
167 u: _raw("tiktok", u, FRESH, text="labubu dolls") for u in (shared, engine_only)
168 })
169 result = _search(net, envelope, config={"SERPER_API_KEY": "sp"})
170 hydrated = net.hydrated_urls()
171 assert hydrated.count(shared) == 1 and engine_only in hydrated
172 by_url = {i["url"]: i for i in result["items"]}
173 assert set(by_url) == {shared, engine_only}
174 assert by_url[shared].get("_host_found") is True
175 assert not by_url[engine_only].get("_host_found")
176
177 def test_tiktok_creator_profiles_feed_creator_expansion(self, tmp_path):
178 listed = tt_url("labubu_official", FRESH, low=9)
179 envelope = _read(_write(tmp_path, _envelope(["https://www.tiktok.com/@labubu_official"])))
180 playlist = json.dumps({"id": listed.rsplit("/", 1)[-1], "title": "new labubu dolls drop"})
181 net = FakeNet([], hydrate={listed: _raw("tiktok", listed, FRESH, text="new labubu dolls drop")},
182 playlists={"labubu_official": playlist})
183 result = _search(net, envelope, config={"LAST30DAYS_SHORTFORM_CREATOR_EXPANSION": "off"})
184 assert net.listed_handles() == ["labubu_official"]
185 assert [i["url"] for i in result["items"]] == [listed]
186 assert result["items"][0]["_host_found"] is True
187
188 def test_instagram_posts_come_from_the_same_envelope(self, tmp_path):
189 reel = f"https://www.instagram.com/reel/{ig_shortcode(FRESH)}/"
190 envelope = _read(_write(tmp_path, _envelope([reel, tt_url("a", FRESH)])))
191 net = FakeNet([], hydrate={reel: _raw("instagram", reel, FRESH, text="labubu dolls unboxing")})
192 result = _search(net, envelope, kind="instagram")
193 assert net.hydrated_urls() == [reel]
194 assert result["items"][0]["_host_found"] is True
195
196 def test_native_host_without_urls_says_why_it_found_nothing(self):
197 result = _search(FakeNet([]), None)
198 assert result["items"] == []
199 assert "--shortform-urls" in result["error"]
200
201 def test_scrapecreators_key_keeps_the_envelope_unused(self, tmp_path):
202 from lib import tiktok
203 fresh = tt_url("dollfan", FRESH)
204 envelope = _read(_write(tmp_path, _envelope([fresh])))
205 sc_item = {"video_id": "1", "text": "labubu dolls", "url": "https://www.tiktok.com/@x/video/1",
206 "engagement": {"views": 5}}
207 with mock.patch.object(tiktok, "search_tiktok", return_value={"items": [sc_item]}), \
208 mock.patch.object(tiktok, "fetch_captions"), \
209 mock.patch.object(shortform_oss, "search", side_effect=AssertionError("keyless must not run")):
210 result = tiktok.search_and_enrich(
211 TOPIC, FROM, TO, depth="quick", token="sc-test",
212 config={"_shortform_envelope": envelope},
213 )
214 assert [i["video_id"] for i in result["items"]] == ["1"]
215
216
217 # ---------------------------------------------------------------------------
218 # Pipeline and footer
219 # ---------------------------------------------------------------------------
220
221
222 class TestPipeline:
223 def _plan(self):
224 return {
225 "intent": "opinion", "freshness_mode": "balanced_recent", "cluster_mode": "story",
226 "subqueries": [{"label": "primary", "search_query": TOPIC, "ranking_query": TOPIC,
227 "sources": ["tiktok"]}],
228 "source_weights": {"tiktok": 1.0},
229 }
230
231 def test_host_found_items_reach_the_report_and_the_footer_names_the_lane(self, tmp_path):
232 fresh = tt_url("dollfan", FRESH)
233 envelope = _read(_write(tmp_path, _envelope([fresh])))
234 net = FakeNet([], hydrate={fresh: _raw("tiktok", fresh, FRESH, text="labubu dolls haul")})
235 with mock.patch("lib.youtube_yt.is_ytdlp_installed", return_value=True), \
236 mock.patch("lib.http.request", side_effect=net.request), \
237 mock.patch("lib.subproc.run_with_timeout", side_effect=net.run), \
238 redirect_stderr(io.StringIO()):
239 report = pipeline.run(
240 topic=TOPIC, config=dict(NATIVE), depth="default", requested_sources=["tiktok"],
241 mock=False, external_plan=self._plan(), web_backend="none", save_dir="",
242 shortform_urls=envelope,
243 )
244 items = report.items_by_source.get("tiktok") or []
245 assert [i.url for i in items] == [fresh]
246 assert items[0].metadata["host_search"] is True
247 footer = "\n".join(render._build_source_footer_lines(report))
248 assert render.HOST_SEARCH_LABEL in footer
249
250 def test_a_run_searching_neither_platform_ignores_the_envelope(self, tmp_path):
251 envelope = _read(_write(tmp_path, _envelope([tt_url("a", FRESH)])))
252 err = io.StringIO()
253 with redirect_stderr(err), pytest.raises(ValueError, match="No available planned sources"):
254 pipeline.run(
255 topic=TOPIC, config={"EXCLUDE_SOURCES": "tiktok,instagram"}, depth="default",
256 requested_sources=None, mock=False, external_plan=self._plan(),
257 web_backend="none", save_dir="", shortform_urls=envelope,
258 )
259 assert "envelope ignored (TikTok and Instagram are excluded" in err.getvalue()
260
261
262 # ---------------------------------------------------------------------------
263 # CLI
264 # ---------------------------------------------------------------------------
265
266 _DIAG = {
267 "available_sources": ["tiktok", "instagram"],
268 "x_pending_browser_auth": False,
269 "native_search": True,
270 "bird_installed": False,
271 "bird_authenticated": False,
272 "bird_username": None,
273 "native_web_backend": None,
274 "safe": False,
275 }
276
277
278 def _cli(argv, tmp_path, *, run=None, environ=None, config=None):
279 out, err = io.StringIO(), io.StringIO()
280 cfg_dir = tmp_path / "cfg"
281 cfg_dir.mkdir(exist_ok=True)
282 with contextlib.ExitStack() as stack:
283 stack.enter_context(mock.patch.object(cli.env, "get_config", return_value=dict(config or {})))
284 stack.enter_context(mock.patch.object(cli.env, "CONFIG_DIR", cfg_dir))
285 stack.enter_context(mock.patch.object(cli.env, "CONFIG_FILE", cfg_dir / ".env"))
286 stack.enter_context(mock.patch.object(cli.ui, "ProgressDisplay", return_value=mock.Mock()))
287 stack.enter_context(mock.patch.dict(
288 os.environ, {"LAST30DAYS_SKIP_PREFLIGHT": "1", **(environ or {})}, clear=False,
289 ))
290 stack.enter_context(mock.patch.object(sys, "argv", ["last30days.py", *argv]))
291 stack.enter_context(mock.patch.object(cli.pipeline, "diagnose", return_value=dict(_DIAG)))
292 stack.enter_context(mock.patch.object(
293 cli.pipeline, "run", side_effect=run or AssertionError("pipeline.run must not run"),
294 ))
295 stack.enter_context(redirect_stdout(out))
296 stack.enter_context(redirect_stderr(err))
297 try:
298 rc = cli.main()
299 except SystemExit as exc:
300 rc = exc.code
301 return rc, out.getvalue(), err.getvalue()
302
303
304 def _fake_report(topic: str) -> schema.Report:
305 return schema.Report(
306 topic=topic, range_from=FROM, range_to=TO, generated_at="2026-11-15T00:00:00+00:00",
307 provider_runtime=schema.ProviderRuntime(reasoning_provider="local", planner_model="d", rerank_model="l"),
308 query_plan=schema.QueryPlan(intent="general", freshness_mode="balanced_recent", cluster_mode="story",
309 raw_topic=topic, subqueries=[], source_weights={}),
310 clusters=[], ranked_candidates=[], items_by_source={}, errors_by_source={},
311 )
312
313
314 def _capturing(store: dict):
315 def fake_run(**kwargs):
316 store.update(kwargs)
317 return _fake_report(kwargs["topic"])
318 return fake_run
319
320
321 class TestCli:
322 def test_valid_envelope_reaches_run(self, tmp_path):
323 path = _write(tmp_path, _envelope([tt_url("a", FRESH), "https://example.com/x"]))
324 store: dict = {}
325 rc, _, err = _cli([TOPIC, "--shortform-urls", path], tmp_path, run=_capturing(store))
326 assert rc == 0, err
327 envelope = store["shortform_urls"]
328 assert envelope.posts("tiktok") == [tt_url("a", FRESH)]
329 assert envelope.counters["non-shortform"] == 1
330 assert "ScrapeCreators is configured" not in err
331
332 def test_ignored_when_neither_platform_is_searched(self, tmp_path):
333 store: dict = {}
334 missing = str(tmp_path / "nope.json")
335 rc, _, err = _cli([TOPIC, "--search", "hackernews", "--shortform-urls", missing],
336 tmp_path, run=_capturing(store))
337 assert rc == 0, err
338 assert "--shortform-urls ignored: TikTok and Instagram are not searched" in err
339 assert store.get("shortform_urls") is None
340
341 def test_a_scrapecreators_key_gets_a_one_line_note(self, tmp_path):
342 path = _write(tmp_path, _envelope([tt_url("a", FRESH)]))
343 store: dict = {}
344 rc, _, err = _cli([TOPIC, "--shortform-urls", path], tmp_path, run=_capturing(store),
345 config={"SCRAPECREATORS_API_KEY": "sc-test"})
346 assert rc == 0, err
347 notes = [line for line in err.splitlines() if "--shortform-urls" in line]
348 assert len(notes) == 1 and "ScrapeCreators is configured" in notes[0]
349 assert "sc-test" not in err
350
351 def test_wrong_schema_exits_2_without_echoing_values(self, tmp_path):
352 path = _write(tmp_path, _envelope([tt_url("a", FRESH)], schema="nope"))
353 rc, _, err = _cli([TOPIC, "--shortform-urls", path], tmp_path)
354 assert rc == 2
355 assert path in err and "schema" in err and "without --shortform-urls" in err
356 assert "nope" not in err
357
358 def test_protected_dir_exits_2(self, tmp_path):
359 cfg = tmp_path / "cfg"
360 cfg.mkdir(exist_ok=True)
361 path = _write(cfg, _envelope([tt_url("a", FRESH)]))
362 rc, _, err = _cli([TOPIC, "--shortform-urls", path], tmp_path)
363 assert rc == 2
364 assert "credential directory" in err
365
366 def test_inline_json_exits_2(self, tmp_path):
367 rc, _, err = _cli([TOPIC, "--shortform-urls", json.dumps(_envelope([tt_url("a", FRESH)]))], tmp_path)
368 assert rc == 2
369 assert "--shortform-urls accepts a file path" in err
370
371 def test_comparison_run_exits_2(self, tmp_path):
372 path = _write(tmp_path, _envelope([tt_url("a", FRESH)], topic="labubu vs smiski"))
373 rc, _, err = _cli(["labubu vs smiski", "--shortform-urls", path], tmp_path)
374 assert rc == 2
375 assert "single-topic" in err
376
377 def test_hosted_backend_rejects_the_flag(self, tmp_path):
378 path = _write(tmp_path, _envelope([tt_url("a", FRESH)]))
379 with mock.patch.object(cli.env, "read_secret_env", return_value="hosted-test-key"), \
380 mock.patch("lib.hosted.run_hosted", side_effect=AssertionError("hosted must not run")):
381 rc, _, err = _cli(
382 [TOPIC, "--shortform-urls", path], tmp_path,
383 environ={"LAST30DAYS_API_BASE": "https://hosted.example.test"},
384 )
385 assert rc == 2
386 assert "--shortform-urls is not supported by the hosted backend" in err
387
388 def test_cached_report_refuses_the_flag(self, tmp_path):
389 path = _write(tmp_path, _envelope([tt_url("a", FRESH)]))
390 synth = tmp_path / "synth.md"
391 synth.write_text("# s\n")
392 rc, _, err = _cli(
393 [TOPIC, "--cached-report", "--emit", "html", "--synthesis-file", str(synth),
394 "--shortform-urls", path], tmp_path,
395 )
396 assert rc == 2
397 assert "--cached-report" in err
398
399 def test_the_envelope_digest_binds_the_report_cache(self, tmp_path):
400 first = _read(_write(tmp_path, _envelope([tt_url("a", FRESH)]), "first.json"))
401 second = _read(_write(tmp_path, _envelope([tt_url("b", FRESH)]), "second.json"))
402 assert cli._envelope_digest(None, None, None, None) is None
403 one = cli._envelope_digest(None, None, None, first)
404 assert one and one != cli._envelope_digest(None, None, None, second)
405
405 lines PYTHON