返回 last30days-skill
test_news_rss_source.py
根目录 / tests / test_news_rss_source.py
1 """Tests for the News RSS source adapter (lib/news_rss.py) and its default-on wiring."""
2
3 from __future__ import annotations
4
5 import json
6 import subprocess
7
8 import pytest
9
10 from lib import doctor, health, news_rss, normalize, pipeline, planner, render, schema, signals, subproc, ui
11
12
13 def _ok_proc(stdout: str = "", stderr: str = "", rc: int = 0) -> subprocess.CompletedProcess[str]:
14 return subprocess.CompletedProcess(args=["news-rss-pp-cli"], returncode=rc, stdout=stdout, stderr=stderr)
15
16
17 def test_build_search_args_has_separator_and_sanitizes_sources():
18 cmd = news_rss._build_search_args(
19 "-dash-query",
20 days=14,
21 limit=12,
22 sources_csv="Google, invalid, local, google",
23 db_path="/tmp/custom-news.db",
24 )
25 assert cmd[:6] == ["news-rss-pp-cli", "news", "--json", "--days", "14", "--limit"]
26 assert cmd[6] == "12"
27 assert "--sources" in cmd
28 assert cmd[cmd.index("--sources") + 1] == "Google, invalid, local, google"
29 assert cmd[cmd.index("--db") + 1] == "/tmp/custom-news.db"
30 assert cmd[-2:] == ["--", "-dash-query"]
31 assert news_rss._sanitize_sources_csv("Google, invalid, local, google") == "google,local"
32
33
34 def test_child_env_strips_secrets_and_node_options(monkeypatch):
35 monkeypatch.setenv("OPENAI_API_KEY", "sk-secret-value")
36 monkeypatch.setenv("NODE_OPTIONS", "--require /tmp/evil.js")
37 monkeypatch.setenv("PATH", "/usr/bin:/bin")
38 env = news_rss._child_env()
39 assert "PATH" in env
40 assert "OPENAI_API_KEY" not in env
41 assert "NODE_OPTIONS" not in env
42
43
44 def test_search_news_rss_missing_binary(monkeypatch):
45 monkeypatch.setattr(news_rss.shutil, "which", lambda _name: None)
46 res = news_rss.search_news_rss("Anthropic", "2026-11-01", "2026-12-01")
47 assert res["results"] == []
48 assert "not on PATH" in res["error"]
49
50
51 def test_search_news_rss_windows_dates_and_caps_depth(monkeypatch):
52 monkeypatch.setattr(news_rss.shutil, "which", lambda _name: "/usr/local/bin/news-rss-pp-cli")
53 payload = {
54 "query": "Anthropic",
55 "days": 30,
56 "sources_used": ["bing", "google"],
57 "items": [
58 {
59 "id": "old-1",
60 "clean_title": "Anthropic old story outside window",
61 "url": "https://reuters.com/old",
62 "publisher": "Reuters",
63 "publisher_domain": "reuters.com",
64 "published_date": "2026-10-15",
65 "source": "google-news",
66 },
67 {
68 "id": "in-1",
69 "clean_title": "Anthropic launches new Claude reasoning models",
70 "url": "https://news.google.com/rss/articles/CBMi1",
71 "canonical_url": "https://www.reuters.com/tech/anthropic-claude-models",
72 "publisher": "Reuters",
73 "publisher_domain": "reuters.com",
74 "published_date": "2026-11-28",
75 "summary": "Anthropic unveiled new enterprise reasoning capabilities.",
76 "cluster_count": 3,
77 "cluster_outlets": [
78 {"publisher": "Reuters"},
79 {"publisher": "Bloomberg"},
80 {"publisher": "Financial Times"},
81 ],
82 "source": "google-news+bing-news",
83 },
84 {
85 "id": "future-1",
86 "clean_title": "Anthropic story after to_date",
87 "url": "https://reuters.com/future",
88 "publisher": "Reuters",
89 "publisher_domain": "reuters.com",
90 "published_date": "2026-12-10",
91 "source": "bing-news",
92 },
93 {
94 "id": "undated-1",
95 "clean_title": "Anthropic analysis with missing feed date",
96 "url": "https://stratechery.com/anthropic-analysis",
97 "publisher": "Stratechery",
98 "publisher_domain": "stratechery.com",
99 "published_date": "",
100 "source": "rss-pack",
101 },
102 ],
103 }
104 captured_cmd: list[str] = []
105
106 def fake_run(cmd, timeout, env=None):
107 captured_cmd.extend(cmd)
108 return _ok_proc(stdout=json.dumps(payload))
109
110 monkeypatch.setattr(news_rss.subproc, "run_with_timeout", fake_run)
111 res = news_rss.search_news_rss(
112 "Anthropic",
113 "2026-11-01",
114 "2026-12-01",
115 depth="quick",
116 config={"LAST30DAYS_NEWS_RSS_SOURCES": "google,bing,bad", "LAST30DAYS_NEWS_RSS_DB": "/tmp/n.db"},
117 )
118 assert "--sources" in captured_cmd
119 assert captured_cmd[captured_cmd.index("--sources") + 1] == "google,bing"
120 assert captured_cmd[captured_cmd.index("--db") + 1] == "/tmp/n.db"
121 assert [r["id"] for r in res["results"]] == ["in-1", "undated-1"]
122
123 parsed = news_rss.parse_news_rss_response(res, query="Anthropic")
124 assert len(parsed) == 2
125 first = parsed[0]
126 assert first["url"] == "https://www.reuters.com/tech/anthropic-claude-models"
127 assert first["publisher"] == "Reuters"
128 assert first["cluster_count"] == 3
129 assert first["cluster_outlets"] == ["Reuters", "Bloomberg", "Financial Times"]
130 assert first["date"] == "2026-11-28"
131
132 norm = normalize.normalize_source_items("news_rss", parsed, "2026-11-01", "2026-12-01")
133 assert len(norm) == 2
134 assert norm[0].source == "news_rss"
135 assert norm[0].container == "Reuters"
136 assert norm[0].date_confidence == "high"
137 assert norm[0].metadata["cluster_count"] == 3
138 assert norm[1].date_confidence == "low"
139
140
141 def test_search_news_rss_distinguishes_malformed_json_and_errors(monkeypatch):
142 monkeypatch.setattr(news_rss.shutil, "which", lambda _name: "/usr/local/bin/news-rss-pp-cli")
143
144 # Non-zero exit with URL userinfo scrubbed.
145 monkeypatch.setattr(
146 news_rss.subproc,
147 "run_with_timeout",
148 lambda *_a, **_k: _ok_proc(rc=1, stderr="proxy error https://user:pass@proxy.example:8080/"),
149 )
150 err_res = news_rss.search_news_rss("Anthropic", "2026-11-01", "2026-12-01")
151 assert err_res["results"] == []
152 assert "user:pass@" not in err_res["error"]
153
154 # Timeout handled cleanly.
155 def raise_timeout(*_a, **_k):
156 raise subproc.SubprocTimeout("news-rss-pp-cli timed out after 30s")
157
158 monkeypatch.setattr(news_rss.subproc, "run_with_timeout", raise_timeout)
159 to_res = news_rss.search_news_rss("Anthropic", "2026-11-01", "2026-12-01")
160 assert to_res["results"] == []
161 assert "timed out" in to_res["error"]
162
163 # Unexpected JSON shape returns error rather than silent empty.
164 monkeypatch.setattr(
165 news_rss.subproc,
166 "run_with_timeout",
167 lambda *_a, **_k: _ok_proc(stdout='{"unexpected": 123}'),
168 )
169 shape_res = news_rss.search_news_rss("Anthropic", "2026-11-01", "2026-12-01")
170 assert shape_res["results"] == []
171 assert "unexpected News RSS response shape" in shape_res["error"]
172
173 # Valid empty SearchResult (items: null or []) is empty without error.
174 monkeypatch.setattr(
175 news_rss.subproc,
176 "run_with_timeout",
177 lambda *_a, **_k: _ok_proc(stdout='{"query": "Anthropic", "days": 30, "items": []}'),
178 )
179 empty_res = news_rss.search_news_rss("Anthropic", "2026-11-01", "2026-12-01")
180 assert empty_res["results"] == []
181 assert "error" not in empty_res
182
183
184 def test_parse_news_rss_drops_short_headlines_off_topic_and_dupes():
185 raw = {
186 "results": [
187 {
188 "id": "1",
189 "clean_title": "Reuters", # too short (< 3 words)
190 "url": "https://reuters.com",
191 "publisher": "Reuters",
192 },
193 {
194 "id": "2",
195 "clean_title": "Completely unrelated weather forecast for Antarctica tomorrow",
196 "url": "https://weather.example/antarctica",
197 "publisher": "Weather",
198 },
199 {
200 "id": "3",
201 "clean_title": "Anthropic expands Claude access for global teams",
202 "canonical_url": "https://bloomberg.com/anthropic-claude/",
203 "publisher": "Bloomberg",
204 "published_date": "2026-12-01",
205 },
206 {
207 "id": "4",
208 "clean_title": "Anthropic expands Claude access for global teams duplicate",
209 "canonical_url": "https://bloomberg.com/anthropic-claude",
210 "publisher": "Bloomberg",
211 "published_date": "2026-12-01",
212 },
213 ]
214 }
215 parsed = news_rss.parse_news_rss_response(raw, query="Anthropic Claude")
216 assert len(parsed) == 1
217 assert parsed[0]["id"] == "3"
218
219
220 def test_news_rss_wired_across_pipeline_planner_signals_render_ui_and_doctor(monkeypatch):
221 assert "news_rss" in pipeline.MOCK_AVAILABLE_SOURCES
222 assert "news_rss" in planner.HOST_PLAN_BACKFILL_SOURCES
223 assert "news_rss" in planner.SOURCE_CAPABILITIES
224 assert signals.source_quality("news_rss") == pytest.approx(0.55)
225 assert news_rss.DEPTH_CONFIG == {"quick": 4, "default": 8, "deep": 15}
226 assert "news_rss" in signals._NO_ENGAGEMENT_SCORE_SOURCES
227 assert render.SOURCE_LABELS["news_rss"] == "News RSS"
228 assert "news_rss" in ui.SOURCE_COMPLETION_META
229 assert doctor.CLI_DEPENDENCIES["news_rss"] == "news-rss-pp-cli"
230
231 # available_sources includes news_rss when news-rss-pp-cli is on PATH.
232 monkeypatch.setattr(
233 pipeline,
234 "which",
235 lambda name: "/usr/local/bin/news-rss-pp-cli" if name == "news-rss-pp-cli" else None,
236 )
237 avail = pipeline.available_sources({})
238 assert "news_rss" in avail
239
240 # EXCLUDE_SOURCES=news_rss disables it cleanly.
241 avail_excluded = pipeline.available_sources({"EXCLUDE_SOURCES": "news_rss"})
242 assert "news_rss" not in avail_excluded
243
244 # Doctor reports news_rss cleanly via _news_rss_record.
245 monkeypatch.setattr(
246 health,
247 "probe_dependency",
248 lambda name: health.DependencyProbe(
249 name=name,
250 status=health.OK if name == "news-rss-pp-cli" else health.MISSING,
251 detail="news-rss-pp-cli 2026.12.1" if name == "news-rss-pp-cli" else "not found",
252 ),
253 )
254 rec = doctor._news_rss_record({})
255 assert rec["status"] == health.OK
256
257
258 def test_parse_news_rss_keeps_cjk_headlines_without_spaces():
259 raw = {
260 "results": [
261 {
262 "id": "jp-1",
263 "clean_title": "任天堂新作ゲーム発表まとめ",
264 "url": "https://example.jp/nintendo-news",
265 "publisher": "日経",
266 "published_date": "2026-12-01",
267 "source": "rss-pack",
268 },
269 {
270 "id": "zh-1",
271 "clean_title": "人工智能芯片发布最新突破",
272 "url": "https://example.cn/ai-chip",
273 "publisher": "科技日报",
274 "published_date": "2026-12-01",
275 "source": "google-news",
276 },
277 ]
278 }
279 parsed_jp = news_rss.parse_news_rss_response(raw, query="任天堂新作")
280 assert [p["id"] for p in parsed_jp] == ["jp-1"]
281 parsed_zh = news_rss.parse_news_rss_response(raw, query="人工智能芯片")
282 assert [p["id"] for p in parsed_zh] == ["zh-1"]
283
284
285 def test_parse_news_rss_scores_content_only_newsletters():
286 raw = {
287 "results": [
288 {
289 "id": "nl-1",
290 "clean_title": "Weekly Engineering Digest Issue 42",
291 "summary": "",
292 "content": "Deep dive into Anthropic Claude tool-use architecture and prompt caching benchmarks.",
293 "canonical_url": "https://newsletter.example/issue-42",
294 "publisher": "Weekly Engineering",
295 "publisher_domain": "newsletter.example",
296 "published_date": "2026-12-01",
297 "source": "rss-pack",
298 },
299 ]
300 }
301 parsed = news_rss.parse_news_rss_response(raw, query="Anthropic Claude prompt caching")
302 assert len(parsed) == 1
303 assert parsed[0]["id"] == "nl-1"
304 assert "prompt caching" in parsed[0]["summary"]
305
306
307 def test_pipeline_news_rss_surfaces_fetch_failures_for_partial_and_empty_runs(monkeypatch):
308 sq = schema.SubQuery(
309 label="primary",
310 search_query="Anthropic",
311 ranking_query="Anthropic",
312 sources=["news_rss"],
313 )
314
315 # Case 1: partial failure with usable story -> PARTIAL outcome with detail.
316 monkeypatch.setattr(
317 news_rss,
318 "search_news_rss",
319 lambda *_a, **_k: {
320 "results": [
321 {
322 "id": "ok-1",
323 "clean_title": "Anthropic announces new enterprise safety report",
324 "url": "https://reuters.com/anthropic-report",
325 "publisher": "Reuters",
326 "published_date": "2026-12-01",
327 "source": "google-news",
328 }
329 ],
330 "fetch_failures": [
331 {"source": "bing", "error": "HTTP 503 upstream unavailable"},
332 ],
333 },
334 )
335 runtime = schema.ProviderRuntime(
336 reasoning_provider="local",
337 planner_model="",
338 rerank_model="",
339 )
340 items_partial, art_partial = pipeline._retrieve_stream_impl(
341 source="news_rss",
342 subquery=sq,
343 topic="Anthropic",
344 raw_topic="Anthropic",
345 date_range=("2026-11-01", "2026-12-02"),
346 depth="default",
347 config={},
348 runtime=runtime,
349 mock=False,
350 )
351 assert len(items_partial) == 1
352 assert art_partial["_source_outcome"]["state"] == schema.PARTIAL
353 assert "bing: HTTP 503" in art_partial["_source_outcome"]["detail"]
354
355 # Case 2: fetch_failures with zero usable stories -> failure outcome, not clean empty.
356 monkeypatch.setattr(
357 news_rss,
358 "search_news_rss",
359 lambda *_a, **_k: {
360 "results": [],
361 "fetch_failures": [
362 {"source": "google", "error": "HTTP 429 rate limited"},
363 {"source": "bing", "error": "request timeout"},
364 ],
365 },
366 )
367 items_failed, art_failed = pipeline._retrieve_stream_impl(
368 source="news_rss",
369 subquery=sq,
370 topic="Anthropic",
371 raw_topic="Anthropic",
372 date_range=("2026-11-01", "2026-12-02"),
373 depth="default",
374 config={},
375 runtime=runtime,
376 mock=False,
377 )
378 assert items_failed == []
379 assert art_failed["_source_outcome"]["state"] != schema.NO_RESULTS
380 assert "google: HTTP 429" in art_failed["_source_outcome"]["detail"]
381
382
383 def test_unwrap_bing_redirect_and_clean_publisher():
384 bing = (
385 "http://www.bing.com/news/apiclick.aspx?ref=FexRss&aid=&"
386 "url=https%3A%2F%2Fwww.reuters.com%2Fmarkets%2Ffed-rates-2026&c=123"
387 )
388 assert news_rss._unwrap_bing_redirect(bing) == "https://www.reuters.com/markets/fed-rates-2026"
389 # Non-http target scheme is never unwrapped.
390 bad = "http://www.bing.com/news/apiclick.aspx?url=javascript%3Aalert(1)"
391 assert news_rss._unwrap_bing_redirect(bad) == bad
392 # Normal URLs pass through unchanged.
393 direct = "https://www.wsj.com/economy/fed-rates"
394 assert news_rss._unwrap_bing_redirect(direct) == direct
395
396 assert news_rss._clean_publisher("ABC News - Breaking News, Latest News and Videos") == "ABC News"
397 assert news_rss._clean_publisher("CNBC | Stock Market & Business News Today") == "CNBC"
398 assert news_rss._clean_publisher("The Wall Street Journal") == "The Wall Street Journal"
399
400
401 def test_planner_gives_news_rss_supporting_weight_below_social():
402 default_prod = planner._default_source_weights("product", ["reddit", "youtube", "news_rss"])
403 assert default_prod["news_rss"] < default_prod["reddit"]
404 assert default_prod["news_rss"] < default_prod["youtube"]
405
406 default_news = planner._default_source_weights("breaking_news", ["reddit", "x", "news_rss"])
407 assert default_news["news_rss"] < default_news["reddit"]
408 assert default_news["news_rss"] < default_news["x"]
409
410 # Backfilled news_rss sits below social when host omitted it from source_weights.
411 backfilled = planner._sanitize_source_weights(
412 {"reddit": 1.0, "x": 1.0},
413 available={"reddit", "x", "news_rss"},
414 requested=set(),
415 eligible_sources=["reddit", "x", "news_rss"],
416 topic="Claude Code",
417 intent_hint="product",
418 depth="default",
419 )
420 assert backfilled["news_rss"] < backfilled["reddit"]
421 assert backfilled["news_rss"] < backfilled["x"]
422
423 # Explicit host weight for news_rss is preserved relative to other sources.
424 explicit = planner._sanitize_source_weights(
425 {"reddit": 1.0, "news_rss": 2.0},
426 available={"reddit", "news_rss"},
427 requested=set(),
428 eligible_sources=["reddit", "news_rss"],
429 topic="Federal Reserve",
430 intent_hint="breaking_news",
431 depth="default",
432 )
433 assert explicit["news_rss"] > explicit["reddit"]
434
434 lines PYTHON