test_news_mcp.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. from __future__ import annotations
  2. import tempfile
  3. from pathlib import Path
  4. from news_mcp.dedup.cluster import dedup_and_cluster_articles
  5. from news_mcp.storage.sqlite_store import SQLiteClusterStore
  6. from news_mcp.enrichment.importance import compute_importance
  7. from news_mcp.enrichment.llm_enrich import _filter_entities, _matches_blacklist
  8. from news_mcp.entity_normalize import normalize_query, normalize_entities
  9. from news_mcp.llm import build_extraction_prompt, call_llm, load_prompt
  10. def _article(title: str, url: str = "https://example.com/x", source: str = "Src", ts: str = "Mon, 30 Mar 2026 12:00:00 GMT"):
  11. return {
  12. "title": title,
  13. "url": url,
  14. "source": source,
  15. "timestamp": ts,
  16. "summary": "summary text",
  17. }
  18. def test_dedup_merges_similar_titles():
  19. articles = [
  20. _article("Trump warns Iran war could spread"),
  21. _article("Trump warns Iran conflict could spread"),
  22. _article("Unrelated sports result"),
  23. ]
  24. clustered = dedup_and_cluster_articles(articles, similarity_threshold=0.75)
  25. # We expect the Trump/Iran items to be merged into one cluster in the same topic bucket.
  26. total_clusters = sum(len(v) for v in clustered.values())
  27. assert total_clusters == 2
  28. def test_sqlite_feed_hash_roundtrip():
  29. with tempfile.TemporaryDirectory() as td:
  30. db = Path(td) / "news.sqlite"
  31. store = SQLiteClusterStore(db)
  32. assert store.get_feed_hash("breakingthenews") is None
  33. store.set_feed_hash("breakingthenews", "abc123")
  34. assert store.get_feed_hash("breakingthenews") == "abc123"
  35. def test_sqlite_summary_cache_roundtrip():
  36. with tempfile.TemporaryDirectory() as td:
  37. db = Path(td) / "news.sqlite"
  38. store = SQLiteClusterStore(db)
  39. # Upsert a base cluster first.
  40. store.upsert_clusters([
  41. {
  42. "cluster_id": "cid1",
  43. "headline": "Headline",
  44. "summary": "Summary",
  45. "entities": ["Iran"],
  46. "sentiment": "negative",
  47. "importance": 0.5,
  48. "sources": ["BreakingTheNews"],
  49. "timestamp": "Mon, 30 Mar 2026 12:00:00 GMT",
  50. "articles": [],
  51. "first_seen": "Mon, 30 Mar 2026 12:00:00 GMT",
  52. "last_updated": "Mon, 30 Mar 2026 12:00:00 GMT",
  53. }
  54. ], topic="other")
  55. store.upsert_cluster_summary(
  56. "cid1",
  57. {
  58. "headline": "Headline",
  59. "mergedSummary": "Merged summary",
  60. "keyFacts": ["Fact 1"],
  61. "sources": ["BreakingTheNews"],
  62. },
  63. )
  64. cached = store.get_cluster_summary("cid1", ttl_hours=24)
  65. assert cached is not None
  66. assert cached["mergedSummary"] == "Merged summary"
  67. assert cached["keyFacts"] == ["Fact 1"]
  68. def test_blacklist_filters_entities_case_insensitively():
  69. entities = ["Bloomberg", "Reuters", "bloomberg", "CoinDesk"]
  70. filtered = _filter_entities(entities, blacklist=["bloomberg"])
  71. assert filtered == ["Reuters", "CoinDesk"]
  72. def test_blacklist_supports_wildcards():
  73. assert _matches_blacklist("Bloomberg Economics", blacklist=["bloomberg*"])
  74. assert _matches_blacklist("bloomberg", blacklist=["*berg"])
  75. assert not _matches_blacklist("Reuters", blacklist=["bloomberg*"])
  76. def test_query_normalization_keeps_common_shorthand_working():
  77. assert normalize_query("btc") == "Bitcoin"
  78. assert normalize_query("Trump") == "Donald Trump"
  79. assert normalize_query("nvidia") == "nvidia"
  80. def test_entity_normalization_deduplicates_aliases():
  81. assert normalize_entities(["btc", "Bitcoin", "BTC", "Ethereum"]) == ["Bitcoin", "Ethereum"]
  82. def test_load_prompt_reads_prompt_files():
  83. text = load_prompt("extract_entities.prompt")
  84. assert "Return STRICT JSON" in text
  85. def test_build_extraction_prompt_is_stable_without_blacklist():
  86. cluster = {
  87. "headline": "Bloomberg reports Bitcoin rallies after US rate comments",
  88. "summary": "A report from Bloomberg says Bitcoin moved higher after comments from the Fed.",
  89. "articles": [],
  90. }
  91. prompt = build_extraction_prompt(cluster)
  92. assert "Bloomberg reports Bitcoin rallies" in prompt
  93. assert "Do NOT return empty entities" in prompt
  94. assert "Bloomberg" in prompt # present in the input, not filtered here
  95. def test_call_llm_dispatches_to_selected_provider(monkeypatch):
  96. async def fake_groq(model, messages, response_json=True):
  97. return '{"ok": true, "provider": "groq"}'
  98. async def fake_openai(model, messages, response_json=True):
  99. return '{"ok": true, "provider": "openai"}'
  100. monkeypatch.setattr("news_mcp.llm._call_groq", fake_groq)
  101. monkeypatch.setattr("news_mcp.llm._call_openai", fake_openai)
  102. import asyncio
  103. groq = asyncio.run(call_llm("groq", "x", "sys", "user"))
  104. openai = asyncio.run(call_llm("openai", "x", "sys", "user"))
  105. assert '"provider": "groq"' in groq
  106. assert '"provider": "openai"' in openai
  107. def test_importance_prefers_llm_signal():
  108. # Two clusters with same coverage but different sentiment magnitude.
  109. base = {
  110. "sources": ["A", "B"],
  111. "articles": [{}, {}],
  112. "sentiment": "neutral",
  113. "sentimentScore": 0.0,
  114. }
  115. pos = dict(base, sentimentScore=0.9)
  116. neg = dict(base, sentimentScore=-0.8)
  117. imp_base = compute_importance(base)
  118. imp_pos = compute_importance(pos)
  119. imp_neg = compute_importance(neg)
  120. assert imp_pos >= imp_base
  121. assert imp_neg >= imp_base