返回 last30days-skill
test_reddit_envelope.py
根目录 / tests / test_reddit_envelope.py
1 """The ``--reddit-threads`` host lane: a host's own web search hands the engine
2 Reddit thread URLs or ids, and the engine reads only their identity, rehydrates
3 every thread, holds it to the window and the topic bar, and routes it to the
4 subquery whose terms it matches."""
5
6 from __future__ import annotations
7
8 import contextlib
9 import io
10 import json
11 import os
12 import sys
13 import time
14 from contextlib import redirect_stderr, redirect_stdout
15 from pathlib import Path
16 from unittest import mock
17
18 import pytest
19
20 import last30days as cli
21 from lib import dates, pipeline, reddit_arctic, reddit_discover, reddit_envelope, reddit_keyless, reddit_refs, schema
22
23 TOPIC = "ghostty terminal"
24 FROM, TO = dates.get_date_range(30)
25 DAY = 24 * 3600
26
27
28 # ---------------------------------------------------------------------------
29 # Builders
30 # ---------------------------------------------------------------------------
31
32
33 def _envelope(threads, **over) -> dict:
34 payload = {"schema": reddit_envelope.SCHEMA, "topic": TOPIC, "threads": threads}
35 payload.update(over)
36 return payload
37
38
39 def _write(tmp_path: Path, payload, name: str = "threads.json") -> str:
40 path = tmp_path / name
41 path.write_text(payload if isinstance(payload, str) else json.dumps(payload), encoding="utf-8")
42 return str(path)
43
44
45 def _url(pid: str, sub: str = "Ghostty") -> str:
46 return f"https://www.reddit.com/r/{sub}/comments/{pid}/some_slug/"
47
48
49 def _archive(pid: str, *, title: str, age_days: float = 3, score: int = 120,
50 comments: int = 14, sub: str = "Ghostty") -> dict:
51 """An Arctic Shift row, normalized the way fetch_posts_by_ids returns it."""
52 row = {
53 "id": pid, "title": title, "score": score, "num_comments": comments,
54 "created_utc": time.time() - age_days * DAY, "subreddit": sub,
55 "permalink": f"/r/{sub}/comments/{pid}/slug/", "author": "op", "selftext": "",
56 }
57 return reddit_arctic._normalize_listing_row(row)
58
59
60 @contextlib.contextmanager
61 def _arctic(posts):
62 """Arctic answers ``/posts/ids`` with ``posts`` and has no comment trees."""
63 by_id = {p["metadata"]["post_id"]: p for p in posts}
64
65 def fetch(ids, deadline=None):
66 return {pid: dict(by_id[pid]) for pid in ids if pid in by_id}, "ok"
67
68 with mock.patch.object(reddit_arctic, "fetch_posts_by_ids", side_effect=fetch) as lookup, \
69 mock.patch.object(reddit_arctic, "fetch_comment_tree", return_value=[]):
70 yield lookup
71
72
73 def _read(path: str, topic: str = TOPIC) -> reddit_envelope.Envelope:
74 with redirect_stderr(io.StringIO()):
75 return reddit_envelope.read(path, topic)
76
77
78 def _serve(envelope, label="", **kwargs):
79 with redirect_stderr(io.StringIO()):
80 return envelope.serve(label, from_date=FROM, to_date=TO, **kwargs)
81
82
83 # ---------------------------------------------------------------------------
84 # Reading the envelope
85 # ---------------------------------------------------------------------------
86
87
88 class TestReader:
89 def test_ae8_bad_rows_are_dropped_with_named_counters(self, tmp_path):
90 """AE8: a non-reddit URL, a Google redirect, a share link, an
91 out-of-window thread and a duplicate each drop with their own
92 counter; host titles and scores are ignored."""
93 threads = [
94 {"url": _url("aaa111"), "title": "HOST TITLE", "score": 99999},
95 {"url": "https://news.ycombinator.com/item?id=1"},
96 {"url": "https://www.google.com/url?q=https://www.reddit.com/r/Ghostty/comments/bbb222/x/"},
97 {"url": "https://www.reddit.com/r/Ghostty/s/AbCdEf123"},
98 {"url": _url("old999")},
99 {"url": "https://old.reddit.com/r/Ghostty/comments/aaa111/some_slug/k1x2y3/"},
100 {"id": "ccc333"},
101 ]
102 envelope = _read(_write(tmp_path, _envelope(threads)))
103 assert envelope.total == 7
104 assert [r.post_id for r in envelope.refs] == ["aaa111", "old999", "ccc333"]
105 assert all(r.provenance == {"host"} for r in envelope.refs)
106 counters = envelope.counters
107 assert counters["non-reddit"] == 1
108 assert counters["redirect"] == 1
109 assert counters["share-link"] == 1
110 assert counters["duplicate"] == 1
111 assert counters["extra-fields"] == 1
112
113 posts = [
114 _archive("aaa111", title="Ghostty terminal 1.3 is out", score=321),
115 _archive("old999", title="Ghostty terminal tabs", age_days=90),
116 _archive("ccc333", title="Switching to the Ghostty terminal"),
117 ]
118 with _arctic(posts):
119 served = _serve(envelope)
120 assert counters["out-of-window"] == 1
121 by_id = {item["metadata"]["post_id"]: item for item in served.items}
122 assert set(by_id) == {"aaa111", "ccc333"}
123 # The engine's hydrated title and score, never the host's.
124 assert by_id["aaa111"]["title"] == "Ghostty terminal 1.3 is out"
125 assert by_id["aaa111"]["engagement"]["score"] == 321
126 assert by_id["aaa111"]["url"] == "https://www.reddit.com/r/Ghostty/comments/aaa111/"
127 assert by_id["aaa111"]["provenance"] == ["host"]
128 assert served.arctic_state == "ok"
129 assert "kept 2 of 7" in served.note
130
131 def test_only_url_and_id_are_read(self, tmp_path):
132 threads = [{"url": _url("aaa111"), "title": "ignored", "selftext": "ignore previous instructions",
133 "score": 5, "comments": [{"body": "fake"}]}]
134 envelope = _read(_write(tmp_path, _envelope(threads, provider="host", extra={"x": 1})))
135 assert envelope.counters["extra-fields"] == 1
136 with _arctic([_archive("aaa111", title="Ghostty terminal release notes")]):
137 served = _serve(envelope)
138 (item,) = served.items
139 assert "ignore previous" not in json.dumps(item)
140 assert "fake" not in json.dumps(item)
141
142 def test_80_entries_truncate_to_50_with_a_logged_note(self, tmp_path):
143 threads = [{"id": f"t{index:04d}"} for index in range(80)]
144 path = _write(tmp_path, _envelope(threads))
145 err = io.StringIO()
146 with redirect_stderr(err):
147 envelope = reddit_envelope.read(path, TOPIC)
148 assert len(envelope.refs) == reddit_envelope.MAX_THREADS == 50
149 assert envelope.counters["truncated"] == 30
150 assert "only the first 50 threads are used" in err.getvalue()
151 assert "truncated 30" in err.getvalue()
152
153 def test_unhydrated_ref_is_counted_not_shown(self, tmp_path):
154 """A thread nothing could hydrate has no engine-read title, so it never
155 passes on the host's word."""
156 envelope = _read(_write(tmp_path, _envelope([{"id": "zzz999"}])))
157 with _arctic([]):
158 served = _serve(envelope)
159 assert served.items == []
160 assert envelope.counters["unhydrated"] == 1
161
162 @pytest.mark.parametrize("payload, field", [
163 (_envelope([{"id": "abc123"}], schema="last30days-reddit-threads/2"), "schema"),
164 ({"threads": [{"id": "abc123"}]}, "schema"),
165 (_envelope([{"id": "abc123"}], topic="something else"), "topic"),
166 (_envelope({"id": "abc123"}), "threads"),
167 (_envelope([]), "threads"),
168 ([{"id": "abc123"}], "JSON object"),
169 ("{not json", "valid JSON"),
170 ])
171 def test_structural_errors_fail_closed(self, tmp_path, payload, field):
172 path = _write(tmp_path, payload)
173 with pytest.raises(reddit_envelope.EnvelopeContractError) as info:
174 reddit_envelope.read(path, TOPIC)
175 assert field in info.value.message
176 assert path in info.value.message
177 assert "without --reddit-threads" in info.value.message
178
179 def test_too_many_entries_fails_closed(self, tmp_path):
180 path = _write(tmp_path, _envelope([{"id": "abc123"}] * (reddit_envelope.MAX_ENTRIES + 1)))
181 with pytest.raises(reddit_envelope.EnvelopeContractError):
182 reddit_envelope.read(path, TOPIC)
183
184 def test_file_bounds(self, tmp_path):
185 with pytest.raises(reddit_envelope.EnvelopeContractError, match="must be a .json file"):
186 reddit_envelope.read(_write(tmp_path, _envelope([{"id": "a1"}]), "threads.txt"), TOPIC)
187 with pytest.raises(reddit_envelope.EnvelopeContractError, match="regular file"):
188 reddit_envelope.read(str(tmp_path), TOPIC)
189 with pytest.raises(reddit_envelope.EnvelopeContractError, match="cannot be read"):
190 reddit_envelope.read(str(tmp_path / "missing.json"), TOPIC)
191 big = _write(tmp_path, "x", "big.json")
192 fake = os.stat(big)
193 with mock.patch.object(reddit_envelope, "_stat", return_value=os.stat_result(
194 (fake.st_mode, 0, 0, 0, 0, 0, reddit_envelope.MAX_BYTES + 1, 0, 0, 0),
195 )):
196 with pytest.raises(reddit_envelope.EnvelopeContractError, match="KiB limit"):
197 reddit_envelope.read(big, TOPIC)
198
199 def test_protected_dir_and_symlink_into_it_fail_closed(self, tmp_path):
200 cfg = tmp_path / "cfg"
201 cfg.mkdir()
202 inside = _write(cfg, _envelope([{"id": "abc123"}]))
203 link = tmp_path / "link.json"
204 link.symlink_to(inside)
205 with mock.patch.object(reddit_envelope.env, "CONFIG_DIR", cfg):
206 for path in (inside, str(link)):
207 with pytest.raises(reddit_envelope.EnvelopeContractError, match="credential directory"):
208 reddit_envelope.read(path, TOPIC)
209
210 def test_a_file_that_grows_after_the_size_check_is_still_bounded(self, tmp_path):
211 path = _write(tmp_path, _envelope([{"id": "abc123"}]))
212 small = os.stat(path)
213
214 def stat_then_grow(real):
215 with open(real, "ab") as handle:
216 handle.write(b" " * (reddit_envelope.MAX_BYTES + 10))
217 return small
218
219 with mock.patch.object(reddit_envelope, "_stat", side_effect=stat_then_grow), \
220 pytest.raises(reddit_envelope.EnvelopeContractError):
221 _read(path)
222
223 def test_stdin(self, tmp_path):
224 data = json.dumps(_envelope([{"id": "abc123"}])).encode()
225 fake_stdin = mock.Mock(buffer=io.BytesIO(data))
226 with mock.patch.object(sys, "stdin", fake_stdin):
227 envelope = _read(reddit_envelope.STDIN)
228 assert [r.post_id for r in envelope.refs] == ["abc123"]
229
230 def test_digest_binds_the_file_content(self, tmp_path):
231 a = _read(_write(tmp_path, _envelope([{"id": "abc123"}]), "a.json"))
232 b = _read(_write(tmp_path, _envelope([{"id": "def456"}]), "b.json"))
233 assert a.sha256 != b.sha256 and len(a.sha256) == 64
234
235
236 # ---------------------------------------------------------------------------
237 # Hydration, the bar, merging and routing
238 # ---------------------------------------------------------------------------
239
240
241 class TestLane:
242 def test_off_topic_hydrated_title_is_dropped_by_the_bar(self, tmp_path):
243 envelope = _read(_write(tmp_path, _envelope([{"id": "aaa111"}, {"id": "bbb222"}])))
244 posts = [
245 _archive("aaa111", title="Ghostty terminal ligatures finally work"),
246 _archive("bbb222", title="My cat learned to open doors", sub="cats"),
247 ]
248 with _arctic(posts):
249 served = _serve(envelope)
250 assert [i["metadata"]["post_id"] for i in served.items] == ["aaa111"]
251 assert envelope.counters["off-topic"] == 1
252
253 def test_host_and_floor_find_the_same_thread_as_one_item(self, tmp_path):
254 envelope = _read(_write(tmp_path, _envelope([{"url": _url("aaa111")}])))
255 web_ref = reddit_refs.canonical_thread("https://old.reddit.com/r/Ghostty/comments/aaa111/x/")
256 web_ref.provenance = {"web"}
257 web_ref.title = "Ghostty terminal 1.3 is out"
258 floor = reddit_discover.WebFloor(refs=[web_ref], queries=[TOPIC], rungs={"brave": "ok"})
259 posts = [_archive("aaa111", title="Ghostty terminal 1.3 is out")]
260 with _arctic(posts), \
261 mock.patch.object(reddit_discover, "web_refs", return_value=floor), \
262 mock.patch.object(reddit_keyless.reddit_search, "search", return_value=[]), \
263 mock.patch.object(reddit_keyless, "_enrich", side_effect=lambda posts, *_a, **_k: posts), \
264 redirect_stderr(io.StringIO()):
265 with reddit_envelope.lane(envelope, ""):
266 items = reddit_keyless.search_and_enrich(TOPIC, FROM, TO)
267 assert len(items) == 1
268 assert items[0]["provenance"] == ["host", "web"]
269
270 def test_fetched_subreddit_beats_the_host_urls_community(self, tmp_path):
271 envelope = _read(_write(tmp_path, _envelope([{"url": _url("aaa111", sub="WrongSub")}])))
272 posts = [_archive("aaa111", title="Ghostty terminal ligatures finally work", sub="Ghostty")]
273 with _arctic(posts):
274 served = _serve(envelope)
275 assert [i["subreddit"] for i in served.items] == ["Ghostty"]
276 assert "/r/Ghostty/" in served.items[0]["url"]
277
278 def test_no_envelope_changes_nothing(self):
279 assert reddit_envelope.current() is None
280 assert reddit_keyless._host_layer(TOPIC, "default", None, None, FROM, TO, None) == []
281
282 def test_session_hydrates_host_refs_first(self, tmp_path):
283 envelope = _read(_write(tmp_path, _envelope([{"id": "aaa111"}])))
284 live = dict(_archive("aaa111", title="Ghostty terminal live thread", score=777))
285 calls = []
286
287 def session_hydrator(refs):
288 calls.append([r.post_id for r in refs])
289 return {"aaa111": live}
290
291 with _arctic([]) as lookup:
292 served = _serve(envelope, session_hydrator=lambda: session_hydrator)
293 assert calls == [["aaa111"]]
294 lookup.assert_not_called()
295 assert served.items[0]["engagement"]["score"] == 777
296 assert served.items[0]["engagement_source"] == reddit_refs.LIVE
297
298 def test_hydrates_once_and_routes_each_subquery_its_matches(self, tmp_path):
299 envelope = _read(_write(tmp_path, _envelope([{"id": "aaa111"}, {"id": "bbb222"}, {"id": "ccc333"}])))
300 envelope.bind_subqueries([
301 ("primary", ("ghostty terminal", "")),
302 ("config", ("ghostty terminal config file", "")),
303 ("themes", ("ghostty terminal color themes", "")),
304 ])
305 posts = [
306 _archive("aaa111", title="Ghostty terminal color themes gallery"),
307 _archive("bbb222", title="Ghostty terminal config file tips"),
308 _archive("ccc333", title="Ghostty terminal color themes I made"),
309 ]
310 with _arctic(posts) as lookup:
311 routed = {label: _serve(envelope, label).items for label in ("primary", "config", "themes")}
312 again = _serve(envelope, "themes").items
313 assert lookup.call_count == 1
314 assert [i["metadata"]["post_id"] for i in routed["themes"]] == ["aaa111", "ccc333"]
315 assert [i["metadata"]["post_id"] for i in routed["config"]] == ["bbb222"]
316 assert routed["primary"] == []
317 assert again == []
318 # Each subquery gets its own copy: a merge in one stream never edits another.
319 routed["themes"][0]["title"] = "edited"
320 assert envelope._kept[0]["title"] != "edited"
321
322
323 class TestPipeline:
324 def _plan(self):
325 def sq(label, query):
326 return {"label": label, "search_query": query, "ranking_query": query, "sources": ["reddit"]}
327 return {
328 "intent": "opinion", "freshness_mode": "balanced_recent", "cluster_mode": "story",
329 "subqueries": [
330 sq("primary", "ghostty terminal"),
331 sq("config", "ghostty terminal config file"),
332 sq("themes", "ghostty terminal color themes"),
333 ],
334 "source_weights": {"reddit": 1.0},
335 }
336
337 def _run(self, envelope, **kwargs):
338 # An opinion plan keeps all three subqueries; lane-time comment
339 # enrichment is stubbed so no reddit.com request is sent.
340 with mock.patch.object(reddit_keyless.reddit_search, "search", return_value=[]), \
341 mock.patch.object(reddit_keyless, "_enrich", side_effect=lambda posts, *_a, **_k: posts), \
342 redirect_stderr(io.StringIO()):
343 return pipeline.run(
344 topic=TOPIC, config={}, depth="default", requested_sources=["reddit"],
345 mock=False, external_plan=self._plan(), web_backend="none", save_dir="",
346 reddit_threads=envelope, **kwargs,
347 )
348
349 def test_refs_reach_the_subquery_whose_terms_match(self, tmp_path):
350 envelope = _read(_write(tmp_path, _envelope([{"id": "aaa111"}, {"id": "bbb222"}])))
351 posts = [
352 _archive("aaa111", title="Ghostty terminal color themes gallery"),
353 _archive("bbb222", title="Ghostty terminal config file tips"),
354 ]
355 with _arctic(posts):
356 report = self._run(envelope)
357 labels = {
358 reddit_refs.canonical_thread(c.url).post_id: c.subquery_labels
359 for c in report.ranked_candidates if c.source == "reddit"
360 }
361 assert [sq.label for sq in report.query_plan.subqueries] == ["primary", "config", "themes"]
362 assert labels == {"aaa111": ["themes"], "bbb222": ["config"]}
363 detail = (report.source_status.get("reddit") or schema.SourceOutcome(source="reddit")).detail or ""
364 assert detail.startswith("host+arctic served")
365
366 def test_excluded_reddit_ignores_the_envelope(self, tmp_path):
367 envelope = _read(_write(tmp_path, _envelope([{"id": "aaa111"}])))
368 err = io.StringIO()
369 with _arctic([_archive("aaa111", title="Ghostty terminal")]) as lookup, \
370 redirect_stderr(err), pytest.raises(ValueError, match="No available planned sources"):
371 # The plan is Reddit-only, so excluding Reddit leaves nothing to run.
372 pipeline.run(
373 topic=TOPIC, config={"EXCLUDE_SOURCES": "reddit"}, depth="default",
374 requested_sources=None, mock=False, external_plan=self._plan(),
375 web_backend="none", save_dir="", reddit_threads=envelope,
376 )
377 lookup.assert_not_called()
378 assert "envelope ignored (reddit is excluded" in err.getvalue()
379
380
381 # ---------------------------------------------------------------------------
382 # CLI
383 # ---------------------------------------------------------------------------
384
385 _DIAG = {
386 "available_sources": ["reddit"],
387 "x_pending_browser_auth": False,
388 "native_search": False,
389 "bird_installed": False,
390 "bird_authenticated": False,
391 "bird_username": None,
392 "native_web_backend": None,
393 "safe": False,
394 }
395
396
397 def _cli(argv, tmp_path, *, run=None, environ=None):
398 out, err = io.StringIO(), io.StringIO()
399 cfg_dir = tmp_path / "cfg"
400 cfg_dir.mkdir(exist_ok=True)
401 with contextlib.ExitStack() as stack:
402 stack.enter_context(mock.patch.object(cli.env, "get_config", return_value={}))
403 stack.enter_context(mock.patch.object(cli.env, "CONFIG_DIR", cfg_dir))
404 stack.enter_context(mock.patch.object(cli.env, "CONFIG_FILE", cfg_dir / ".env"))
405 stack.enter_context(mock.patch.object(cli.ui, "ProgressDisplay", return_value=mock.Mock()))
406 stack.enter_context(mock.patch.dict(
407 os.environ, {"LAST30DAYS_SKIP_PREFLIGHT": "1", **(environ or {})}, clear=False,
408 ))
409 stack.enter_context(mock.patch.object(sys, "argv", ["last30days.py", *argv]))
410 stack.enter_context(mock.patch.object(cli.pipeline, "diagnose", return_value=dict(_DIAG)))
411 stack.enter_context(mock.patch.object(
412 cli.pipeline, "run", side_effect=run or AssertionError("pipeline.run must not run"),
413 ))
414 stack.enter_context(redirect_stdout(out))
415 stack.enter_context(redirect_stderr(err))
416 try:
417 rc = cli.main()
418 except SystemExit as exc:
419 rc = exc.code
420 return rc, out.getvalue(), err.getvalue()
421
422
423 def _fake_report(topic: str) -> schema.Report:
424 return schema.Report(
425 topic=topic, range_from=FROM, range_to=TO, generated_at="2026-11-15T00:00:00+00:00",
426 provider_runtime=schema.ProviderRuntime(reasoning_provider="local", planner_model="d", rerank_model="l"),
427 query_plan=schema.QueryPlan(intent="general", freshness_mode="balanced_recent", cluster_mode="story",
428 raw_topic=topic, subqueries=[], source_weights={}),
429 clusters=[], ranked_candidates=[], items_by_source={}, errors_by_source={},
430 )
431
432
433 def _capturing(store: dict):
434 def fake_run(**kwargs):
435 store.update(kwargs)
436 return _fake_report(kwargs["topic"])
437 return fake_run
438
439
440 class TestCli:
441 def test_flag_is_in_argparse_help(self):
442 flags = {opt for action in cli.build_parser()._actions for opt in action.option_strings}
443 assert "--reddit-threads" in flags
444
445 def test_valid_envelope_reaches_run(self, tmp_path):
446 path = _write(tmp_path, _envelope([{"url": "https://example.com/x"}, {"id": "abc123"}]))
447 store: dict = {}
448 rc, _, err = _cli([TOPIC, "--reddit-threads", path], tmp_path, run=_capturing(store))
449 assert rc == 0, err
450 envelope = store["reddit_threads"]
451 assert [r.post_id for r in envelope.refs] == ["abc123"]
452 assert envelope.counters["non-reddit"] == 1
453
454 def test_missing_file_is_ignored_when_reddit_is_not_searched(self, tmp_path):
455 store: dict = {}
456 missing = str(tmp_path / "nope.json")
457 rc, _, err = _cli([TOPIC, "--search", "hackernews", "--reddit-threads", missing],
458 tmp_path, run=_capturing(store))
459 assert rc == 0, err
460 assert "ignored: Reddit is not searched" in err
461 assert store.get("reddit_threads") is None
462
463 def test_wrong_schema_exits_2_with_remedy(self, tmp_path):
464 path = _write(tmp_path, _envelope([{"id": "abc123"}], schema="nope"))
465 rc, _, err = _cli([TOPIC, "--reddit-threads", path], tmp_path)
466 assert rc == 2
467 assert path in err and "schema" in err and "without --reddit-threads" in err
468 assert "nope" not in err
469
470 def test_protected_dir_exits_2(self, tmp_path):
471 cfg = tmp_path / "cfg"
472 cfg.mkdir(exist_ok=True)
473 path = _write(cfg, _envelope([{"id": "abc123"}]))
474 rc, _, err = _cli([TOPIC, "--reddit-threads", path], tmp_path)
475 assert rc == 2
476 assert "credential directory" in err and "without --reddit-threads" in err
477
478 def test_inline_json_exits_2(self, tmp_path):
479 rc, _, err = _cli([TOPIC, "--reddit-threads", json.dumps(_envelope([{"id": "a1"}]))], tmp_path)
480 assert rc == 2
481 assert "file path" in err
482
483 def test_comparison_run_exits_2(self, tmp_path):
484 path = _write(tmp_path, _envelope([{"id": "abc123"}], topic="ghostty vs kitty"))
485 rc, _, err = _cli(["ghostty vs kitty", "--reddit-threads", path], tmp_path)
486 assert rc == 2
487 assert "single-topic" in err
488
489 def test_hosted_backend_rejects_the_flag(self, tmp_path):
490 path = _write(tmp_path, _envelope([{"id": "abc123"}]))
491 with mock.patch.object(cli.env, "read_secret_env", return_value="hosted-test-key"), \
492 mock.patch("lib.hosted.run_hosted", side_effect=AssertionError("hosted must not run")):
493 rc, _, err = _cli(
494 [TOPIC, "--reddit-threads", path], tmp_path,
495 environ={"LAST30DAYS_API_BASE": "https://hosted.example.test"},
496 )
497 assert rc == 2
498 assert "--reddit-threads is not supported by the hosted backend" in err
499
500 def test_cached_report_refuses_the_flag(self, tmp_path):
501 path = _write(tmp_path, _envelope([{"id": "abc123"}]))
502 synth = tmp_path / "synth.md"
503 synth.write_text("# s\n")
504 rc, _, err = _cli(
505 [TOPIC, "--cached-report", "--emit", "html", "--synthesis-file", str(synth),
506 "--reddit-threads", path], tmp_path,
507 )
508 assert rc == 2
509 assert "--cached-report" in err
510
511 def test_a_different_envelope_never_replays_the_cached_report(self, tmp_path):
512 first = _write(tmp_path, _envelope([{"id": "abc123"}]), "first.json")
513 second = _write(tmp_path, _envelope([{"id": "def456"}]), "second.json")
514 synth = tmp_path / "synth.md"
515 synth.write_text("# synthesis\n")
516 cfg_dir = tmp_path / "cfg"
517 cfg_dir.mkdir(exist_ok=True)
518 argv = [TOPIC, "--emit", "html", "--synthesis-file", str(synth)]
519 options = cli._cache_research_options(cli.build_parser().parse_args([TOPIC]))
520 digest = cli._envelope_digest(None, None, _read(first))
521 assert digest != _read(first).sha256
522 assert cli._envelope_digest(None, None, None) is None
523 with mock.patch.object(cli.env, "CONFIG_DIR", cfg_dir), redirect_stderr(io.StringIO()):
524 assert cli._write_last_run(
525 TOPIC, _fake_report(TOPIC), x_envelope_sha256=digest, research_options=options,
526 )
527 with mock.patch.object(cli, "_render_save_and_print", return_value=0) as render:
528 rc, _, err = _cli([*argv, "--reddit-threads", first], tmp_path)
529 assert rc == 0, err
530 assert "Reusing cached report data" in err
531 render.assert_called_once()
532 store: dict = {}
533 with mock.patch.object(cli, "_render_save_and_print", return_value=0):
534 rc, _, err = _cli([*argv, "--reddit-threads", second], tmp_path, run=_capturing(store))
535 assert "Reusing cached report data" not in err
536 assert "running fresh research" in err
537 assert store["reddit_threads"].refs[0].post_id == "def456"
538 with mock.patch.object(cli, "_render_save_and_print", return_value=0):
539 rc, _, err = _cli(argv, tmp_path, run=_capturing({}))
540 assert "Reusing cached report data" not in err
541
541 lines PYTHON