返回 last30days-skill
test_last_run_state.py
根目录 / tests / test_last_run_state.py
1 import io
2 import json
3 import os
4 import subprocess
5 import sys
6 import tempfile
7 import unittest
8 from contextlib import redirect_stderr, redirect_stdout
9 from pathlib import Path
10 from unittest import mock
11
12 import pytest
13
14 import last30days as cli
15 from lib import dates, schema
16
17 REPO_ROOT = Path(__file__).resolve().parents[1]
18 LAST30DAYS_SCRIPT = REPO_ROOT / "skills" / "last30days" / "scripts" / "last30days.py"
19 SKILL_MD = REPO_ROOT / "skills" / "last30days" / "SKILL.md"
20
21
22 def run_last30days(topic: str, env: dict[str, str]) -> subprocess.CompletedProcess[str]:
23 return subprocess.run(
24 [sys.executable, str(LAST30DAYS_SCRIPT), topic, "--mock", "--emit=json"],
25 cwd=REPO_ROOT,
26 env=env,
27 capture_output=True,
28 text=True,
29 encoding="utf-8",
30 check=False,
31 )
32
33
34 def _report(topic: str) -> schema.Report:
35 range_from, range_to = dates.get_date_range()
36 return schema.Report(
37 topic=topic,
38 range_from=range_from,
39 range_to=range_to,
40 generated_at="2026-05-31T00:00:00+00:00",
41 provider_runtime=schema.ProviderRuntime(
42 reasoning_provider="local",
43 planner_model="mock-planner",
44 rerank_model="mock-rerank",
45 ),
46 query_plan=schema.QueryPlan(
47 intent="concept",
48 freshness_mode="balanced_recent",
49 cluster_mode="none",
50 raw_topic=topic,
51 subqueries=[
52 schema.SubQuery(
53 label="primary",
54 search_query=topic,
55 ranking_query=topic,
56 sources=["grounding"],
57 )
58 ],
59 source_weights={"grounding": 1.0},
60 ),
61 clusters=[],
62 ranked_candidates=[],
63 items_by_source={"grounding": []},
64 errors_by_source={},
65 )
66
67
68 def _diag() -> dict[str, object]:
69 return {
70 "available_sources": ["grounding"],
71 "providers": {"google": True, "openai": False, "xai": False},
72 "x_backend": None,
73 "bird_installed": True,
74 "bird_authenticated": False,
75 "bird_username": None,
76 "native_web_backend": "brave",
77 }
78
79
80 @pytest.mark.parametrize("writer", ["research", "freshness"])
81 def test_cache_writer_holds_exclusive_lock_during_publish(tmp_path, monkeypatch, writer):
82 cache_path = tmp_path / "last-report.json"
83 lock_path = cache_path.with_suffix(".lock")
84 lock_path.touch()
85 monkeypatch.setattr(cli.env, "CONFIG_DIR", tmp_path)
86 assert cli._write_last_run("Original", _report("Original"))
87 cached = cli._load_last_report_cache("Original")
88 assert cached is not None
89 probe = """
90 import errno
91 import os
92 import sys
93
94 with open(sys.argv[1], "r+b") as lock:
95 try:
96 if os.name == "nt":
97 import msvcrt
98 msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
99 else:
100 import fcntl
101 fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
102 except OSError as exc:
103 if exc.errno not in (errno.EACCES, errno.EAGAIN):
104 raise
105 print("contended")
106 else:
107 if os.name == "nt":
108 msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)
109 print("acquired")
110 """
111
112 def probe_lock():
113 return subprocess.run(
114 [sys.executable, "-I", "-c", probe, str(lock_path)],
115 check=True, capture_output=True, text=True, timeout=10,
116 ).stdout.strip()
117
118 published_paths = []
119 replace = cli.replace_private_text
120
121 def observe_publish(path, content):
122 assert probe_lock() == "contended"
123 replace(path, content)
124 published_paths.append(path)
125
126 monkeypatch.setattr(cli, "replace_private_text", observe_publish)
127 if writer == "research":
128 assert cli._write_last_run("New", _report("New"))
129 assert published_paths == [cache_path, tmp_path / "last-run.json"]
130 assert cli._load_last_report_cache("New") is not None
131 else:
132 cached.report.warnings.append("Freshness cache updated")
133 assert cli._update_cached_freshness(cached)
134 assert published_paths == [cache_path]
135 refreshed = cli._load_last_report_cache("Original")
136 assert refreshed is not None
137 assert refreshed.report.warnings == ["Freshness cache updated"]
138 assert probe_lock() == "acquired"
139
140
141 class LastRunStateTests(unittest.TestCase):
142 def test_empty_config_override_disables_last_run_write(self):
143 with tempfile.TemporaryDirectory() as tmp:
144 home = Path(tmp) / "home"
145 env = os.environ.copy()
146 env["HOME"] = str(home)
147 env["LAST30DAYS_CONFIG_DIR"] = ""
148
149 result = run_last30days("synthetic eval query", env)
150
151 self.assertEqual(result.returncode, 0, result.stderr)
152 self.assertFalse((home / ".config" / "last30days" / "last-run.json").exists())
153
154 def test_custom_config_override_writes_last_run_to_custom_dir(self):
155 with tempfile.TemporaryDirectory() as tmp:
156 config_dir = Path(tmp) / "custom-config"
157 env = os.environ.copy()
158 env["HOME"] = str(Path(tmp) / "home")
159 env["LAST30DAYS_CONFIG_DIR"] = str(config_dir)
160
161 result = run_last30days("custom config query", env)
162
163 self.assertEqual(result.returncode, 0, result.stderr)
164 payload = json.loads((config_dir / "last-run.json").read_text())
165 self.assertEqual(payload["topic"], "custom config query")
166 self.assertGreaterEqual(payload["total"], 0)
167 self.assertEqual(str(config_dir / "last-report.json"), payload["report_cache"])
168 report = json.loads((config_dir / "last-report.json").read_text(encoding="utf-8"))
169 self.assertIn(f"[last30days] Follow-up cache ID: {report['run_id']}\n", result.stderr)
170
171 def test_last_report_cache_round_trips_single_report(self):
172 with tempfile.TemporaryDirectory() as tmp:
173 config_dir = Path(tmp) / "config"
174 with mock.patch.object(cli.env, "CONFIG_DIR", config_dir):
175 report = _report("OpenClaw")
176 cli._write_last_run("OpenClaw", report)
177 loaded = cli._load_last_report_cache("OpenClaw")
178
179 self.assertIsNotNone(loaded)
180 cached_report, entity_reports, cache_path = loaded.report, loaded.entity_reports, loaded.path
181 self.assertEqual("OpenClaw", cached_report.topic)
182 self.assertIsNone(entity_reports)
183 self.assertEqual(config_dir / "last-report.json", cache_path)
184
185 def test_legacy_report_cache_remains_usable_without_run_selector(self):
186 with tempfile.TemporaryDirectory() as tmp:
187 config_dir = Path(tmp)
188 cache_path = config_dir / "last-report.json"
189 with mock.patch.object(cli.env, "CONFIG_DIR", config_dir):
190 self.assertTrue(cli._write_last_run("OpenClaw", _report("OpenClaw")))
191 payload = json.loads(cache_path.read_text(encoding="utf-8"))
192 run_id = payload.pop("run_id")
193 cache_path.write_text(json.dumps(payload), encoding="utf-8")
194
195 self.assertIsNotNone(cli._load_last_report_cache("OpenClaw"))
196 self.assertIsNone(cli._load_last_report_cache("OpenClaw", run_id=run_id))
197
198 @unittest.skipUnless(os.name == "posix", "POSIX file permissions")
199 def test_run_cache_files_are_private_before_writing(self):
200 for existing in (False, True):
201 with self.subTest(existing=existing), tempfile.TemporaryDirectory() as tmp:
202 config_dir = Path(tmp)
203 paths = [config_dir / name for name in ("last-run.json", "last-report.json")]
204 if existing:
205 for path in paths:
206 path.write_text("old evidence " * 1000)
207 path.chmod(0o644)
208 modes_at_open = []
209 real_open = io.open
210
211 def observe_open(*args, **kwargs):
212 stream = real_open(*args, **kwargs)
213 if "w" in stream.mode:
214 modes_at_open.append(os.fstat(stream.fileno()).st_mode & 0o777)
215 return stream
216
217 old_umask = os.umask(0o022)
218 try:
219 with mock.patch.object(cli.env, "CONFIG_DIR", config_dir), \
220 mock.patch("io.open", side_effect=observe_open):
221 written = cli._write_last_run("OpenClaw", _report("OpenClaw"))
222 finally:
223 os.umask(old_umask)
224
225 self.assertTrue(written)
226 self.assertEqual([0o600, 0o600], modes_at_open)
227 for path in paths:
228 self.assertEqual(0o600, path.stat().st_mode & 0o777)
229 self.assertEqual("OpenClaw", json.loads(path.read_text())["topic"])
230
231 def test_last_report_cache_expires_after_ttl(self):
232 with tempfile.TemporaryDirectory() as tmp:
233 config_dir = Path(tmp) / "config"
234 with mock.patch.object(cli.env, "CONFIG_DIR", config_dir):
235 cli._write_last_run("OpenClaw", _report("OpenClaw"))
236 cache_path = config_dir / "last-report.json"
237 payload = json.loads(cache_path.read_text(encoding="utf-8"))
238 payload["timestamp"] = "2026-01-01T00:00:00+00:00"
239 cache_path.write_text(json.dumps(payload), encoding="utf-8")
240 loaded = cli._load_last_report_cache("OpenClaw", ttl_seconds=3600)
241
242 self.assertIsNone(loaded)
243
244 def test_last_report_cache_ttl_zero_disables_reuse(self):
245 with tempfile.TemporaryDirectory() as tmp:
246 config_dir = Path(tmp) / "config"
247 with mock.patch.object(cli.env, "CONFIG_DIR", config_dir):
248 cli._write_last_run("OpenClaw", _report("OpenClaw"))
249 loaded = cli._load_last_report_cache("OpenClaw", ttl_seconds=0)
250
251 self.assertIsNone(loaded)
252
253 def test_partial_comparison_cache_does_not_degrade_to_single_report(self):
254 with tempfile.TemporaryDirectory() as tmp:
255 config_dir = Path(tmp) / "config"
256 reports = [("Alpha", _report("Alpha")), ("Beta", _report("Beta"))]
257 with mock.patch.object(cli.env, "CONFIG_DIR", config_dir):
258 cli._write_last_run("Alpha vs Beta", reports[0][1], entity_reports=reports)
259 cache_path = config_dir / "last-report.json"
260 payload = json.loads(cache_path.read_text(encoding="utf-8"))
261 payload["reports"] = payload["reports"][:1]
262 cache_path.write_text(json.dumps(payload), encoding="utf-8")
263 loaded = cli._load_last_report_cache("Alpha vs Beta")
264
265 self.assertIsNone(loaded)
266
267 def test_html_synthesis_reuses_cached_single_report_without_pipeline_run(self):
268 with tempfile.TemporaryDirectory() as tmp:
269 config_dir = Path(tmp) / "config"
270 synthesis_path = Path(tmp) / "synthesis.md"
271 synthesis_path.write_text("# OpenClaw\n\nCached synthesis body.", encoding="utf-8")
272 with mock.patch.object(cli.env, "CONFIG_DIR", config_dir):
273 cli._write_last_run("OpenClaw", _report("OpenClaw"))
274
275 with mock.patch.object(cli.env, "CONFIG_DIR", config_dir), \
276 mock.patch.object(cli.env, "get_config", return_value={}) as get_config, \
277 mock.patch.object(cli.pipeline, "diagnose", return_value=_diag()), \
278 mock.patch.object(cli.pipeline, "run", side_effect=AssertionError("pipeline should not run")), \
279 mock.patch.object(sys, "argv", [
280 "last30days.py",
281 "OpenClaw",
282 "--emit=html",
283 "--synthesis-file",
284 str(synthesis_path),
285 ]), \
286 mock.patch.dict(
287 os.environ,
288 {"LAST30DAYS_SKIP_PREFLIGHT": "1", "CLAUDECODE": "1"},
289 clear=False,
290 ):
291 stdout = io.StringIO()
292 stderr = io.StringIO()
293 with redirect_stdout(stdout), redirect_stderr(stderr):
294 rc = cli.main()
295
296 self.assertEqual(0, rc)
297 self.assertEqual(
298 "plan_only", get_config.call_args.kwargs["policy"].browser_cookies
299 )
300 self.assertIn("Cached synthesis body.", stdout.getvalue())
301 self.assertIn("Reusing cached report data", stderr.getvalue())
302
303 def test_deep_research_bypasses_html_synthesis_cache(self):
304 with tempfile.TemporaryDirectory() as tmp:
305 config_dir = Path(tmp) / "config"
306 synthesis_path = Path(tmp) / "synthesis.md"
307 synthesis_path.write_text("# Cached synthesis", encoding="utf-8")
308 with mock.patch.object(cli.env, "CONFIG_DIR", config_dir):
309 cli._write_last_run("OpenClaw", _report("OpenClaw"))
310
311 fresh_report = _report("OpenClaw")
312 config = {"OPENROUTER_API_KEY": "or-test"}
313 with mock.patch.object(cli.env, "CONFIG_DIR", config_dir), \
314 mock.patch.object(cli.env, "get_config", return_value=config), \
315 mock.patch("lib.resolve.auto_resolve", return_value={}), \
316 mock.patch.object(cli.pipeline, "diagnose", return_value=_diag()), \
317 mock.patch.object(cli.pipeline, "run", return_value=fresh_report) as run_mock, \
318 mock.patch.object(cli.ui, "ProgressDisplay"), \
319 mock.patch.object(cli, "_load_last_report_cache") as cache_mock, \
320 mock.patch.object(sys, "argv", [
321 "last30days.py",
322 "OpenClaw",
323 "--deep-research",
324 "--emit=html",
325 "--synthesis-file",
326 str(synthesis_path),
327 ]), \
328 mock.patch.dict(
329 os.environ,
330 {"LAST30DAYS_SKIP_PREFLIGHT": "1"},
331 clear=False,
332 ):
333 with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
334 rc = cli.main()
335
336 self.assertEqual(0, rc)
337 cache_mock.assert_not_called()
338 run_mock.assert_called_once()
339 self.assertTrue(run_mock.call_args.kwargs["config"]["_deep_research"])
340
341 def test_html_synthesis_reuses_cached_comparison_reports(self):
342 with tempfile.TemporaryDirectory() as tmp:
343 config_dir = Path(tmp) / "config"
344 synthesis_path = Path(tmp) / "synthesis.md"
345 synthesis_path.write_text(
346 "# Alpha vs Beta\n\nCached comparison body.",
347 encoding="utf-8",
348 )
349 reports = [("Alpha", _report("Alpha")), ("Beta", _report("Beta"))]
350 with mock.patch.object(cli.env, "CONFIG_DIR", config_dir):
351 cli._write_last_run("Alpha vs Beta", reports[0][1], entity_reports=reports)
352
353 with mock.patch.object(cli.env, "CONFIG_DIR", config_dir), \
354 mock.patch.object(cli.env, "get_config", return_value={}), \
355 mock.patch.object(cli.pipeline, "diagnose", return_value=_diag()), \
356 mock.patch.object(cli.pipeline, "run", side_effect=AssertionError("pipeline should not run")), \
357 mock.patch.object(sys, "argv", [
358 "last30days.py",
359 "Alpha",
360 "vs",
361 "Beta",
362 "--emit=html",
363 "--synthesis-file",
364 str(synthesis_path),
365 ]), \
366 mock.patch.dict(os.environ, {"LAST30DAYS_SKIP_PREFLIGHT": "1"}, clear=False):
367 stdout = io.StringIO()
368 stderr = io.StringIO()
369 with redirect_stdout(stdout), redirect_stderr(stderr):
370 rc = cli.main()
371
372 self.assertEqual(0, rc)
373 self.assertIn("Cached comparison body.", stdout.getvalue())
374 self.assertIn("last30days · Alpha vs Beta", stdout.getvalue())
375 self.assertIn("Reusing cached report data", stderr.getvalue())
376
377 def test_html_synthesis_warns_and_falls_back_when_cache_topic_misses(self):
378 with tempfile.TemporaryDirectory() as tmp:
379 config_dir = Path(tmp) / "config"
380 synthesis_path = Path(tmp) / "synthesis.md"
381 synthesis_path.write_text("Cached synthesis body.", encoding="utf-8")
382 with mock.patch.object(cli.env, "CONFIG_DIR", config_dir):
383 cli._write_last_run("OpenClaw", _report("OpenClaw"))
384
385 fresh_report = _report("Different Topic")
386 with mock.patch.object(cli.env, "CONFIG_DIR", config_dir), \
387 mock.patch.object(cli.env, "get_config", return_value={}), \
388 mock.patch.object(cli.pipeline, "diagnose", return_value=_diag()), \
389 mock.patch.object(cli.pipeline, "run", return_value=fresh_report) as run_mock, \
390 mock.patch.object(cli.ui, "ProgressDisplay"), \
391 mock.patch.object(sys, "argv", [
392 "last30days.py",
393 "Different",
394 "Topic",
395 "--emit=html",
396 "--synthesis-file",
397 str(synthesis_path),
398 ]), \
399 mock.patch.dict(os.environ, {"LAST30DAYS_SKIP_PREFLIGHT": "1"}, clear=False):
400 stdout = io.StringIO()
401 stderr = io.StringIO()
402 with redirect_stdout(stdout), redirect_stderr(stderr):
403 rc = cli.main()
404
405 self.assertEqual(0, rc)
406 self.assertTrue(run_mock.called)
407 self.assertIn("No matching cached report data", stderr.getvalue())
408 self.assertIn("Cached synthesis body.", stdout.getvalue())
409
410 def test_html_synthesis_falls_back_when_cache_is_stale(self):
411 with tempfile.TemporaryDirectory() as tmp:
412 config_dir = Path(tmp) / "config"
413 synthesis_path = Path(tmp) / "synthesis.md"
414 synthesis_path.write_text("Cached synthesis body.", encoding="utf-8")
415 with mock.patch.object(cli.env, "CONFIG_DIR", config_dir):
416 cli._write_last_run("OpenClaw", _report("OpenClaw"))
417 cache_path = config_dir / "last-report.json"
418 payload = json.loads(cache_path.read_text(encoding="utf-8"))
419 payload["timestamp"] = "2026-01-01T00:00:00+00:00"
420 cache_path.write_text(json.dumps(payload), encoding="utf-8")
421
422 fresh_report = _report("OpenClaw")
423 with mock.patch.object(cli.env, "CONFIG_DIR", config_dir), \
424 mock.patch.object(cli.env, "get_config", return_value={}), \
425 mock.patch.object(cli.pipeline, "diagnose", return_value=_diag()), \
426 mock.patch.object(cli.pipeline, "run", return_value=fresh_report) as run_mock, \
427 mock.patch.object(cli.ui, "ProgressDisplay"), \
428 mock.patch.object(sys, "argv", [
429 "last30days.py",
430 "OpenClaw",
431 "--emit=html",
432 "--synthesis-file",
433 str(synthesis_path),
434 ]), \
435 mock.patch.dict(os.environ, {"LAST30DAYS_SKIP_PREFLIGHT": "1"}, clear=False):
436 stdout = io.StringIO()
437 stderr = io.StringIO()
438 with redirect_stdout(stdout), redirect_stderr(stderr):
439 rc = cli.main()
440
441 self.assertEqual(0, rc)
442 self.assertTrue(run_mock.called)
443 self.assertIn("No matching cached report data", stderr.getvalue())
444 self.assertIn("Cached synthesis body.", stdout.getvalue())
445
446
447 class TestSkillMdFirstRunReference(unittest.TestCase):
448 """Verifies SKILL.md references that exist in the CLI."""
449
450 def test_nux_wizard_not_referenced(self):
451 from tests.skill_contract import contract_documents
452
453 content = "\n".join(contract_documents().values())
454 self.assertNotIn(
455 "nux-wizard.md", content,
456 "SKILL.md should not reference the missing nux-wizard.md file",
457 )
458
459 def test_skill_md_references_setup_command(self):
460 from tests.skill_contract import reference_text
461
462 content = reference_text("setup-wizard")
463 self.assertIn(
464 'last30days.py" setup', content,
465 "SKILL.md should reference the Python setup subcommand",
466 )
467
468 def test_setup_subcommand_dispatches(self):
469 """topic 'setup' must reach setup_wizard, not be swallowed by argparse."""
470 with mock.patch.object(cli.env, "get_config", return_value={}), \
471 mock.patch("lib.setup_wizard.run_auto_setup", return_value={"cookies_found": {}}) as mock_setup, \
472 mock.patch("lib.setup_wizard.write_setup_config") as mock_write, \
473 mock.patch("lib.setup_wizard.get_setup_status_text", return_value="ok"), \
474 mock.patch.object(sys, "argv", ["last30days.py", "setup"]):
475 stderr = io.StringIO()
476 with redirect_stderr(stderr):
477 rc = cli.main()
478 self.assertEqual(0, rc)
479 mock_setup.assert_called_once()
480 mock_write.assert_called_once()
481
482
483
484 if __name__ == "__main__":
485 unittest.main()
486
486 lines PYTHON