返回 last30days-skill
test_cr20_entrypoints.py
根目录 / tests / test_cr20_entrypoints.py
1 import json
2 import sys
3 from unittest import mock
4
5 import pytest
6
7 import last30days as cli
8 from lib import hosted, setup_wizard
9 from tests.test_last_run_state import _diag, _report
10 from tests.competitor_cli_audit_helpers import run_competitor_cli
11
12
13 @pytest.mark.parametrize("topic", [
14 "setup", "doctor", "library feed", "library search example", "queue list",
15 "queue cover example", "ordinary research", "--mock",
16 ])
17 def test_research_only_dispatches_reserved_topics_as_research(monkeypatch, topic, capsys):
18 research = mock.Mock(side_effect=lambda **kwargs: _report(kwargs["topic"]))
19 monkeypatch.setattr(cli.pipeline, "run", research)
20 monkeypatch.setattr(cli.pipeline, "diagnose", lambda *_args, **_kwargs: _diag())
21 for name in ("_run_library_feed", "_run_library_search", "_run_queue_list", "_run_queue_cover"):
22 monkeypatch.setattr(cli, name, mock.Mock(side_effect=AssertionError("administrative dispatch")))
23 monkeypatch.setattr(setup_wizard, "run_auto_setup", mock.Mock(side_effect=AssertionError("setup invoked")))
24 monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")
25 monkeypatch.setattr(sys, "argv", [
26 "last30days.py", "--research-only", "--emit=json", "--json-profile=raw", "--mock",
27 "--no-browser-cookies", "--save-dir", "", "--", topic,
28 ])
29
30 assert cli.main() == 0
31 research.assert_called_once()
32 assert research.call_args.kwargs["topic"] == topic
33 assert json.loads(capsys.readouterr().out)["topic"] == topic
34 assert not cli.env.CONFIG_FILE.exists()
35
36
37 def test_explicit_setup_still_dispatches(monkeypatch, capsys):
38 setup = mock.Mock(return_value={})
39 monkeypatch.setattr(setup_wizard, "run_auto_setup", setup)
40 monkeypatch.setattr(sys, "argv", ["last30days.py", "setup", "--no-browser-cookies"])
41
42 assert cli.main() == 0
43 setup.assert_called_once()
44 assert cli.env.CONFIG_FILE.exists()
45
46
47 def test_main_dedicated_subreddits_do_not_leak_to_peers(monkeypatch, tmp_path):
48 observed = run_competitor_cli(
49 monkeypatch, tmp_path,
50 args=["--dedicated-subreddits", "MainHome", "--subreddits", "MainCategory"],
51 config={"BRAVE_API_KEY": "dummy-brave-key"}, has_backend=True,
52 resolutions={"PeerOne": {"subreddits": ["PeerHome"]}, "PeerTwo": {}},
53 )
54
55 assert observed.calls["MainBrand"]["config"]["_dedicated_subreddits"] == ["MainHome"]
56 assert observed.calls["MainBrand"]["subreddits"] == ["MainCategory"]
57 assert observed.calls["PeerOne"]["subreddits"] == ["PeerHome"]
58 assert observed.calls["PeerTwo"]["subreddits"] is None
59 for peer in ("PeerOne", "PeerTwo"):
60 assert "_dedicated_subreddits" not in observed.calls[peer]["config"]
61
62
63 @pytest.mark.parametrize("window, cached_from, reuse", [
64 ([], "2026-05-01", False),
65 (["--days=30", "--as-of=2026-05-31"], "2026-05-01", True),
66 (["--days=7", "--as-of=2026-05-31"], "2026-05-01", False),
67 (["--days=30", "--as-of=2020-01-31"], "2026-05-01", False),
68 pytest.param(["--days=0", "--as-of=2026-05-31"], "2026-05-01", False, id="zero-days-rejects-thirty-day-cache"),
69 pytest.param(["--days=0", "--as-of=2026-05-31"], "2026-05-31", True, id="zero-days-reuses-same-day-cache"),
70 ])
71 def test_html_cache_respects_requested_window(monkeypatch, tmp_path, window, cached_from, reuse, capsys):
72 report = _report("OpenClaw")
73 report.range_from, report.range_to = cached_from, "2026-05-31"
74 monkeypatch.setattr(cli.env, "get_config", lambda **kwargs: {})
75 assert cli._write_last_run(report.topic, report)
76 synthesis = tmp_path / "synthesis.md"
77 synthesis.write_text("# Cached synthesis", encoding="utf-8")
78 research = mock.Mock(return_value=report)
79 monkeypatch.setattr(cli.pipeline, "run", research)
80 monkeypatch.setattr(cli.pipeline, "diagnose", lambda *_args, **_kwargs: _diag())
81 monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")
82 monkeypatch.setenv("LAST30DAYS_ALLOW_ENGINE_PLAN", "1")
83 monkeypatch.setattr(sys, "argv", [
84 "last30days.py", "OpenClaw", "--emit=html", "--synthesis-file", str(synthesis), *window,
85 ])
86
87 assert cli.main() == 0
88 assert research.call_count == (0 if reuse else 1)
89 if "--days=0" in window and not reuse:
90 assert research.call_args.kwargs["lookback_days"] == 0
91 assert ("Reusing cached report" in capsys.readouterr().err) == reuse
92
93
94 def test_comparison_html_cache_survives_plan_cleanup(monkeypatch, tmp_path, capsys):
95 plan = tmp_path / "competitors.json"
96 plan.write_text(json.dumps({"PeerOne": {"subreddits": ["peerone"]}}), encoding="utf-8")
97 run_competitor_cli(monkeypatch, tmp_path, args=["--competitors-plan", str(plan)])
98 plan.unlink()
99 capsys.readouterr()
100 synthesis = tmp_path / "synthesis.md"
101 synthesis.write_text("# Comparison synthesis\n\nMainBrand and peers.", encoding="utf-8")
102 research = mock.Mock(side_effect=AssertionError("cached export must not research"))
103 monkeypatch.setattr(cli.pipeline, "run", research)
104 monkeypatch.setattr(sys, "argv", [
105 "last30days.py", "MainBrand", "--cached-report", "--emit=html",
106 "--synthesis-file", str(synthesis),
107 ])
108
109 assert cli.main() == 0
110 output = capsys.readouterr().out
111 assert "Comparison synthesis" in output
112 assert "PeerOne" in output and "PeerTwo" in output
113 research.assert_not_called()
114
115
116 @pytest.mark.parametrize("expired", [False, True])
117 def test_cache_only_export_does_not_fall_back_to_research(monkeypatch, tmp_path, expired):
118 if expired:
119 assert cli._write_last_run("OpenClaw", _report("OpenClaw"))
120 path = cli.env.CONFIG_DIR / "last-report.json"
121 payload = json.loads(path.read_text())
122 payload["timestamp"] = "2020-01-01T00:00:00+00:00"
123 path.write_text(json.dumps(payload))
124 synthesis = tmp_path / "synthesis.md"
125 synthesis.write_text("Existing synthesis", encoding="utf-8")
126 research = mock.Mock(side_effect=AssertionError("unexpected research"))
127 monkeypatch.setattr(cli.pipeline, "run", research)
128 monkeypatch.setattr(sys, "argv", [
129 "last30days.py", "OpenClaw", "--cached-report", "--emit=html",
130 "--synthesis-file", str(synthesis),
131 ])
132
133 assert cli.main() == 2
134 research.assert_not_called()
135
136
137 @pytest.mark.parametrize("initial, followup, reused", [
138 (["--search=reddit"], ["--search=reddit"], True),
139 (["--search=reddit"], ["--search=x"], False),
140 (["--subreddits=Home"], ["--subreddits=Other"], False),
141 ([], ["--hiring-signals"], False),
142 (["--web-backend=none"], ["--web-backend=auto"], False),
143 ])
144 def test_cache_matches_explicit_research_scope(monkeypatch, tmp_path, initial, followup, reused):
145 report = _report("OpenClaw")
146 research = mock.Mock(return_value=report)
147 monkeypatch.setattr(cli.pipeline, "run", research)
148 monkeypatch.setattr(cli.pipeline, "diagnose", lambda *_args, **_kwargs: _diag())
149 monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")
150 monkeypatch.setenv("LAST30DAYS_ALLOW_ENGINE_PLAN", "1")
151 monkeypatch.setattr(sys, "argv", ["last30days.py", "OpenClaw", *initial])
152 assert cli.main() == 0
153 research.reset_mock()
154 synthesis = tmp_path / "synthesis.md"
155 synthesis.write_text("Existing synthesis", encoding="utf-8")
156 monkeypatch.setattr(sys, "argv", [
157 "last30days.py", "OpenClaw", "--emit=html", "--synthesis-file", str(synthesis), *followup,
158 ])
159
160 assert cli.main() == 0
161 assert research.call_count == (0 if reused else 1)
162
163
164 def test_cache_matches_plan_content_not_temporary_filename(monkeypatch, tmp_path):
165 plan = tmp_path / "plan.json"
166 plan.write_text(json.dumps({"subqueries": [{"search_query": "first"}]}))
167 options = cli._cache_research_options(cli.build_parser().parse_args(["OpenClaw", "--plan", str(plan)]))
168 assert cli._write_last_run("OpenClaw", _report("OpenClaw"), research_options=options)
169 same_plan = tmp_path / "new-plan.json"
170 same_plan.write_text(plan.read_text())
171 same_options = cli._cache_research_options(cli.build_parser().parse_args(["OpenClaw", "--plan", str(same_plan)]))
172 assert cli._load_last_report_cache("OpenClaw", research_options=same_options)
173 plan.write_text(json.dumps({"subqueries": [{"search_query": "different"}]}))
174 changed_options = cli._cache_research_options(cli.build_parser().parse_args(["OpenClaw", "--plan", str(plan)]))
175 assert cli._load_last_report_cache("OpenClaw", research_options=changed_options) is None
176
177
178 @pytest.mark.parametrize("cached", [False, True])
179 def test_cached_export_never_calls_hosted_research(monkeypatch, tmp_path, cached, capsys):
180 if cached:
181 assert cli._write_last_run("OpenClaw", _report("OpenClaw"))
182 synthesis = tmp_path / "synthesis.md"
183 synthesis.write_text("# Stored report export", encoding="utf-8")
184 remote = mock.Mock(return_value=123)
185 local = mock.Mock(side_effect=AssertionError("unexpected local research"))
186 monkeypatch.setattr(hosted, "run_hosted", remote)
187 monkeypatch.setattr(cli.pipeline, "run", local)
188 monkeypatch.setenv("LAST30DAYS_API_KEY", "dummy-hosted-key")
189 monkeypatch.setenv("LAST30DAYS_API_BASE", "https://hosted.example.test")
190 monkeypatch.setattr(sys, "argv", [
191 "last30days.py", "OpenClaw", "--cached-report", "--emit=html",
192 "--synthesis-file", str(synthesis),
193 ])
194
195 assert cli.main() == (0 if cached else 2)
196 remote.assert_not_called()
197 local.assert_not_called()
198 if cached:
199 assert "Stored report export" in capsys.readouterr().out
200
201
202 def test_ordinary_synthesis_rejects_changed_source_exclusions(monkeypatch, tmp_path):
203 config = {"EXCLUDE_SOURCES": "reddit", "SCRAPECREATORS_API_KEY": "dummy-private-key"}
204 monkeypatch.setattr(cli.env, "get_config", lambda **kwargs: dict(config))
205 research = mock.Mock(side_effect=lambda **kwargs: _report(kwargs["topic"]))
206 monkeypatch.setattr(cli.pipeline, "run", research)
207 monkeypatch.setattr(cli.pipeline, "diagnose", lambda *_args, **_kwargs: _diag())
208 monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")
209 monkeypatch.setenv("LAST30DAYS_ALLOW_ENGINE_PLAN", "1")
210 monkeypatch.setattr(sys, "argv", ["last30days.py", "OpenClaw"])
211 assert cli.main() == 0
212 assert "dummy-private-key" not in (cli.env.CONFIG_DIR / "last-report.json").read_text()
213 research.reset_mock()
214 config["EXCLUDE_SOURCES"] = "x"
215 synthesis = tmp_path / "synthesis.md"
216 synthesis.write_text("Stored synthesis", encoding="utf-8")
217 monkeypatch.setattr(sys, "argv", [
218 "last30days.py", "OpenClaw", "--emit=html", "--synthesis-file", str(synthesis),
219 ])
220
221 assert cli.main() == 0
222 research.assert_called_once()
223 assert research.call_args.kwargs["config"]["EXCLUDE_SOURCES"] == "x"
224
225
226 @pytest.mark.parametrize("other_mode", ["--welcome", "--preflight", "--discover=ai", "--verify-freshness"])
227 def test_cache_only_rejects_other_modes_before_dispatch(monkeypatch, tmp_path, other_mode):
228 synthesis = tmp_path / "synthesis.md"
229 synthesis.write_text("Stored synthesis", encoding="utf-8")
230 monkeypatch.setattr(cli.env, "get_config", mock.Mock(side_effect=AssertionError("dispatch began")))
231 monkeypatch.setattr(sys, "argv", [
232 "last30days.py", "OpenClaw", "--cached-report", "--emit=html", "--synthesis-file", str(synthesis), other_mode,
233 ])
234
235 with pytest.raises(SystemExit) as exc:
236 cli.main()
237 assert exc.value.code == 2
238
239
240 def test_cache_only_without_topic_rejects_freshness_before_dispatch(monkeypatch, tmp_path):
241 synthesis = tmp_path / "synthesis.md"
242 synthesis.write_text("Stored synthesis", encoding="utf-8")
243 monkeypatch.setattr(cli.env, "get_config", mock.Mock(side_effect=AssertionError("dispatch began")))
244 monkeypatch.setattr(cli, "_run_cached_freshness", mock.Mock(side_effect=AssertionError("freshness dispatched")))
245 monkeypatch.setattr(sys, "argv", [
246 "last30days.py", "--cached-report", "--emit=html", "--synthesis-file", str(synthesis), "--verify-freshness",
247 ])
248
249 with pytest.raises(SystemExit) as exc:
250 cli.main()
251 assert exc.value.code == 2
252
253
254 @pytest.fixture
255 def corpus_cache_cli(monkeypatch, tmp_path):
256 projects = {name: tmp_path / name for name in ("project-a", "project-b")}
257 for name, directory in projects.items():
258 notes = directory / "notes"
259 notes.mkdir(parents=True)
260 (notes / "mcp.md").write_text(
261 f"MCP servers provide local tools and resources. Private notes from {name}.",
262 encoding="utf-8",
263 )
264 synthesis = tmp_path / "synthesis.md"
265 synthesis.write_text("# MCP server synthesis", encoding="utf-8")
266 config = {}
267 research = mock.Mock(wraps=cli.pipeline.run)
268 monkeypatch.setattr(cli.pipeline, "run", research)
269 monkeypatch.setattr(cli.pipeline, "diagnose", lambda *_args, **_kwargs: _diag())
270 monkeypatch.setattr(cli.env, "get_config", lambda **kwargs: dict(config))
271 monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")
272
273 def run(project, *, cli_path=None, config_path=None, synthesize=False, cached_only=False):
274 monkeypatch.chdir(projects[project])
275 config.clear()
276 if config_path is not None:
277 config["LAST30DAYS_CORPUS_DIRS"] = config_path
278 argv = [
279 "last30days.py", "MCP servers", "--mock", "--quick", "--search=corpus",
280 "--no-browser-cookies", "--corpus-all-time", "--save-dir=",
281 ]
282 if cli_path is not None:
283 argv += ["--corpus", cli_path]
284 if synthesize:
285 argv += ["--emit=html", "--synthesis-file", str(synthesis)]
286 else:
287 argv += ["--emit=json", "--json-profile=raw"]
288 if cached_only:
289 argv.append("--cached-report")
290 monkeypatch.setattr(sys, "argv", argv)
291 return cli.main()
292
293 return projects, research, run
294
295
296 @pytest.mark.parametrize("configured", [False, True], ids=["cli", "config"])
297 def test_relative_corpus_cache_cannot_cross_project_directories(corpus_cache_cli, configured, capsys):
298 projects, research, run = corpus_cache_cli
299 scope = {"config_path" if configured else "cli_path": "notes"}
300 assert run("project-a", **scope) == 0
301 first = json.loads(capsys.readouterr().out)
302 assert "project-a" in first["items_by_source"]["corpus"][0]["body"]
303 research.reset_mock()
304
305 assert run("project-b", synthesize=True, **scope) == 0
306 research.assert_called_once()
307 assert research.call_args.kwargs["config"]["_CORPUS_DIRS"] == [str(projects["project-b"] / "notes")]
308 stored = json.loads((cli.env.CONFIG_DIR / "last-report.json").read_text())
309 assert "project-b" in stored["reports"][0]["report"]["items_by_source"]["corpus"][0]["body"]
310
311
312 @pytest.mark.parametrize("initial_layer, followup_layer", [
313 ("cli_path", "cli_path"), ("config_path", "config_path"),
314 ("config_path", "cli_path"), ("cli_path", "config_path"),
315 ])
316 def test_corpus_cache_matches_effective_paths_across_aliases_and_layers(
317 corpus_cache_cli, initial_layer, followup_layer,
318 ):
319 projects, research, run = corpus_cache_cli
320 assert run("project-a", **{initial_layer: "notes"}) == 0
321 research.reset_mock()
322
323 assert run("project-b", synthesize=True, **{followup_layer: str(projects["project-a"] / "notes")}) == 0
324 research.assert_not_called()
325
326
327 @pytest.mark.parametrize("explicit, configured, expected", [
328 (None, "notes", 0),
329 ("notes", None, 2),
330 ("absolute-a", None, 0),
331 ("absolute-a", "notes", 2),
332 ])
333 def test_cached_export_corpus_override_matches_effective_directories(
334 corpus_cache_cli, explicit, configured, expected,
335 ):
336 projects, research, run = corpus_cache_cli
337 assert run("project-a", config_path="notes") == 0
338 research.reset_mock()
339 if explicit == "absolute-a":
340 explicit = str(projects["project-a"] / "notes")
341
342 assert run("project-b", cli_path=explicit, config_path=configured, synthesize=True, cached_only=True) == expected
343 research.assert_not_called()
344
344 lines PYTHON