Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

test: add 165 high-value tests across 8 modules (round 3) (#2536)

LearningCircuit3ae54520c52c
diff --git a/tests/advanced_search_system/filters/test_filters_high_value.py b/tests/advanced_search_system/filters/test_filters_high_value.py
new file mode 100644
index 0000000000..d9c43f8d07
--- /dev/null
+++ b/tests/advanced_search_system/filters/test_filters_high_value.py
@@ -0,0 +1,164 @@
+"""High-value tests for filters module: base_filter.py and followup_relevance_filter.py.
+
+Covers BaseFilter ABC enforcement, FollowUpRelevanceFilter logic with
+mocked LLM responses, empty inputs, and fallback behavior.
+"""
+
+import pytest
+from unittest.mock import MagicMock
+
+from local_deep_research.advanced_search_system.filters.base_filter import (
+ BaseFilter,
+)
+from local_deep_research.advanced_search_system.filters.followup_relevance_filter import (
+ FollowUpRelevanceFilter,
+)
+
+
+class TestBaseFilterABC:
+ """Test BaseFilter abstract base class."""
+
+ def test_cannot_instantiate_directly(self):
+ with pytest.raises(TypeError):
+ BaseFilter()
+
+ def test_incomplete_subclass_raises(self):
+ class Incomplete(BaseFilter):
+ pass
+
+ with pytest.raises(TypeError):
+ Incomplete()
+
+ def test_complete_subclass_works(self):
+ class Complete(BaseFilter):
+ def filter_results(self, results, query, **kwargs):
+ return results
+
+ f = Complete()
+ assert isinstance(f, BaseFilter)
+
+ def test_model_stored(self):
+ class Complete(BaseFilter):
+ def filter_results(self, results, query, **kwargs):
+ return results
+
+ model = MagicMock()
+ f = Complete(model=model)
+ assert f.model is model
+
+ def test_model_default_none(self):
+ class Complete(BaseFilter):
+ def filter_results(self, results, query, **kwargs):
+ return results
+
+ f = Complete()
+ assert f.model is None
+
+
+class TestFollowUpRelevanceFilterEmptyInput:
+ """Test FollowUpRelevanceFilter with empty/None inputs."""
+
+ def test_empty_results_returns_empty(self):
+ """Empty results list returns empty list."""
+ f = FollowUpRelevanceFilter(model=MagicMock())
+ assert f.filter_results([], "query") == []
+
+ def test_no_model_returns_first_n(self):
+ """Without model, returns first max_results sources."""
+ f = FollowUpRelevanceFilter(model=None)
+ results = [
+ {"title": f"R{i}", "url": f"http://{i}.com"} for i in range(20)
+ ]
+ filtered = f.filter_results(results, "query", max_results=5)
+ assert len(filtered) == 5
+ assert filtered[0]["title"] == "R0"
+
+
+class TestFollowUpRelevanceFilterWithModel:
+ """Test FollowUpRelevanceFilter with mocked LLM."""
+
+ def _make_filter(self, llm_content="[0, 2, 4]"):
+ model = MagicMock()
+ model.invoke.return_value = MagicMock(content=llm_content)
+ return FollowUpRelevanceFilter(model=model)
+
+ def test_selects_indices_from_llm(self):
+ """Uses LLM-selected indices to filter."""
+ f = self._make_filter("[0, 2]")
+ results = [
+ {"title": "A", "url": "http://a.com"},
+ {"title": "B", "url": "http://b.com"},
+ {"title": "C", "url": "http://c.com"},
+ ]
+ filtered = f.filter_results(results, "follow-up query")
+ assert len(filtered) == 2
+ assert filtered[0]["title"] == "A"
+ assert filtered[1]["title"] == "C"
+
+ def test_out_of_range_indices_skipped(self):
+ """Indices >= len(results) are silently skipped."""
+ f = self._make_filter("[0, 99]")
+ results = [{"title": "Only", "url": "http://only.com"}]
+ filtered = f.filter_results(results, "query")
+ assert len(filtered) == 1
+
+ def test_llm_failure_falls_back_to_first_n(self):
+ """LLM exception falls back to first max_results."""
+ model = MagicMock()
+ model.invoke.side_effect = RuntimeError("LLM error")
+ f = FollowUpRelevanceFilter(model=model)
+ results = [
+ {"title": f"R{i}", "url": f"http://{i}.com"} for i in range(10)
+ ]
+ filtered = f.filter_results(results, "query", max_results=3)
+ assert len(filtered) == 3
+
+ def test_context_included_in_prompt(self):
+ """past_findings and original_query are passed through."""
+ model = MagicMock()
+ model.invoke.return_value = MagicMock(content="[0]")
+ f = FollowUpRelevanceFilter(model=model)
+ results = [{"title": "A", "url": "http://a.com"}]
+ f.filter_results(
+ results,
+ "follow-up",
+ past_findings="previous research",
+ original_query="original question",
+ )
+ prompt = model.invoke.call_args[0][0]
+ assert "previous research" in prompt
+ assert "original question" in prompt
+
+ def test_non_json_response_regex_fallback(self):
+ """Non-JSON LLM response falls back to regex number extraction."""
+ f = self._make_filter("The relevant sources are indices 0, 2, and 4.")
+ results = [
+ {"title": f"R{i}", "url": f"http://{i}.com"} for i in range(5)
+ ]
+ filtered = f.filter_results(results, "query")
+ assert len(filtered) == 3
+ assert filtered[0]["title"] == "R0"
+ assert filtered[1]["title"] == "R2"
+ assert filtered[2]["title"] == "R4"
+
+
+class TestFollowUpRelevanceFilterMaxResults:
+ """Test max_results parameter."""
+
+ def test_default_max_results_is_ten(self):
+ """Default max_results parameter is 10."""
+ f = FollowUpRelevanceFilter(model=None)
+ results = [
+ {"title": f"R{i}", "url": f"http://{i}.com"} for i in range(20)
+ ]
+ filtered = f.filter_results(results, "query")
+ assert len(filtered) == 10
+
+ def test_custom_max_results(self):
+ """Custom max_results limits output."""
+ f = FollowUpRelevanceFilter(model=None)
+ results = [
+ {"title": f"R{i}", "url": f"http://{i}.com"} for i in range(20)
+ ]
+ filtered = f.filter_results(results, "query", max_results=3)
+ assert len(filtered) == 3
diff --git a/tests/advanced_search_system/findings/test_findings_high_value.py b/tests/advanced_search_system/findings/test_findings_high_value.py
new file mode 100644
index 0000000000..bb1d3cb631
--- /dev/null
+++ b/tests/advanced_search_system/findings/test_findings_high_value.py
@@ -0,0 +1,246 @@
+"""High-value tests for findings module: topic.py and repository.py.
+
+Covers Topic source management, TopicGraph operations,
+FindingsRepository CRUD, and format_links helper.
+"""
+
+from unittest.mock import MagicMock
+
+from local_deep_research.advanced_search_system.findings.topic import (
+ Topic,
+ TopicGraph,
+)
+from local_deep_research.advanced_search_system.findings.repository import (
+ FindingsRepository,
+ format_links,
+)
+
+
+class TestTopicSourceManagement:
+ """Test Topic source add/reject/update operations."""
+
+ def _make_topic(self):
+ return Topic(
+ id="t1",
+ title="Test Topic",
+ lead_source={"url": "http://lead.com", "title": "Lead"},
+ )
+
+ def test_add_supporting_source_no_duplicates(self):
+ """Same source added twice only appears once."""
+ t = self._make_topic()
+ src = {"url": "http://a.com"}
+ t.add_supporting_source(src)
+ t.add_supporting_source(src)
+ assert len(t.supporting_sources) == 1
+
+ def test_reject_source_moves_from_supporting(self):
+ """Rejecting moves source from supporting to rejected."""
+ t = self._make_topic()
+ src = {"url": "http://a.com"}
+ t.add_supporting_source(src)
+ t.reject_source(src)
+ assert src not in t.supporting_sources
+ assert src in t.rejected_sources
+
+ def test_reject_source_not_in_supporting(self):
+ """Rejecting a source not in supporting still adds to rejected."""
+ t = self._make_topic()
+ src = {"url": "http://new.com"}
+ t.reject_source(src)
+ assert src in t.rejected_sources
+
+ def test_update_lead_source(self):
+ """Old lead becomes supporting, new lead replaces it."""
+ t = self._make_topic()
+ old_lead = t.lead_source
+ new_lead = {"url": "http://new-lead.com"}
+ t.update_lead_source(new_lead)
+ assert t.lead_source is new_lead
+ assert old_lead in t.supporting_sources
+
+ def test_update_lead_removes_from_supporting(self):
+ """New lead from supporting is removed from supporting."""
+ t = self._make_topic()
+ new_lead = {"url": "http://support.com"}
+ t.add_supporting_source(new_lead)
+ t.update_lead_source(new_lead)
+ assert new_lead not in t.supporting_sources
+ assert t.lead_source is new_lead
+
+ def test_get_all_sources_includes_lead(self):
+ """get_all_sources returns lead + supporting."""
+ t = self._make_topic()
+ t.add_supporting_source({"url": "http://a.com"})
+ all_sources = t.get_all_sources()
+ assert len(all_sources) == 2
+ assert all_sources[0] == t.lead_source
+
+ def test_to_dict_has_expected_keys(self):
+ """to_dict returns all expected keys."""
+ t = self._make_topic()
+ d = t.to_dict()
+ expected = {
+ "id",
+ "title",
+ "lead_source",
+ "supporting_sources",
+ "rejected_sources",
+ "created_at",
+ "related_topic_ids",
+ "parent_topic_id",
+ "child_topic_ids",
+ }
+ assert set(d.keys()) == expected
+
+
+class TestTopicGraph:
+ """Test TopicGraph operations."""
+
+ def _make_graph(self):
+ g = TopicGraph()
+ t1 = Topic(id="t1", title="T1", lead_source={"url": "a"})
+ t2 = Topic(id="t2", title="T2", lead_source={"url": "b"})
+ g.add_topic(t1)
+ g.add_topic(t2)
+ return g
+
+ def test_add_and_get_topic(self):
+ g = self._make_graph()
+ assert g.get_topic("t1") is not None
+ assert g.get_topic("nonexistent") is None
+
+ def test_link_topics_bidirectional(self):
+ """link_topics creates bidirectional relationships."""
+ g = self._make_graph()
+ g.link_topics("t1", "t2")
+ assert "t2" in g.get_topic("t1").related_topic_ids
+ assert "t1" in g.get_topic("t2").related_topic_ids
+
+ def test_link_topics_no_duplicates(self):
+ """Linking twice doesn't create duplicate relationships."""
+ g = self._make_graph()
+ g.link_topics("t1", "t2")
+ g.link_topics("t1", "t2")
+ assert g.get_topic("t1").related_topic_ids.count("t2") == 1
+
+ def test_set_parent_child(self):
+ g = self._make_graph()
+ g.set_parent_child("t1", "t2")
+ assert "t2" in g.get_topic("t1").child_topic_ids
+ assert g.get_topic("t2").parent_topic_id == "t1"
+
+ def test_get_root_topics(self):
+ """Root topics have no parent."""
+ g = self._make_graph()
+ g.set_parent_child("t1", "t2")
+ roots = g.get_root_topics()
+ assert len(roots) == 1
+ assert roots[0].id == "t1"
+
+ def test_get_related_topics(self):
+ g = self._make_graph()
+ g.link_topics("t1", "t2")
+ related = g.get_related_topics("t1")
+ assert len(related) == 1
+ assert related[0].id == "t2"
+
+ def test_get_related_topics_nonexistent(self):
+ g = self._make_graph()
+ assert g.get_related_topics("nonexistent") == []
+
+ def test_merge_topics(self):
+ """Merging combines sources and removes topic2."""
+ g = self._make_graph()
+ g.get_topic("t2").add_supporting_source({"url": "c"})
+ merged = g.merge_topics("t1", "t2", new_title="Merged")
+ assert merged.title == "Merged"
+ assert {"url": "c"} in merged.supporting_sources
+ assert g.get_topic("t2") is None
+
+ def test_merge_nonexistent_returns_none(self):
+ g = self._make_graph()
+ assert g.merge_topics("t1", "nonexistent") is None
+
+ def test_to_dict(self):
+ g = self._make_graph()
+ d = g.to_dict()
+ assert "t1" in d
+ assert "t2" in d
+
+
+class TestFormatLinks:
+ """Test format_links helper function."""
+
+ def test_formats_correctly(self):
+ links = [
+ {"title": "Title A", "url": "http://a.com"},
+ {"title": "Title B", "url": "http://b.com"},
+ ]
+ result = format_links(links)
+ assert "1. Title A" in result
+ assert "2. Title B" in result
+ assert "http://a.com" in result
+
+ def test_empty_list(self):
+ assert format_links([]) == ""
+
+
+class TestFindingsRepository:
+ """Test FindingsRepository CRUD operations."""
+
+ def _make_repo(self):
+ model = MagicMock()
+ return FindingsRepository(model=model)
+
+ def test_add_string_finding(self):
+ """String finding is converted to dict."""
+ repo = self._make_repo()
+ repo.add_finding("query1", "finding text")
+ findings = repo.get_findings("query1")
+ assert len(findings) == 1
+ assert findings[0]["content"] == "finding text"
+ assert findings[0]["phase"] == "Synthesis"
+
+ def test_add_dict_finding(self):
+ """Dict finding is stored as-is."""
+ repo = self._make_repo()
+ finding = {"phase": "Phase 1", "content": "result"}
+ repo.add_finding("query1", finding)
+ assert repo.get_findings("query1")[0]["content"] == "result"
+
+ def test_final_synthesis_creates_extra_entry(self):
+ """Final synthesis finding creates a _synthesis key."""
+ repo = self._make_repo()
+ finding = {"phase": "Final synthesis", "content": "final result"}
+ repo.add_finding("query1", finding)
+ assert "query1_synthesis" in repo.findings
+
+ def test_get_findings_nonexistent_returns_empty(self):
+ repo = self._make_repo()
+ assert repo.get_findings("nonexistent") == []
+
+ def test_clear_findings(self):
+ repo = self._make_repo()
+ repo.add_finding("q1", "finding")
+ repo.clear_findings("q1")
+ assert repo.get_findings("q1") == []
+
+ def test_clear_findings_nonexistent_no_error(self):
+ """Clearing nonexistent query doesn't raise."""
+ repo = self._make_repo()
+ repo.clear_findings("nonexistent") # Should not raise
+
+ def test_add_documents(self):
+ repo = self._make_repo()
+ docs = [MagicMock(), MagicMock()]
+ repo.add_documents(docs)
+ assert len(repo.documents) == 2
+
+ def test_set_questions_by_iteration(self):
+ repo = self._make_repo()
+ questions = {1: ["Q1a", "Q1b"], 2: ["Q2a"]}
+ repo.set_questions_by_iteration(questions)
+ assert repo.questions_by_iteration == questions
+ # Verify it's a copy, not the same reference
+ assert repo.questions_by_iteration is not questions
diff --git a/tests/advanced_search_system/knowledge/test_followup_context_manager_high_value.py b/tests/advanced_search_system/knowledge/test_followup_context_manager_high_value.py
new file mode 100644
index 0000000000..fcf612ef82
--- /dev/null
+++ b/tests/advanced_search_system/knowledge/test_followup_context_manager_high_value.py
@@ -0,0 +1,245 @@
+"""High-value tests for knowledge/followup_context_manager.py.
+
+Covers FollowUpContextHandler: build_context, _extract_findings,
+_extract_sources, _extract_metadata, summarize_for_followup,
+_generate_summary, format_for_settings_snapshot, get_relevant_context_for_llm.
+"""
+
+from unittest.mock import MagicMock
+
+from local_deep_research.advanced_search_system.knowledge.followup_context_manager import (
+ FollowUpContextHandler,
+)
+
+
+def _make_handler(model=None):
+ if model is None:
+ model = MagicMock()
+ model.invoke.return_value = MagicMock(content="mock summary")
+ return FollowUpContextHandler(model=model)
+
+
+class TestExtractFindings:
+ """Test _extract_findings."""
+
+ def test_returns_formatted_findings_when_present(self):
+ handler = _make_handler()
+ data = {"formatted_findings": "These are findings"}
+ result = handler._extract_findings(data)
+ assert "These are findings" in result
+
+ def test_falls_back_to_report_content(self):
+ """Uses report_content when formatted_findings missing."""
+ handler = _make_handler()
+ data = {"report_content": "Report text" * 100}
+ result = handler._extract_findings(data)
+ assert "Report text" in result
+
+ def test_truncates_report_to_2000(self):
+ """Report content is truncated to 2000 chars."""
+ handler = _make_handler()
+ data = {"report_content": "x" * 5000}
+ result = handler._extract_findings(data)
+ assert len(result) <= 2000
+
+ def test_no_findings_returns_message(self):
+ """Returns 'No previous findings' when nothing available."""
+ handler = _make_handler()
+ result = handler._extract_findings({})
+ assert "No previous findings" in result
+
+
+class TestExtractSources:
+ """Test _extract_sources."""
+
+ def test_deduplicates_by_url(self):
+ """Sources with same URL are deduplicated."""
+ handler = _make_handler()
+ data = {
+ "resources": [{"url": "http://a.com", "title": "A"}],
+ "all_links_of_system": [{"url": "http://a.com", "title": "A dup"}],
+ }
+ sources = handler._extract_sources(data)
+ assert len(sources) == 1
+
+ def test_includes_sources_without_url(self):
+ """Sources without URL are included (not deduplicated)."""
+ handler = _make_handler()
+ data = {"resources": [{"title": "No URL"}, {"title": "Also no URL"}]}
+ sources = handler._extract_sources(data)
+ assert len(sources) == 2
+
+ def test_empty_data_returns_empty_list(self):
+ handler = _make_handler()
+ assert handler._extract_sources({}) == []
+
+ def test_collects_from_all_fields(self):
+ """Collects sources from resources, all_links_of_system, past_links."""
+ handler = _make_handler()
+ data = {
+ "resources": [{"url": "http://a.com", "title": "A"}],
+ "all_links_of_system": [{"url": "http://b.com", "title": "B"}],
+ "past_links": [{"url": "http://c.com", "title": "C"}],
+ }
+ sources = handler._extract_sources(data)
+ assert len(sources) == 3
+
+
+class TestExtractMetadata:
+ """Test _extract_metadata."""
+
+ def test_extracts_expected_keys(self):
+ handler = _make_handler()
+ data = {
+ "strategy": "source-based",
+ "mode": "deep",
+ "created_at": "2024-01-01",
+ }
+ meta = handler._extract_metadata(data)
+ assert meta["strategy"] == "source-based"
+ assert meta["mode"] == "deep"
+ assert "research_meta" in meta
+
+ def test_missing_keys_default_to_empty(self):
+ handler = _make_handler()
+ meta = handler._extract_metadata({})
+ assert meta["strategy"] == ""
+ assert meta["research_meta"] == {}
+
+
+class TestBuildContext:
+ """Test build_context."""
+
+ def test_returns_all_expected_keys(self):
+ handler = _make_handler()
+ data = {
+ "research_id": "r1",
+ "query": "original",
+ "formatted_findings": "findings",
+ "report_content": "report",
+ "all_links_of_system": [],
+ }
+ ctx = handler.build_context(data, "follow-up question")
+ expected_keys = {
+ "parent_research_id",
+ "original_query",
+ "follow_up_query",
+ "past_findings",
+ "past_sources",
+ "key_entities",
+ "summary",
+ "report_content",
+ "formatted_findings",
+ "all_links_of_system",
+ "metadata",
+ }
+ assert set(ctx.keys()) == expected_keys
+
+ def test_follow_up_query_stored(self):
+ handler = _make_handler()
+ ctx = handler.build_context({}, "What about X?")
+ assert ctx["follow_up_query"] == "What about X?"
+
+
+class TestGenerateSummary:
+ """Test _generate_summary and summarize_for_followup."""
+
+ def test_empty_findings_returns_empty_string(self):
+ handler = _make_handler()
+ result = handler._generate_summary("", "query")
+ assert result == ""
+
+ def test_short_findings_returned_as_is(self):
+ """Findings shorter than max_length returned unchanged."""
+ handler = _make_handler()
+ result = handler._generate_summary(
+ "short text", "query", max_length=1000
+ )
+ assert result == "short text"
+
+ def test_no_model_falls_back_to_truncation(self):
+ """Without model, falls back to truncation."""
+ handler = FollowUpContextHandler(model=None)
+ long_text = "x" * 2000
+ result = handler._generate_summary(long_text, "query", max_length=100)
+ assert len(result) <= 104 # 100 + "..."
+ assert result.endswith("...")
+
+ def test_model_failure_falls_back_to_truncation(self):
+ """When model raises, falls back to truncation."""
+ model = MagicMock()
+ model.invoke.side_effect = RuntimeError("LLM error")
+ handler = _make_handler(model=model)
+ long_text = "x" * 2000
+ result = handler._generate_summary(long_text, "query", max_length=100)
+ assert result.endswith("...")
+
+ def test_summarize_for_followup_delegates(self):
+ """summarize_for_followup uses _generate_summary internally."""
+ handler = _make_handler()
+ result = handler.summarize_for_followup(
+ "findings text", "query", max_length=500
+ )
+ assert isinstance(result, str)
+
+
+class TestFormatForSettingsSnapshot:
+ """Test format_for_settings_snapshot."""
+
+ def test_returns_minimal_metadata(self):
+ handler = _make_handler()
+ ctx = {"parent_research_id": "r1", "past_findings": "some findings"}
+ result = handler.format_for_settings_snapshot(ctx)
+ assert "followup_metadata" in result
+ assert result["followup_metadata"]["is_followup"] is True
+ assert result["followup_metadata"]["has_context"] is True
+
+ def test_empty_findings_has_context_false(self):
+ handler = _make_handler()
+ ctx = {"parent_research_id": "r1", "past_findings": ""}
+ result = handler.format_for_settings_snapshot(ctx)
+ assert result["followup_metadata"]["has_context"] is False
+
+
+class TestGetRelevantContextForLLM:
+ """Test get_relevant_context_for_llm."""
+
+ def test_includes_queries(self):
+ handler = _make_handler()
+ ctx = {
+ "original_query": "orig",
+ "follow_up_query": "followup",
+ }
+ result = handler.get_relevant_context_for_llm(ctx)
+ assert "orig" in result
+ assert "followup" in result
+
+ def test_includes_entities(self):
+ handler = _make_handler()
+ ctx = {
+ "original_query": "",
+ "follow_up_query": "",
+ "key_entities": ["Entity1", "Entity2"],
+ }
+ result = handler.get_relevant_context_for_llm(ctx)
+ assert "Entity1" in result
+
+ def test_truncates_to_max_tokens(self):
+ handler = _make_handler()
+ ctx = {
+ "original_query": "q",
+ "follow_up_query": "q",
+ "summary": "x" * 50000,
+ }
+ result = handler.get_relevant_context_for_llm(ctx, max_tokens=100)
+ assert len(result) <= 100 * 4 + 3 # max_chars + "..."
+
+ def test_includes_source_count(self):
+ handler = _make_handler()
+ ctx = {
+ "original_query": "",
+ "follow_up_query": "",
+ "past_sources": [{"url": "a"}, {"url": "b"}],
+ }
+ result = handler.get_relevant_context_for_llm(ctx)
+ assert "2" in result
diff --git a/tests/benchmarks/efficiency/test_resource_monitor_high_value.py b/tests/benchmarks/efficiency/test_resource_monitor_high_value.py
new file mode 100644
index 0000000000..79cb2dc5f1
--- /dev/null
+++ b/tests/benchmarks/efficiency/test_resource_monitor_high_value.py
@@ -0,0 +1,225 @@
+"""High-value tests for benchmarks/efficiency/resource_monitor.py.
+
+Covers ResourceMonitor init, start/stop lifecycle, stats computation,
+export_data, context manager, and check_system_resources.
+"""
+
+from unittest.mock import MagicMock, patch
+
+from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ check_system_resources,
+)
+
+
+class TestResourceMonitorInit:
+ """Test ResourceMonitor initialization."""
+
+ def test_default_sampling_interval(self):
+ monitor = ResourceMonitor()
+ assert monitor.sampling_interval == 1.0
+
+ def test_custom_sampling_interval(self):
+ monitor = ResourceMonitor(sampling_interval=0.5)
+ assert monitor.sampling_interval == 0.5
+
+ def test_not_monitoring_initially(self):
+ monitor = ResourceMonitor()
+ assert monitor.monitoring is False
+ assert monitor.monitor_thread is None
+
+ def test_empty_data_initially(self):
+ monitor = ResourceMonitor()
+ assert monitor.process_data == []
+ assert monitor.system_data == []
+
+ def test_track_flags_stored(self):
+ monitor = ResourceMonitor(track_process=False, track_system=True)
+ assert monitor.track_process is False
+ assert monitor.track_system is True
+
+
+class TestResourceMonitorStats:
+ """Test stats computation with pre-populated data."""
+
+ def test_get_process_stats_empty_returns_empty_dict(self):
+ """Empty process_data returns empty dict."""
+ monitor = ResourceMonitor()
+ assert monitor.get_process_stats() == {}
+
+ def test_get_system_stats_empty_returns_empty_dict(self):
+ """Empty system_data returns empty dict."""
+ monitor = ResourceMonitor()
+ assert monitor.get_system_stats() == {}
+
+ def test_get_process_stats_with_data(self):
+ """Process stats are computed correctly from pre-populated data."""
+ monitor = ResourceMonitor()
+ monitor.start_time = 100.0
+ monitor.end_time = 110.0
+ monitor.process_data = [
+ {
+ "timestamp": 101.0,
+ "cpu_percent": 10.0,
+ "memory_rss": 100 * 1024 * 1024, # 100 MB
+ "memory_vms": 200 * 1024 * 1024,
+ "memory_shared": 0,
+ "num_threads": 4,
+ "open_files": 2,
+ "status": "running",
+ },
+ {
+ "timestamp": 102.0,
+ "cpu_percent": 20.0,
+ "memory_rss": 200 * 1024 * 1024, # 200 MB
+ "memory_vms": 300 * 1024 * 1024,
+ "memory_shared": 0,
+ "num_threads": 6,
+ "open_files": 3,
+ "status": "running",
+ },
+ ]
+ stats = monitor.get_process_stats()
+ assert stats["duration"] == 10.0
+ assert stats["sample_count"] == 2
+ assert stats["cpu_min"] == 10.0
+ assert stats["cpu_max"] == 20.0
+ assert stats["cpu_avg"] == 15.0
+ assert stats["memory_min_mb"] == 100.0
+ assert stats["memory_max_mb"] == 200.0
+ assert stats["thread_max"] == 6
+
+ def test_get_system_stats_with_data(self):
+ """System stats are computed correctly."""
+ monitor = ResourceMonitor()
+ monitor.start_time = 100.0
+ monitor.end_time = 110.0
+ monitor.system_data = [
+ {
+ "timestamp": 101.0,
+ "cpu_percent": 30.0,
+ "memory_total": 16 * 1024**3,
+ "memory_available": 8 * 1024**3,
+ "memory_used": 8 * 1024**3,
+ "memory_percent": 50.0,
+ "disk_total": 500 * 1024**3,
+ "disk_used": 250 * 1024**3,
+ "disk_percent": 50.0,
+ },
+ ]
+ stats = monitor.get_system_stats()
+ assert stats["sample_count"] == 1
+ assert stats["cpu_min"] == 30.0
+ assert stats["memory_total_gb"] == 16.0
+ assert stats["disk_total_gb"] == 500.0
+
+ def test_get_combined_stats_merges_both(self):
+ """Combined stats include prefixed process and system stats."""
+ monitor = ResourceMonitor()
+ monitor.start_time = 100.0
+ monitor.end_time = 110.0
+ monitor.process_data = [
+ {
+ "timestamp": 101.0,
+ "cpu_percent": 10.0,
+ "memory_rss": 100 * 1024 * 1024,
+ "memory_vms": 200 * 1024 * 1024,
+ "memory_shared": 0,
+ "num_threads": 4,
+ "open_files": 2,
+ "status": "running",
+ },
+ ]
+ monitor.system_data = [
+ {
+ "timestamp": 101.0,
+ "cpu_percent": 30.0,
+ "memory_total": 16 * 1024**3,
+ "memory_available": 8 * 1024**3,
+ "memory_used": 8 * 1024**3,
+ "memory_percent": 50.0,
+ "disk_total": 500 * 1024**3,
+ "disk_used": 250 * 1024**3,
+ "disk_percent": 50.0,
+ },
+ ]
+ stats = monitor.get_combined_stats()
+ assert "process_cpu_avg" in stats
+ assert "system_cpu_avg" in stats
+ assert stats["duration"] == 10.0
+
+
+class TestResourceMonitorExport:
+ """Test export_data."""
+
+ def test_export_structure(self):
+ """Export contains all expected keys."""
+ monitor = ResourceMonitor(sampling_interval=2.0)
+ monitor.start_time = 100.0
+ monitor.end_time = 110.0
+ data = monitor.export_data()
+ assert data["start_time"] == 100.0
+ assert data["end_time"] == 110.0
+ assert data["sampling_interval"] == 2.0
+ assert data["process_data"] == []
+ assert data["system_data"] == []
+
+
+class TestResourceMonitorLifecycle:
+ """Test start/stop lifecycle."""
+
+ def test_stop_when_not_monitoring_is_noop(self):
+ """Stopping when not monitoring does nothing."""
+ monitor = ResourceMonitor()
+ monitor.stop() # Should not raise
+ assert monitor.monitoring is False
+
+ @patch(
+ "local_deep_research.benchmarks.efficiency.resource_monitor.PSUTIL_AVAILABLE",
+ False,
+ )
+ def test_start_without_psutil_is_noop(self):
+ """Start without psutil logs warning but doesn't crash."""
+ monitor = ResourceMonitor()
+ monitor.can_monitor = False
+ monitor.start()
+ assert monitor.monitoring is False
+
+
+class TestCheckSystemResources:
+ """Test the check_system_resources function."""
+
+ @patch(
+ "local_deep_research.benchmarks.efficiency.resource_monitor.PSUTIL_AVAILABLE",
+ False,
+ )
+ def test_returns_error_without_psutil(self):
+ """Returns error dict when psutil not available."""
+ result = check_system_resources()
+ assert result["available"] is False
+ assert "error" in result
+
+ @patch(
+ "local_deep_research.benchmarks.efficiency.resource_monitor.PSUTIL_AVAILABLE",
+ True,
+ )
+ @patch("local_deep_research.benchmarks.efficiency.resource_monitor.psutil")
+ def test_returns_system_info_with_psutil(self, mock_psutil):
+ """Returns system info when psutil is available."""
+ mock_psutil.cpu_count.return_value = 8
+ mock_psutil.cpu_percent.return_value = 25.0
+ mock_psutil.virtual_memory.return_value = MagicMock(
+ total=16 * 1024**3,
+ available=8 * 1024**3,
+ used=8 * 1024**3,
+ percent=50.0,
+ )
+ mock_psutil.disk_usage.return_value = MagicMock(
+ total=500 * 1024**3,
+ free=250 * 1024**3,
+ percent=50.0,
+ )
+ result = check_system_resources()
+ assert result["available"] is True
+ assert result["cpu_count"] == 8
+ assert result["memory_percent"] == 50.0
diff --git a/tests/benchmarks/test_comparison_high_value.py b/tests/benchmarks/test_comparison_high_value.py
new file mode 100644
index 0000000000..55ee7e41f3
--- /dev/null
+++ b/tests/benchmarks/test_comparison_high_value.py
@@ -0,0 +1,139 @@
+"""High-value tests for benchmarks/comparison/results.py.
+
+Covers Benchmark_results: add_result, get_all, get_best sorting,
+file loading, and edge cases.
+"""
+
+import json
+import pytest
+from unittest.mock import patch
+
+from local_deep_research.benchmarks.comparison.results import Benchmark_results
+
+
+class TestBenchmarkResultsInit:
+ """Test Benchmark_results initialization."""
+
+ def test_default_results_file(self, tmp_path, monkeypatch):
+ """Default results file is benchmark_results.json."""
+ monkeypatch.chdir(tmp_path)
+ br = Benchmark_results()
+ assert br.results_file == "benchmark_results.json"
+
+ def test_custom_results_file(self, tmp_path):
+ """Custom results file is used."""
+ f = tmp_path / "custom.json"
+ f.write_text("[]")
+ br = Benchmark_results(results_file=str(f))
+ assert br.results_file == str(f)
+
+ def test_empty_results_when_file_missing(self, tmp_path):
+ """Missing file results in empty list."""
+ br = Benchmark_results(results_file=str(tmp_path / "nonexistent.json"))
+ assert br.results == []
+
+ def test_loads_existing_results(self, tmp_path):
+ """Existing file's results are loaded."""
+ data = [{"model": "test", "accuracy_focused": 0.9}]
+ f = tmp_path / "results.json"
+ f.write_text(json.dumps(data))
+ br = Benchmark_results(results_file=str(f))
+ assert len(br.results) == 1
+ assert br.results[0]["model"] == "test"
+
+
+class TestBenchmarkResultsAddResult:
+ """Test add_result method."""
+
+ def test_add_result_appends_and_saves(self, tmp_path):
+ """add_result appends to results and calls _save_results."""
+ with patch.object(Benchmark_results, "_save_results"):
+ br = Benchmark_results(results_file=str(tmp_path / "nonexist.json"))
+ result = br.add_result(
+ model="gpt-4",
+ hardware="RTX 4090",
+ accuracy_focused=0.95,
+ accuracy_source=0.90,
+ avg_time_per_question=5.0,
+ context_window=128000,
+ temperature=0.0,
+ ldr_version="1.0",
+ date_tested="2024-01-01",
+ notes="test run",
+ )
+ assert result is True
+ assert len(br.results) == 1
+ assert br.results[0]["model"] == "gpt-4"
+ assert br.results[0]["notes"] == "test run"
+
+ def test_add_result_default_notes_empty(self, tmp_path):
+ """Notes defaults to empty string."""
+ with patch.object(Benchmark_results, "_save_results"):
+ br = Benchmark_results(results_file=str(tmp_path / "nonexist.json"))
+ br.add_result(
+ "m", "h", 0.5, 0.5, 1.0, 8192, 0.0, "1.0", "2024-01-01"
+ )
+ assert br.results[0]["notes"] == ""
+
+
+class TestBenchmarkResultsGetBest:
+ """Test get_best sorting."""
+
+ def _make_results(self, tmp_path):
+ f = tmp_path / "results.json"
+ data = [
+ {
+ "model": "fast",
+ "accuracy_focused": 0.7,
+ "accuracy_source": 0.6,
+ "avg_time_per_question": 1.0,
+ "hardware": "h",
+ "context_window": 8192,
+ "temperature": 0.0,
+ "ldr_version": "1.0",
+ "date_tested": "2024-01-01",
+ "notes": "",
+ },
+ {
+ "model": "accurate",
+ "accuracy_focused": 0.95,
+ "accuracy_source": 0.9,
+ "avg_time_per_question": 10.0,
+ "hardware": "h",
+ "context_window": 128000,
+ "temperature": 0.0,
+ "ldr_version": "1.0",
+ "date_tested": "2024-01-01",
+ "notes": "",
+ },
+ ]
+ f.write_text(json.dumps(data))
+ return Benchmark_results(results_file=str(f))
+
+ def test_sort_by_accuracy_descending(self, tmp_path):
+ """Default sort by accuracy_focused is descending."""
+ br = self._make_results(tmp_path)
+ best = br.get_best()
+ assert best[0]["model"] == "accurate"
+
+ def test_sort_by_time_ascending(self, tmp_path):
+ """Sort by avg_time_per_question is ascending."""
+ br = self._make_results(tmp_path)
+ best = br.get_best(sort_by="avg_time_per_question")
+ assert best[0]["model"] == "fast"
+
+ def test_invalid_sort_key_raises(self, tmp_path):
+ """Invalid sort_by key raises ValueError."""
+ br = self._make_results(tmp_path)
+ with pytest.raises(ValueError, match="Invalid sort_by key"):
+ br.get_best(sort_by="nonexistent_key")
+
+ def test_get_all_returns_all(self, tmp_path):
+ """get_all returns all results unchanged."""
+ br = self._make_results(tmp_path)
+ assert len(br.get_all()) == 2
+
+ def test_get_best_empty_results(self, tmp_path):
+ """get_best on empty results returns empty list."""
+ br = Benchmark_results(results_file=str(tmp_path / "nonexist.json"))
+ assert br.get_best() == []
diff --git a/tests/benchmarks/test_datasets_base_high_value.py b/tests/benchmarks/test_datasets_base_high_value.py
new file mode 100644
index 0000000000..a02f07ccd8
--- /dev/null
+++ b/tests/benchmarks/test_datasets_base_high_value.py
@@ -0,0 +1,271 @@
+"""High-value tests for benchmarks/datasets/base.py.
+
+Covers BenchmarkDataset ABC enforcement, DatasetRegistry CRUD,
+load() with different file formats, sampling, and get_example bounds.
+"""
+
+import json
+import pytest
+
+from local_deep_research.benchmarks.datasets.base import (
+ BenchmarkDataset,
+ DatasetRegistry,
+)
+
+
+class ConcreteBenchmarkDataset(BenchmarkDataset):
+ """Minimal concrete implementation for testing."""
+
+ @classmethod
+ def get_dataset_info(cls):
+ return {
+ "id": "test-dataset",
+ "name": "Test",
+ "description": "For testing",
+ }
+
+ @classmethod
+ def get_default_dataset_path(cls):
+ return "/tmp/test_dataset.json"
+
+ def process_example(self, example):
+ return example
+
+
+class TestBenchmarkDatasetABC:
+ """Test abstract base class enforcement."""
+
+ def test_cannot_instantiate_directly(self):
+ """BenchmarkDataset cannot be instantiated."""
+ with pytest.raises(TypeError):
+ BenchmarkDataset()
+
+ def test_incomplete_subclass_raises(self):
+ """Subclass missing abstract methods raises TypeError."""
+
+ class Incomplete(BenchmarkDataset):
+ pass
+
+ with pytest.raises(TypeError):
+ Incomplete()
+
+ def test_complete_subclass_instantiable(self):
+ """Complete subclass can be instantiated."""
+ ds = ConcreteBenchmarkDataset()
+ assert isinstance(ds, BenchmarkDataset)
+
+
+class TestBenchmarkDatasetInit:
+ """Test BenchmarkDataset initialization."""
+
+ def test_default_path_from_class_method(self):
+ """Uses get_default_dataset_path when no path provided."""
+ ds = ConcreteBenchmarkDataset()
+ assert ds.dataset_path == "/tmp/test_dataset.json"
+
+ def test_custom_path_overrides_default(self):
+ """Custom path overrides the default."""
+ ds = ConcreteBenchmarkDataset(dataset_path="/custom/path.json")
+ assert ds.dataset_path == "/custom/path.json"
+
+ def test_not_loaded_initially(self):
+ """Dataset is not loaded on init."""
+ ds = ConcreteBenchmarkDataset()
+ assert ds._is_loaded is False
+ assert ds.examples == []
+
+ def test_default_seed(self):
+ """Default seed is 42."""
+ ds = ConcreteBenchmarkDataset()
+ assert ds.seed == 42
+
+ def test_custom_num_examples(self):
+ """num_examples is stored correctly."""
+ ds = ConcreteBenchmarkDataset(num_examples=10)
+ assert ds.num_examples == 10
+
+
+class TestBenchmarkDatasetLoad:
+ """Test load() method."""
+
+ def test_load_json_file(self, tmp_path):
+ """Loads examples from a JSON file."""
+ data = [
+ {"problem": "Q1", "answer": "A1"},
+ {"problem": "Q2", "answer": "A2"},
+ ]
+ f = tmp_path / "data.json"
+ f.write_text(json.dumps(data))
+
+ ds = ConcreteBenchmarkDataset(dataset_path=str(f))
+ examples = ds.load()
+ assert len(examples) == 2
+ assert ds._is_loaded is True
+
+ def test_load_jsonl_file(self, tmp_path):
+ """Loads examples from a JSONL file."""
+ lines = ['{"problem": "Q1", "answer": "A1"}\n', '{"problem": "Q2"}\n']
+ f = tmp_path / "data.jsonl"
+ f.write_text("".join(lines))
+
+ ds = ConcreteBenchmarkDataset(dataset_path=str(f))
+ examples = ds.load()
+ assert len(examples) == 2
+
+ def test_load_csv_file(self, tmp_path):
+ """Loads examples from a CSV file."""
+ f = tmp_path / "data.csv"
+ f.write_text("problem,answer\nQ1,A1\nQ2,A2\n")
+
+ ds = ConcreteBenchmarkDataset(dataset_path=str(f))
+ examples = ds.load()
+ assert len(examples) == 2
+
+ def test_unsupported_format_raises(self, tmp_path):
+ """Unsupported file format raises ValueError."""
+ f = tmp_path / "data.xml"
+ f.write_text("<data/>")
+
+ ds = ConcreteBenchmarkDataset(dataset_path=str(f))
+ with pytest.raises(ValueError, match="Unsupported file format"):
+ ds.load()
+
+ def test_load_returns_cached_on_second_call(self, tmp_path):
+ """Second call to load() returns cached results."""
+ f = tmp_path / "data.json"
+ f.write_text(json.dumps([{"q": "1"}]))
+
+ ds = ConcreteBenchmarkDataset(dataset_path=str(f))
+ first = ds.load()
+ second = ds.load()
+ assert first is second
+
+ def test_sampling_with_num_examples(self, tmp_path):
+ """load() samples when num_examples < total examples."""
+ data = [{"q": str(i)} for i in range(100)]
+ f = tmp_path / "data.json"
+ f.write_text(json.dumps(data))
+
+ ds = ConcreteBenchmarkDataset(dataset_path=str(f), num_examples=10)
+ examples = ds.load()
+ assert len(examples) == 10
+
+ def test_sampling_deterministic_with_seed(self, tmp_path):
+ """Same seed produces same sample."""
+ data = [{"q": str(i)} for i in range(100)]
+ f = tmp_path / "data.json"
+ f.write_text(json.dumps(data))
+
+ ds1 = ConcreteBenchmarkDataset(
+ dataset_path=str(f), num_examples=5, seed=42
+ )
+ ds2 = ConcreteBenchmarkDataset(
+ dataset_path=str(f), num_examples=5, seed=42
+ )
+ assert ds1.load() == ds2.load()
+
+ def test_process_example_error_counted(self, tmp_path):
+ """Errors during process_example are counted, not raised."""
+ data = [{"q": "1"}, {"q": "2"}, {"q": "3"}]
+ f = tmp_path / "data.json"
+ f.write_text(json.dumps(data))
+
+ class FailingDataset(ConcreteBenchmarkDataset):
+ def process_example(self, example):
+ if example["q"] == "2":
+ raise RuntimeError("bad example")
+ return example
+
+ ds = FailingDataset(dataset_path=str(f))
+ examples = ds.load()
+ assert len(examples) == 2 # 3 total - 1 failed
+
+
+class TestBenchmarkDatasetGetters:
+ """Test get_example, get_question, get_answer."""
+
+ def test_get_example_valid_index(self, tmp_path):
+ """get_example returns the correct example."""
+ f = tmp_path / "data.json"
+ f.write_text(json.dumps([{"q": "A"}, {"q": "B"}]))
+ ds = ConcreteBenchmarkDataset(dataset_path=str(f))
+ assert ds.get_example(1)["q"] == "B"
+
+ def test_get_example_out_of_range(self, tmp_path):
+ """get_example raises IndexError for invalid index."""
+ f = tmp_path / "data.json"
+ f.write_text(json.dumps([{"q": "A"}]))
+ ds = ConcreteBenchmarkDataset(dataset_path=str(f))
+ with pytest.raises(IndexError):
+ ds.get_example(5)
+
+ def test_get_example_negative_index_raises(self, tmp_path):
+ """Negative index raises IndexError."""
+ f = tmp_path / "data.json"
+ f.write_text(json.dumps([{"q": "A"}]))
+ ds = ConcreteBenchmarkDataset(dataset_path=str(f))
+ with pytest.raises(IndexError):
+ ds.get_example(-1)
+
+ def test_get_question_returns_problem_field(self):
+ """get_question extracts 'problem' field."""
+ ds = ConcreteBenchmarkDataset()
+ assert ds.get_question({"problem": "What is X?"}) == "What is X?"
+
+ def test_get_question_missing_field_returns_empty(self):
+ """Missing 'problem' field returns empty string."""
+ ds = ConcreteBenchmarkDataset()
+ assert ds.get_question({}) == ""
+
+ def test_get_answer_prefers_correct_answer(self):
+ """get_answer prefers 'correct_answer' over 'answer'."""
+ ds = ConcreteBenchmarkDataset()
+ example = {"correct_answer": "CA", "answer": "A"}
+ assert ds.get_answer(example) == "CA"
+
+ def test_get_answer_falls_back_to_answer(self):
+ """get_answer falls back to 'answer' field."""
+ ds = ConcreteBenchmarkDataset()
+ assert ds.get_answer({"answer": "A"}) == "A"
+
+
+class TestDatasetRegistry:
+ """Test DatasetRegistry registration and retrieval."""
+
+ def setup_method(self):
+ """Clear registry before each test."""
+ DatasetRegistry._registry = {}
+
+ def test_register_stores_class(self):
+ """register() stores the class by its ID."""
+ DatasetRegistry.register(ConcreteBenchmarkDataset)
+ assert "test-dataset" in DatasetRegistry._registry
+
+ def test_register_no_id_raises(self):
+ """register() raises when dataset has no ID."""
+
+ class NoIdDataset(ConcreteBenchmarkDataset):
+ @classmethod
+ def get_dataset_info(cls):
+ return {"name": "No ID"}
+
+ with pytest.raises(ValueError, match="must have an ID"):
+ DatasetRegistry.register(NoIdDataset)
+
+ def test_get_dataset_class_unknown_raises(self):
+ """get_dataset_class raises for unknown ID."""
+ with pytest.raises(ValueError, match="Unknown dataset"):
+ DatasetRegistry.get_dataset_class("nonexistent")
+
+ def test_create_dataset_returns_instance(self):
+ """create_dataset returns a BenchmarkDataset instance."""
+ DatasetRegistry.register(ConcreteBenchmarkDataset)
+ ds = DatasetRegistry.create_dataset("test-dataset")
+ assert isinstance(ds, BenchmarkDataset)
+
+ def test_get_available_datasets(self):
+ """get_available_datasets returns info for all registered datasets."""
+ DatasetRegistry.register(ConcreteBenchmarkDataset)
+ available = DatasetRegistry.get_available_datasets()
+ assert len(available) == 1
+ assert available[0]["id"] == "test-dataset"
diff --git a/tests/news/rating_system/test_rating_system_high_value.py b/tests/news/rating_system/test_rating_system_high_value.py
new file mode 100644
index 0000000000..371ec752e5
--- /dev/null
+++ b/tests/news/rating_system/test_rating_system_high_value.py
@@ -0,0 +1,177 @@
+"""High-value tests for news/rating_system/base_rater.py.
+
+Covers enums, ABC enforcement, QualityRatingSystem and RelevanceRatingSystem
+validation, rating records, and default method behavior.
+"""
+
+import pytest
+
+from local_deep_research.news.rating_system.base_rater import (
+ BaseRatingSystem,
+ QualityRating,
+ QualityRatingSystem,
+ RelevanceRating,
+ RelevanceRatingSystem,
+)
+
+
+class TestRatingEnums:
+ """Test rating enum values."""
+
+ def test_relevance_up_value(self):
+ assert RelevanceRating.UP.value == "up"
+
+ def test_relevance_down_value(self):
+ assert RelevanceRating.DOWN.value == "down"
+
+ def test_quality_star_values(self):
+ assert QualityRating.ONE_STAR.value == 1
+ assert QualityRating.FIVE_STARS.value == 5
+
+ def test_quality_has_five_levels(self):
+ assert len(QualityRating) == 5
+
+
+class TestBaseRatingSystemABC:
+ """Test BaseRatingSystem abstract base class."""
+
+ def test_cannot_instantiate_directly(self):
+ with pytest.raises(TypeError):
+ BaseRatingSystem()
+
+ def test_incomplete_subclass_raises(self):
+ class Incomplete(BaseRatingSystem):
+ pass
+
+ with pytest.raises(TypeError):
+ Incomplete()
+
+ def test_rating_type_set_from_class_name(self):
+ """rating_type is set to the class name."""
+ system = QualityRatingSystem()
+ assert system.rating_type == "QualityRatingSystem"
+
+
+class TestBaseRatingSystemDefaults:
+ """Test default method implementations."""
+
+ def test_get_recent_ratings_returns_empty(self):
+ """Default get_recent_ratings returns empty list."""
+ system = QualityRatingSystem()
+ assert system.get_recent_ratings("user1") == []
+
+ def test_get_card_ratings_returns_zero(self):
+ """Default get_card_ratings returns zero total."""
+ system = QualityRatingSystem()
+ result = system.get_card_ratings("card1")
+ assert result["total"] == 0
+ assert result["average"] is None
+
+ def test_remove_rating_returns_false(self):
+ """Default remove_rating returns False."""
+ system = QualityRatingSystem()
+ assert system.remove_rating("user1", "card1") is False
+
+
+class TestBaseRatingSystemValidation:
+ """Test _validate_rating_value."""
+
+ def test_none_value_raises(self):
+ """None rating value raises ValueError."""
+ system = QualityRatingSystem()
+ with pytest.raises(ValueError, match="cannot be None"):
+ system._validate_rating_value(None)
+
+
+class TestCreateRatingRecord:
+ """Test _create_rating_record helper."""
+
+ def test_record_has_expected_keys(self):
+ system = QualityRatingSystem()
+ record = system._create_rating_record(
+ "user1", "card1", QualityRating.FIVE_STARS
+ )
+ expected_keys = {
+ "user_id",
+ "card_id",
+ "rating_type",
+ "rating_value",
+ "rated_at",
+ "metadata",
+ }
+ assert set(record.keys()) == expected_keys
+
+ def test_record_metadata_defaults_to_empty_dict(self):
+ system = QualityRatingSystem()
+ record = system._create_rating_record("u", "c", QualityRating.ONE_STAR)
+ assert record["metadata"] == {}
+
+ def test_record_preserves_metadata(self):
+ system = QualityRatingSystem()
+ meta = {"source": "test"}
+ record = system._create_rating_record(
+ "u", "c", QualityRating.ONE_STAR, metadata=meta
+ )
+ assert record["metadata"]["source"] == "test"
+
+ def test_record_rating_type_from_get_rating_type(self):
+ system = QualityRatingSystem()
+ record = system._create_rating_record("u", "c", QualityRating.ONE_STAR)
+ assert record["rating_type"] == "quality"
+
+
+class TestQualityRatingSystem:
+ """Test QualityRatingSystem."""
+
+ def test_get_rating_type(self):
+ assert QualityRatingSystem().get_rating_type() == "quality"
+
+ def test_rate_success(self):
+ system = QualityRatingSystem()
+ result = system.rate("user1", "card1", QualityRating.FOUR_STARS)
+ assert result["success"] is True
+ assert "4 stars" in result["message"]
+
+ def test_rate_invalid_value_raises(self):
+ """Non-QualityRating value raises ValueError."""
+ system = QualityRatingSystem()
+ with pytest.raises(ValueError, match="QualityRating"):
+ system.rate("user1", "card1", "invalid")
+
+ def test_rate_integer_raises(self):
+ """Plain integer raises ValueError (must be enum)."""
+ system = QualityRatingSystem()
+ with pytest.raises(ValueError):
+ system.rate("user1", "card1", 5)
+
+ def test_get_rating_no_backend_returns_none(self):
+ system = QualityRatingSystem()
+ assert system.get_rating("user1", "card1") is None
+
+
+class TestRelevanceRatingSystem:
+ """Test RelevanceRatingSystem."""
+
+ def test_get_rating_type(self):
+ assert RelevanceRatingSystem().get_rating_type() == "relevance"
+
+ def test_rate_up(self):
+ system = RelevanceRatingSystem()
+ result = system.rate("user1", "card1", RelevanceRating.UP)
+ assert result["success"] is True
+ assert "thumbs up" in result["message"]
+
+ def test_rate_down(self):
+ system = RelevanceRatingSystem()
+ result = system.rate("user1", "card1", RelevanceRating.DOWN)
+ assert result["success"] is True
+ assert "thumbs down" in result["message"]
+
+ def test_rate_invalid_value_raises(self):
+ system = RelevanceRatingSystem()
+ with pytest.raises(ValueError, match="RelevanceRating"):
+ system.rate("user1", "card1", "thumbs_up")
+
+ def test_get_rating_no_backend_returns_none(self):
+ system = RelevanceRatingSystem()
+ assert system.get_rating("user1", "card1") is None
diff --git a/tests/news/subscription_manager/test_base_subscription_high_value.py b/tests/news/subscription_manager/test_base_subscription_high_value.py
new file mode 100644
index 0000000000..5bea59a832
--- /dev/null
+++ b/tests/news/subscription_manager/test_base_subscription_high_value.py
@@ -0,0 +1,202 @@
+"""High-value tests for news/subscription_manager/base_subscription.py.
+
+Covers BaseSubscription lifecycle: init, should_refresh, error handling,
+exponential backoff, pause/resume, update_interval, and to_dict.
+"""
+
+import pytest
+from unittest.mock import patch
+
+from local_deep_research.news.subscription_manager.base_subscription import (
+ BaseSubscription,
+)
+from local_deep_research.news.core.base_card import CardSource
+
+
+class ConcreteSubscription(BaseSubscription):
+ """Concrete implementation for testing."""
+
+ def __init__(self, *args, **kwargs):
+ with patch(
+ "local_deep_research.news.subscription_manager.base_subscription.SQLSubscriptionStorage"
+ ):
+ super().__init__(*args, **kwargs)
+ self.subscription_type = "test"
+
+ def generate_search_query(self):
+ return self.query_or_topic
+
+ def get_subscription_type(self):
+ return "test_subscription"
+
+
+def _make_source():
+ return CardSource(type="test", source_id="src1", created_from="manual")
+
+
+class TestBaseSubscriptionInit:
+ """Test initialization."""
+
+ def test_stores_basic_fields(self):
+ sub = ConcreteSubscription("user1", _make_source(), "test query")
+ assert sub.user_id == "user1"
+ assert sub.query_or_topic == "test query"
+ assert sub.is_active is True
+
+ def test_default_interval(self):
+ sub = ConcreteSubscription("user1", _make_source(), "q")
+ assert sub.refresh_interval_minutes == 240
+
+ def test_custom_interval(self):
+ sub = ConcreteSubscription(
+ "user1", _make_source(), "q", refresh_interval_minutes=120
+ )
+ assert sub.refresh_interval_minutes == 120
+
+ def test_generates_id_when_not_provided(self):
+ sub = ConcreteSubscription("user1", _make_source(), "q")
+ assert sub.id is not None and len(sub.id) > 0
+
+ def test_uses_provided_id(self):
+ sub = ConcreteSubscription(
+ "user1", _make_source(), "q", subscription_id="custom-id"
+ )
+ assert sub.id == "custom-id"
+
+ def test_initial_refresh_count_zero(self):
+ sub = ConcreteSubscription("user1", _make_source(), "q")
+ assert sub.refresh_count == 0
+ assert sub.error_count == 0
+ assert sub.last_error is None
+
+
+class TestShouldRefresh:
+ """Test should_refresh logic."""
+
+ def test_inactive_subscription_should_not_refresh(self):
+ sub = ConcreteSubscription("user1", _make_source(), "q")
+ sub.is_active = False
+ assert sub.should_refresh() is False
+
+ def test_is_due_for_refresh_alias(self):
+ """is_due_for_refresh is an alias for should_refresh."""
+ sub = ConcreteSubscription("user1", _make_source(), "q")
+ assert sub.is_due_for_refresh() == sub.should_refresh()
+
+
+class TestRefreshCallbacks:
+ """Test on_refresh_start, on_refresh_success, on_refresh_error."""
+
+ def test_on_refresh_start_sets_last_refreshed(self):
+ sub = ConcreteSubscription("user1", _make_source(), "q")
+ assert sub.last_refreshed is None
+ sub.on_refresh_start()
+ assert sub.last_refreshed is not None
+
+ def test_on_refresh_success_increments_count(self):
+ sub = ConcreteSubscription("user1", _make_source(), "q")
+ sub.on_refresh_start()
+ sub.on_refresh_success(["result"])
+ assert sub.refresh_count == 1
+
+ def test_on_refresh_success_resets_errors(self):
+ sub = ConcreteSubscription("user1", _make_source(), "q")
+ sub.error_count = 3
+ sub.on_refresh_start()
+ sub.on_refresh_success(["result"])
+ assert sub.error_count == 0
+
+ def test_on_refresh_error_increments_error_count(self):
+ sub = ConcreteSubscription("user1", _make_source(), "q")
+ sub.on_refresh_error(RuntimeError("test error"))
+ assert sub.error_count == 1
+ assert sub.last_error == "test error"
+
+ def test_on_refresh_error_exponential_backoff(self):
+ """Error backoff increases next_refresh time exponentially."""
+ sub = ConcreteSubscription("user1", _make_source(), "q")
+ first_next = sub.next_refresh
+ sub.on_refresh_error(RuntimeError("err"))
+ after_first_error = sub.next_refresh
+ # After error, next_refresh should be further in the future
+ assert after_first_error > first_next
+
+ def test_disables_after_10_errors(self):
+ """Subscription disabled after 10 consecutive errors."""
+ sub = ConcreteSubscription("user1", _make_source(), "q")
+ for _ in range(10):
+ sub.on_refresh_error(RuntimeError("err"))
+ assert sub.is_active is False
+ assert sub.error_count == 10
+
+
+class TestPauseResume:
+ """Test pause and resume."""
+
+ def test_pause_deactivates(self):
+ sub = ConcreteSubscription("user1", _make_source(), "q")
+ sub.pause()
+ assert sub.is_active is False
+
+ def test_resume_activates_and_resets_errors(self):
+ sub = ConcreteSubscription("user1", _make_source(), "q")
+ sub.error_count = 5
+ sub.is_active = False
+ sub.resume()
+ assert sub.is_active is True
+ assert sub.error_count == 0
+
+
+class TestUpdateInterval:
+ """Test update_interval validation."""
+
+ def test_valid_interval(self):
+ sub = ConcreteSubscription("user1", _make_source(), "q")
+ sub.update_interval(120)
+ assert sub.refresh_interval_minutes == 120
+
+ def test_too_short_interval_raises(self):
+ sub = ConcreteSubscription("user1", _make_source(), "q")
+ with pytest.raises(ValueError, match="at least 60"):
+ sub.update_interval(30)
+
+ def test_too_long_interval_raises(self):
+ sub = ConcreteSubscription("user1", _make_source(), "q")
+ with pytest.raises(ValueError, match="30 days"):
+ sub.update_interval(60 * 24 * 31)
+
+
+class TestToDict:
+ """Test to_dict serialization."""
+
+ def test_has_expected_keys(self):
+ sub = ConcreteSubscription("user1", _make_source(), "test query")
+ d = sub.to_dict()
+ expected_keys = {
+ "id",
+ "type",
+ "user_id",
+ "query_or_topic",
+ "source",
+ "created_at",
+ "last_refreshed",
+ "next_refresh",
+ "refresh_interval_minutes",
+ "is_active",
+ "refresh_count",
+ "error_count",
+ "last_error",
+ "metadata",
+ }
+ assert set(d.keys()) == expected_keys
+
+ def test_last_refreshed_none_serialized(self):
+ """last_refreshed=None serialized as None."""
+ sub = ConcreteSubscription("user1", _make_source(), "q")
+ assert sub.to_dict()["last_refreshed"] is None
+
+ def test_source_dict_structure(self):
+ sub = ConcreteSubscription("user1", _make_source(), "q")
+ source_dict = sub.to_dict()["source"]
+ assert "type" in source_dict
+ assert "source_id" in source_dict