返回 last30days-skill
test_watchlist_output.py
根目录 / tests / test_watchlist_output.py
1 import io
2 import json
3 import subprocess
4 import sys
5 from contextlib import redirect_stderr, redirect_stdout
6
7 import pytest
8
9 import last30days as cli
10 import store
11 import watchlist
12 from lib import hosted, schema
13
14
15 @pytest.fixture
16 def watch_store(tmp_path):
17 with store.scoped_db(tmp_path / "watchlist.db"):
18 yield
19
20
21 def _report(topic, *urls):
22 return schema.Report(
23 topic=topic,
24 range_from="2026-09-01",
25 range_to="2026-11-30",
26 generated_at="2026-11-30T00:00:00Z",
27 provider_runtime=schema.ProviderRuntime("local", "local", "local"),
28 query_plan=schema.QueryPlan("overview", "recent", "themes", topic, [], {}),
29 clusters=[],
30 ranked_candidates=[],
31 items_by_source={
32 "hackernews": [
33 schema.SourceItem(url, "hackernews", f"{topic} finding", topic, url)
34 for url in urls
35 ],
36 },
37 errors_by_source={},
38 )
39
40
41 def _comparison():
42 first = _report("Alpha", "https://example.test/alpha", "https://example.test/shared")
43 second = _report("Beta", "https://example.test/beta", "https://example.test/shared")
44 return cli.emit_comparison_output(
45 [("Alpha", first), ("Beta", second)], "json", json_profile="raw",
46 )
47
48
49 def test_watchlist_persists_both_entities_under_the_original_topic(watch_store, monkeypatch):
50 topic = store.add_topic("Weekly comparison", search_queries=["Alpha vs Beta"])
51 output = _comparison()
52 monkeypatch.setattr(
53 watchlist.subprocess, "run",
54 lambda argv, **kwargs: subprocess.CompletedProcess(argv, 0, stdout=output, stderr=""),
55 )
56
57 result = watchlist._run_topic(topic)
58
59 assert result["status"] == "completed"
60 assert result["new"] == 3
61 assert result["updated"] == 0
62 findings = store.get_new_findings(topic["id"])
63 assert {row["source_url"]: row["content"] for row in findings} == {
64 "https://example.test/alpha": "Alpha",
65 "https://example.test/beta": "Beta",
66 "https://example.test/shared": "Alpha",
67 }
68 assert [row["name"] for row in store.list_topics()] == ["Weekly comparison"]
69 assert len(store.get_latest_completed_runs(topic["id"])) == 1
70
71
72 @pytest.mark.parametrize(
73 "invalid_output",
74 [
75 "non-object", "missing reports", "bad peer", "malformed finding",
76 "invalid Unicode title", "invalid Unicode report topic", "invalid Unicode entity name",
77 ],
78 )
79 def test_invalid_child_output_fails_one_run_and_lets_next_topic_complete(
80 watch_store, monkeypatch, capsys, invalid_output,
81 ):
82 bad = store.add_topic("First")
83 good = store.add_topic("Second")
84 if invalid_output in ("bad peer", "invalid Unicode entity name"):
85 comparison = json.loads(_comparison())
86 peer = comparison["reports"][1]
87 if invalid_output == "bad peer":
88 del peer["report"]["topic"]
89 else:
90 peer["entity"] = "\ud800"
91 invalid = json.dumps(comparison)
92 elif invalid_output == "missing reports":
93 invalid = '{"comparison": true}'
94 elif invalid_output in ("malformed finding", "invalid Unicode title", "invalid Unicode report topic"):
95 report = schema.to_dict(_report(bad["name"], "https://example.test/bad"))
96 item = report["items_by_source"]["hackernews"][0]
97 if invalid_output == "malformed finding":
98 item["title"] = {"text": "not a title"}
99 elif invalid_output == "invalid Unicode title":
100 item["title"] = "\ud800"
101 else:
102 report["topic"] = "\ud800"
103 invalid = json.dumps(report)
104 else:
105 invalid = "[]"
106 valid = cli.emit_output(
107 _report(good["name"], "https://example.test/café"),
108 "json",
109 json_profile="raw",
110 )
111 outputs = iter([invalid, valid])
112 monkeypatch.setattr(
113 watchlist.subprocess, "run",
114 lambda argv, **kwargs: subprocess.CompletedProcess(argv, 0, stdout=next(outputs), stderr=""),
115 )
116
117 watchlist.cmd_run_all(None)
118
119 results = json.loads(capsys.readouterr().out)["results"]
120 assert [(item["topic"], item["status"]) for item in results] == [
121 ("First", "failed"), ("Second", "completed"),
122 ]
123 assert "Invalid research output" in results[0]["error"]
124 assert store.list_topics()[0]["last_status"] == "failed"
125 assert store.get_new_findings(bad["id"]) == []
126 assert [row["source_url"] for row in store.get_new_findings(good["id"])] == [
127 "https://example.test/café",
128 ]
129
130
131 def test_watchlist_reports_unsupported_hosted_backend_before_submission(watch_store, monkeypatch):
132 topic = store.add_topic("Example research")
133 submitted = []
134 monkeypatch.setenv("LAST30DAYS_API_KEY", "DUMMY_TEST_KEY")
135 monkeypatch.setenv("LAST30DAYS_API_BASE", "https://example.test")
136
137 def submit(query, depth, register="default"):
138 submitted.append(query)
139 return {"needs_clarification": True, "question": "Unexpected submission"}
140
141 def run_engine(argv, *, env, **kwargs):
142 stdout, stderr = io.StringIO(), io.StringIO()
143 with monkeypatch.context() as child:
144 child.setattr(sys, "argv", argv[1:])
145 with redirect_stdout(stdout), redirect_stderr(stderr):
146 code = cli.main()
147 return subprocess.CompletedProcess(argv, code, stdout=stdout.getvalue(), stderr=stderr.getvalue())
148
149 monkeypatch.setattr(hosted, "submit", submit)
150 monkeypatch.setattr(watchlist.subprocess, "run", run_engine)
151
152 result = watchlist._run_topic(topic)
153
154 assert submitted == []
155 assert result["status"] == "failed"
156 assert "Watchlist requires structured local reports" in result["error"]
157 assert "LAST30DAYS_API_BASE" in result["error"]
158 assert store.list_topics()[0]["last_status"] == "failed"
159 assert store.get_daily_unknown_cost_runs() == 0
160
160 lines PYTHON