返回 last30days-skill
test_watchlist_strict_exit.py
根目录 / tests / test_watchlist_strict_exit.py
1 """Exercise strict child results through the watchlist and its database."""
2
3 import json
4 from dataclasses import replace
5 from unittest.mock import Mock
6
7 import pytest
8
9 import last30days as cli
10 import store
11 import watchlist
12 from lib import library_index, schema
13
14
15 def _install_child(tmp_path, monkeypatch, results):
16 (tmp_path / "last30days.py").write_text(
17 f"import sys\nstdout, stderr, exit_code = {results!r}[sys.argv[-1]]\n"
18 "sys.stdout.write(stdout)\nsys.stderr.write(stderr)\nraise SystemExit(exit_code)\n",
19 encoding="utf-8",
20 )
21 monkeypatch.setattr(watchlist, "SCRIPT_DIR", tmp_path)
22
23
24 @pytest.fixture
25 def watchlist_report(tmp_path, monkeypatch, capsys):
26 monkeypatch.setattr(store, "_db_override", tmp_path / "research.db")
27 topic = store.add_topic("Example")
28 item = schema.SourceItem(
29 item_id="r1", source="reddit", title="A useful finding",
30 body="Evidence from Reddit", url="https://www.reddit.com/r/example/comments/r1/",
31 )
32 report = schema.Report(
33 topic=topic["name"],
34 range_from="2026-04-01",
35 range_to="2026-07-01",
36 generated_at="2026-07-01T00:00:00Z",
37 provider_runtime=schema.ProviderRuntime("local", "local", "local"),
38 query_plan=schema.QueryPlan(
39 "general", "recent", "story", topic["name"], [], {},
40 ),
41 clusters=[],
42 ranked_candidates=[],
43 items_by_source={"reddit": [item]},
44 errors_by_source={"x": "rate-limited"},
45 source_status={
46 "reddit": schema.SourceOutcome("reddit", "ok", items_returned=1),
47 "x": schema.SourceOutcome("x", "rate-limited"),
48 },
49 )
50 args = cli.build_parser().parse_args([
51 "--emit=json", "--json-profile=raw", "--save-dir", "", topic["name"],
52 ])
53 assert cli._render_save_and_print(args, report, None, None, {"LAST30DAYS_STRICT_EXIT": "1"}) == 3
54 output = capsys.readouterr()
55 return topic, item, output.out, output.err
56
57
58 @pytest.mark.parametrize(
59 ("case", "exit_code", "want_status"),
60 [
61 ("normal", 0, "completed"),
62 ("degraded", 3, "degraded"),
63 ("clarification", 3, "failed"),
64 ("unrelated-code-three", 3, "failed"),
65 ("invalid-report", 3, "failed"),
66 ("hard-failure", 1, "failed"),
67 ],
68 )
69 def test_watchlist_persists_only_completed_reports(
70 tmp_path, monkeypatch, watchlist_report, case, exit_code, want_status,
71 ):
72 topic, item, raw_report, receipt = watchlist_report
73 notice = Mock()
74 monkeypatch.setattr(watchlist, "_send_generic_webhook", notice)
75 store.set_setting("delivery_channel", "https://webhook.example/notify")
76
77 stdout = {
78 "clarification": "",
79 "invalid-report": "{}",
80 }.get(case, raw_report)
81 stderr = (
82 receipt if case in {"degraded", "invalid-report", "hard-failure"}
83 else "Choose what to research\n" if exit_code else ""
84 )
85 _install_child(tmp_path, monkeypatch, {topic["name"]: (stdout, stderr, exit_code)})
86 result = watchlist._run_topic(topic)
87
88 assert result["status"] == want_status
89 assert store.list_topics()[0]["last_status"] == want_status
90 findings = store.get_new_findings(topic["id"])
91 if want_status == "failed":
92 assert findings == []
93 notice.assert_not_called()
94 return
95
96 assert result["new"] == 1
97 assert [finding["source_url"] for finding in findings] == [item.url]
98 matches = library_index.search(
99 "Evidence from Reddit",
100 db_path=tmp_path / "library.db",
101 store_db_path=tmp_path / "research.db",
102 )
103 assert [(match.topic, match.url) for match in matches] == [(topic["name"], item.url)]
104 notice.assert_called_once()
105 assert ("degraded coverage" in notice.call_args.args[1]) == (want_status == "degraded")
106
107
108 def test_late_delivery_error_does_not_reclassify_report(tmp_path, monkeypatch, watchlist_report):
109 topic, item, raw_report, receipt = watchlist_report
110 _install_child(tmp_path, monkeypatch, {topic["name"]: (raw_report, receipt, 3)})
111 notice = Mock(side_effect=ValueError("test delivery error"))
112 monkeypatch.setattr(watchlist, "_deliver_findings", notice)
113
114 with pytest.raises(ValueError, match="test delivery error"):
115 watchlist._run_topic(topic)
116
117 assert store.list_topics()[0]["last_status"] == "degraded"
118 assert [finding["source_url"] for finding in store.get_new_findings(topic["id"])] == [item.url]
119
120
121 @pytest.mark.parametrize("use_fallback", [False, True], ids=["sqlite-default", "sqlite-fallback"])
122 def test_watchlist_alerts_each_topic_once_for_a_shared_url(
123 tmp_path, monkeypatch, capsys, watchlist_report, use_fallback,
124 ):
125 if use_fallback:
126 monkeypatch.setattr(store, "_SUPPORTS_RETURNING", False)
127 first, item, raw_report, _ = watchlist_report
128 second = store.add_topic("Later topic")
129 second_report = json.loads(raw_report)
130 second_report["topic"] = second["name"]
131 second_report["query_plan"]["raw_topic"] = second["name"]
132 _install_child(tmp_path, monkeypatch, {
133 first["name"]: (raw_report, "", 0),
134 second["name"]: (json.dumps(second_report), "", 0),
135 })
136 store.set_setting("delivery_channel", "https://webhook.example/notify")
137 notice = Mock()
138 monkeypatch.setattr(watchlist, "_send_generic_webhook", notice)
139
140 watchlist.cmd_run_all(None)
141 results = json.loads(capsys.readouterr().out)["results"]
142 names = [first["name"], second["name"]]
143 assert [(r["topic"], r["new"], r["updated"]) for r in results] == [
144 (name, 1, 0) for name in names
145 ]
146 assert notice.call_count == 2
147 for name, alert in zip(names, notice.call_args_list, strict=True):
148 assert f"update: {name}" in alert.args[1]
149
150 watchlist.cmd_run_all(None)
151 results = json.loads(capsys.readouterr().out)["results"]
152 assert [(r["topic"], r["new"], r["updated"]) for r in results] == [
153 (name, 0, 1) for name in names
154 ]
155 assert notice.call_count == 2
156 assert store.get_stats()["total_findings"] == 1
157 for topic in (first, second):
158 runs = store.get_latest_completed_runs(topic["id"])
159 assert [(run["findings_new"], run["findings_updated"]) for run in runs] == [(0, 1), (1, 0)]
160 assert [finding["source_url"] for finding in store.get_new_findings(topic["id"])] == [item.url]
161
162
163 def test_degraded_comparison_survives_invalid_webhook_and_batch_continues(
164 tmp_path, monkeypatch, capsys, watchlist_report,
165 ):
166 topic, item, raw_report, _ = watchlist_report
167 later = store.add_topic("Later topic")
168 report = schema.report_from_dict(json.loads(raw_report))
169 peer = replace(item, item_id="r2", url="https://www.reddit.com/r/example/comments/r2/")
170 clean_report = replace(
171 report, topic=later["name"], items_by_source={"reddit": [peer]},
172 errors_by_source={}, source_status={},
173 )
174 args = cli.build_parser().parse_args([
175 "--emit=json", "--json-profile=raw", "--save-dir", "", topic["name"],
176 ])
177 assert cli._render_save_and_print(
178 args, clean_report, [(report.topic, report), (clean_report.topic, clean_report)],
179 None, {"LAST30DAYS_STRICT_EXIT": "1"},
180 ) == 3
181 comparison = capsys.readouterr()
182 _install_child(tmp_path, monkeypatch, {
183 topic["name"]: (comparison.out, comparison.err, 3),
184 later["name"]: (cli.emit_output(clean_report, "json", json_profile="raw"), "", 0),
185 })
186 invalid_channel = "https://[::1/unusable"
187 store.set_setting("delivery_channel", invalid_channel)
188 post = Mock()
189 monkeypatch.setattr(watchlist.http, "post", post)
190
191 watchlist.cmd_run_all(None)
192
193 output = capsys.readouterr()
194 results = json.loads(output.out)["results"]
195 assert [(r["topic"], r["status"], r["new"], r["updated"]) for r in results] == [
196 (topic["name"], "degraded", 2, 0),
197 (later["name"], "completed", 1, 0),
198 ]
199 assert [(row["name"], row["last_status"]) for row in store.list_topics()] == [
200 (topic["name"], "degraded"), (later["name"], "completed"),
201 ]
202 assert {row["source_url"] for row in store.get_new_findings(topic["id"])} == {item.url, peer.url}
203 assert [row["source_url"] for row in store.get_new_findings(later["id"])] == [peer.url]
204 assert output.err.splitlines() == ["Delivery failed: ValueError"] * 2
205 assert invalid_channel not in output.out
206 post.assert_not_called()
207
207 lines PYTHON