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 more tests to improve code coverage

LearningCircuitc8fa6630519a
diff --git a/tests/advanced_search_system/tools/__init__.py b/tests/advanced_search_system/tools/__init__.py
new file mode 100644
index 0000000000..bd46a8989d
--- /dev/null
+++ b/tests/advanced_search_system/tools/__init__.py
@@ -0,0 +1 @@
+"""Tests for advanced_search_system/tools module."""
diff --git a/tests/advanced_search_system/tools/test_base_tool.py b/tests/advanced_search_system/tools/test_base_tool.py
new file mode 100644
index 0000000000..715968a86f
--- /dev/null
+++ b/tests/advanced_search_system/tools/test_base_tool.py
@@ -0,0 +1,262 @@
+"""
+Tests for advanced_search_system/tools/base_tool.py
+
+Tests cover:
+- TYPE_MAP constant
+- BaseTool class initialization and methods
+- Parameter validation
+"""
+
+from unittest.mock import patch
+
+
+class TestTypeMap:
+ """Tests for TYPE_MAP constant."""
+
+ def test_type_map_exists(self):
+ """Test that TYPE_MAP is defined."""
+ from local_deep_research.advanced_search_system.tools.base_tool import (
+ TYPE_MAP,
+ )
+
+ assert TYPE_MAP is not None
+ assert isinstance(TYPE_MAP, dict)
+
+ def test_contains_common_types(self):
+ """Test that common types are mapped."""
+ from local_deep_research.advanced_search_system.tools.base_tool import (
+ TYPE_MAP,
+ )
+
+ assert TYPE_MAP["str"] is str
+ assert TYPE_MAP["int"] is int
+ assert TYPE_MAP["float"] is float
+ assert TYPE_MAP["bool"] is bool
+ assert TYPE_MAP["list"] is list
+ assert TYPE_MAP["dict"] is dict
+
+ def test_contains_collection_types(self):
+ """Test that collection types are mapped."""
+ from local_deep_research.advanced_search_system.tools.base_tool import (
+ TYPE_MAP,
+ )
+
+ assert TYPE_MAP["tuple"] is tuple
+ assert TYPE_MAP["set"] is set
+
+
+class ConcreteTool:
+ """Concrete implementation of BaseTool for testing."""
+
+ def __init__(self, name="test_tool", description="A test tool"):
+ # We can't subclass ABC directly in tests, so we'll access methods
+ self.name = name
+ self.description = description
+ self.parameters = {}
+
+ def execute(self, **kwargs):
+ return f"Executed with {kwargs}"
+
+
+class TestBaseTool:
+ """Tests for BaseTool class."""
+
+ def test_init_sets_name_and_description(self):
+ """Test that __init__ sets name and description."""
+ from local_deep_research.advanced_search_system.tools.base_tool import (
+ BaseTool,
+ )
+
+ # Create a minimal concrete subclass
+ class TestTool(BaseTool):
+ def execute(self, **kwargs):
+ return "result"
+
+ tool = TestTool(name="my_tool", description="Does something")
+
+ assert tool.name == "my_tool"
+ assert tool.description == "Does something"
+ assert tool.parameters == {}
+
+ def test_get_schema_returns_correct_format(self):
+ """Test that get_schema returns proper format."""
+ from local_deep_research.advanced_search_system.tools.base_tool import (
+ BaseTool,
+ )
+
+ class TestTool(BaseTool):
+ def execute(self, **kwargs):
+ return "result"
+
+ tool = TestTool(name="my_tool", description="Does something")
+ tool.parameters = {
+ "query": {"type": "str", "required": True},
+ }
+
+ schema = tool.get_schema()
+
+ assert schema["name"] == "my_tool"
+ assert schema["description"] == "Does something"
+ assert "query" in schema["parameters"]
+
+ def test_validate_parameters_returns_true_for_valid(self):
+ """Test validation returns True for valid parameters."""
+ from local_deep_research.advanced_search_system.tools.base_tool import (
+ BaseTool,
+ )
+
+ class TestTool(BaseTool):
+ def execute(self, **kwargs):
+ return "result"
+
+ tool = TestTool(name="test", description="test")
+ tool.parameters = {
+ "query": {"type": "str", "required": True},
+ }
+
+ result = tool.validate_parameters(query="hello")
+
+ assert result is True
+
+ def test_validate_parameters_returns_false_for_missing_required(self):
+ """Test validation returns False for missing required parameter."""
+ from local_deep_research.advanced_search_system.tools.base_tool import (
+ BaseTool,
+ )
+
+ class TestTool(BaseTool):
+ def execute(self, **kwargs):
+ return "result"
+
+ tool = TestTool(name="test", description="test")
+ tool.parameters = {
+ "query": {"type": "str", "required": True},
+ }
+
+ result = tool.validate_parameters() # Missing 'query'
+
+ assert result is False
+
+ def test_validate_parameters_allows_optional_missing(self):
+ """Test validation allows missing optional parameters."""
+ from local_deep_research.advanced_search_system.tools.base_tool import (
+ BaseTool,
+ )
+
+ class TestTool(BaseTool):
+ def execute(self, **kwargs):
+ return "result"
+
+ tool = TestTool(name="test", description="test")
+ tool.parameters = {
+ "query": {"type": "str", "required": False},
+ }
+
+ result = tool.validate_parameters() # Missing optional param
+
+ assert result is True
+
+ def test_validate_parameters_returns_false_for_wrong_type(self):
+ """Test validation returns False for wrong parameter type."""
+ from local_deep_research.advanced_search_system.tools.base_tool import (
+ BaseTool,
+ )
+
+ class TestTool(BaseTool):
+ def execute(self, **kwargs):
+ return "result"
+
+ tool = TestTool(name="test", description="test")
+ tool.parameters = {
+ "count": {"type": "int", "required": True},
+ }
+
+ result = tool.validate_parameters(count="not an int")
+
+ assert result is False
+
+ def test_validate_parameters_checks_enum_values(self):
+ """Test validation checks enum values."""
+ from local_deep_research.advanced_search_system.tools.base_tool import (
+ BaseTool,
+ )
+
+ class TestTool(BaseTool):
+ def execute(self, **kwargs):
+ return "result"
+
+ tool = TestTool(name="test", description="test")
+ tool.parameters = {
+ "mode": {"type": "str", "enum": ["fast", "slow"]},
+ }
+
+ # Valid enum value
+ assert tool.validate_parameters(mode="fast") is True
+
+ # Invalid enum value
+ assert tool.validate_parameters(mode="medium") is False
+
+ def test_validate_parameters_ignores_unknown_types(self):
+ """Test validation ignores unknown type strings."""
+ from local_deep_research.advanced_search_system.tools.base_tool import (
+ BaseTool,
+ )
+
+ class TestTool(BaseTool):
+ def execute(self, **kwargs):
+ return "result"
+
+ tool = TestTool(name="test", description="test")
+ tool.parameters = {
+ "custom": {"type": "unknown_type"}, # Unknown type
+ }
+
+ # Should not fail validation for unknown types
+ result = tool.validate_parameters(custom="anything")
+
+ assert result is True
+
+ def test_log_execution_logs_info(self):
+ """Test that _log_execution logs properly."""
+ from local_deep_research.advanced_search_system.tools.base_tool import (
+ BaseTool,
+ )
+
+ class TestTool(BaseTool):
+ def execute(self, **kwargs):
+ return "result"
+
+ tool = TestTool(name="test_tool", description="test")
+
+ with patch(
+ "local_deep_research.advanced_search_system.tools.base_tool.logger"
+ ) as mock_logger:
+ tool._log_execution(param1="value1", param2="value2")
+
+ mock_logger.info.assert_called()
+ # Should mention tool name and parameter count
+ call_args = mock_logger.info.call_args[0][0]
+ assert "test_tool" in call_args
+ assert "2" in call_args
+
+ def test_log_result_logs_info(self):
+ """Test that _log_result logs properly."""
+ from local_deep_research.advanced_search_system.tools.base_tool import (
+ BaseTool,
+ )
+
+ class TestTool(BaseTool):
+ def execute(self, **kwargs):
+ return "result"
+
+ tool = TestTool(name="test_tool", description="test")
+
+ with patch(
+ "local_deep_research.advanced_search_system.tools.base_tool.logger"
+ ) as mock_logger:
+ tool._log_result("my_result")
+
+ mock_logger.info.assert_called()
+ call_args = mock_logger.info.call_args[0][0]
+ assert "test_tool" in call_args
+ assert "my_result" in call_args
diff --git a/tests/benchmarks/test_datasets_utils.py b/tests/benchmarks/test_datasets_utils.py
new file mode 100644
index 0000000000..abce546c88
--- /dev/null
+++ b/tests/benchmarks/test_datasets_utils.py
@@ -0,0 +1,179 @@
+"""
+Tests for benchmarks/datasets/utils.py
+
+Tests cover:
+- derive_key function for key derivation
+- decrypt function for XOR decryption
+- get_known_answer_map function
+"""
+
+import base64
+
+
+class TestDeriveKey:
+ """Tests for the derive_key function."""
+
+ def test_derives_consistent_key(self):
+ """Test that same password produces same key."""
+ from local_deep_research.benchmarks.datasets.utils import derive_key
+
+ key1 = derive_key("password123", 32)
+ key2 = derive_key("password123", 32)
+
+ assert key1 == key2
+
+ def test_different_passwords_produce_different_keys(self):
+ """Test that different passwords produce different keys."""
+ from local_deep_research.benchmarks.datasets.utils import derive_key
+
+ key1 = derive_key("password1", 32)
+ key2 = derive_key("password2", 32)
+
+ assert key1 != key2
+
+ def test_key_has_requested_length(self):
+ """Test that key has the requested length."""
+ from local_deep_research.benchmarks.datasets.utils import derive_key
+
+ for length in [16, 32, 64, 100]:
+ key = derive_key("password", length)
+ assert len(key) == length
+
+ def test_handles_short_length(self):
+ """Test handling of short key lengths."""
+ from local_deep_research.benchmarks.datasets.utils import derive_key
+
+ key = derive_key("password", 8)
+ assert len(key) == 8
+
+ def test_handles_long_length(self):
+ """Test handling of long key lengths (requires key repetition)."""
+ from local_deep_research.benchmarks.datasets.utils import derive_key
+
+ key = derive_key("password", 128)
+ assert len(key) == 128
+
+ def test_empty_password(self):
+ """Test handling of empty password."""
+ from local_deep_research.benchmarks.datasets.utils import derive_key
+
+ key = derive_key("", 32)
+ assert len(key) == 32
+
+
+class TestDecrypt:
+ """Tests for the decrypt function."""
+
+ def test_returns_short_strings_unchanged(self):
+ """Test that strings shorter than 8 chars are returned unchanged."""
+ from local_deep_research.benchmarks.datasets.utils import decrypt
+
+ result = decrypt("short", "password")
+ assert result == "short"
+
+ def test_returns_non_base64_unchanged(self):
+ """Test that non-base64 strings are returned unchanged."""
+ from local_deep_research.benchmarks.datasets.utils import decrypt
+
+ # Contains characters not in base64 alphabet
+ result = decrypt("not@base64!string", "password")
+ assert result == "not@base64!string"
+
+ def test_returns_non_string_unchanged(self):
+ """Test that non-string input is returned unchanged."""
+ from local_deep_research.benchmarks.datasets.utils import decrypt
+
+ result = decrypt(12345, "password")
+ assert result == 12345
+
+ def test_known_encryption_decryption(self):
+ """Test decryption with known encrypted value."""
+ from local_deep_research.benchmarks.datasets.utils import (
+ decrypt,
+ derive_key,
+ )
+
+ # Create a known encrypted value
+ plaintext = "Hello World test message"
+ password = "test_password"
+
+ # Encrypt
+ key = derive_key(password, len(plaintext.encode()))
+ encrypted = bytes(
+ a ^ b for a, b in zip(plaintext.encode(), key, strict=False)
+ )
+ ciphertext_b64 = base64.b64encode(encrypted).decode()
+
+ # Decrypt should return original
+ result = decrypt(ciphertext_b64, password)
+ assert result == plaintext
+
+ def test_invalid_base64_returns_original(self):
+ """Test that invalid base64 returns original string."""
+ from local_deep_research.benchmarks.datasets.utils import decrypt
+
+ # Valid base64 chars but invalid padding/encoding
+ invalid = "AAAAAAAA" # Valid chars but may not decode properly
+ result = decrypt(invalid, "password")
+ # Should return something (either original or decrypted)
+ assert isinstance(result, str)
+
+ def test_decryption_with_hardcoded_key_fallback(self):
+ """Test that hardcoded key fallback is attempted."""
+ from local_deep_research.benchmarks.datasets.utils import decrypt
+
+ # Create encrypted with hardcoded BrowseComp key
+ plaintext = "This is a test message with spaces"
+ password = "MHGGF2022!"
+
+ from local_deep_research.benchmarks.datasets.utils import derive_key
+
+ key = derive_key(password, len(plaintext.encode()))
+ encrypted = bytes(
+ a ^ b for a, b in zip(plaintext.encode(), key, strict=False)
+ )
+ ciphertext_b64 = base64.b64encode(encrypted).decode()
+
+ # Should decrypt using hardcoded key as fallback
+ result = decrypt(ciphertext_b64, "wrong_password")
+ assert result == plaintext
+
+
+class TestGetKnownAnswerMap:
+ """Tests for the get_known_answer_map function."""
+
+ def test_returns_dictionary(self):
+ """Test that function returns a dictionary."""
+ from local_deep_research.benchmarks.datasets.utils import (
+ get_known_answer_map,
+ )
+
+ result = get_known_answer_map()
+ assert isinstance(result, dict)
+
+ def test_contains_known_mappings(self):
+ """Test that known mappings are present."""
+ from local_deep_research.benchmarks.datasets.utils import (
+ get_known_answer_map,
+ )
+
+ result = get_known_answer_map()
+
+ # Check known mappings exist
+ assert "dFoTn+K+bcdyWg==" in result
+ assert result["dFoTn+K+bcdyWg=="] == "Tooth Rock"
+
+ assert "ERFIwA==" in result
+ assert result["ERFIwA=="] == "1945"
+
+ def test_values_are_strings(self):
+ """Test that all values are strings."""
+ from local_deep_research.benchmarks.datasets.utils import (
+ get_known_answer_map,
+ )
+
+ result = get_known_answer_map()
+
+ for key, value in result.items():
+ assert isinstance(key, str)
+ assert isinstance(value, str)
diff --git a/tests/benchmarks/test_metrics_calculation.py b/tests/benchmarks/test_metrics_calculation.py
new file mode 100644
index 0000000000..7edced47d3
--- /dev/null
+++ b/tests/benchmarks/test_metrics_calculation.py
@@ -0,0 +1,303 @@
+"""
+Tests for benchmarks/metrics/calculation.py
+
+Tests cover:
+- calculate_metrics function
+- calculate_combined_score function
+- calculate_resource_metrics function
+"""
+
+import json
+
+
+class TestCalculateMetrics:
+ """Tests for the calculate_metrics function."""
+
+ def test_calculates_basic_metrics(self, tmp_path):
+ """Test calculation of basic metrics from results file."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ # Create a test results file
+ results_file = tmp_path / "results.jsonl"
+ results = [
+ {"is_correct": True, "processing_time": 1.5, "confidence": "90"},
+ {"is_correct": True, "processing_time": 2.0, "confidence": "85"},
+ {"is_correct": False, "processing_time": 1.0, "confidence": "70"},
+ ]
+ with open(results_file, "w") as f:
+ for r in results:
+ f.write(json.dumps(r) + "\n")
+
+ metrics = calculate_metrics(str(results_file))
+
+ assert metrics["total_examples"] == 3
+ assert metrics["graded_examples"] == 3
+ assert metrics["correct"] == 2
+ assert metrics["accuracy"] == 2 / 3
+ assert metrics["average_processing_time"] == 1.5
+ assert metrics["average_confidence"] == (90 + 85 + 70) / 3
+
+ def test_handles_empty_file(self, tmp_path):
+ """Test handling of empty results file."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ results_file = tmp_path / "empty.jsonl"
+ results_file.write_text("")
+
+ metrics = calculate_metrics(str(results_file))
+
+ assert "error" in metrics
+ assert metrics["error"] == "No results found"
+
+ def test_handles_missing_file(self, tmp_path):
+ """Test handling of missing results file."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ metrics = calculate_metrics(str(tmp_path / "nonexistent.jsonl"))
+
+ assert "error" in metrics
+
+ def test_calculates_error_rate(self, tmp_path):
+ """Test calculation of error rate."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ results_file = tmp_path / "results.jsonl"
+ results = [
+ {"is_correct": True},
+ {"error": "Some error occurred"},
+ {"is_correct": False},
+ ]
+ with open(results_file, "w") as f:
+ for r in results:
+ f.write(json.dumps(r) + "\n")
+
+ metrics = calculate_metrics(str(results_file))
+
+ assert metrics["error_count"] == 1
+ assert metrics["error_rate"] == 1 / 3
+
+ def test_calculates_per_category_metrics(self, tmp_path):
+ """Test calculation of per-category metrics."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ results_file = tmp_path / "results.jsonl"
+ results = [
+ {"is_correct": True, "category": "science"},
+ {"is_correct": False, "category": "science"},
+ {"is_correct": True, "category": "history"},
+ {"is_correct": True, "category": "history"},
+ ]
+ with open(results_file, "w") as f:
+ for r in results:
+ f.write(json.dumps(r) + "\n")
+
+ metrics = calculate_metrics(str(results_file))
+
+ assert "categories" in metrics
+ assert metrics["categories"]["science"]["total"] == 2
+ assert metrics["categories"]["science"]["correct"] == 1
+ assert metrics["categories"]["science"]["accuracy"] == 0.5
+ assert metrics["categories"]["history"]["total"] == 2
+ assert metrics["categories"]["history"]["correct"] == 2
+ assert metrics["categories"]["history"]["accuracy"] == 1.0
+
+ def test_handles_missing_confidence(self, tmp_path):
+ """Test handling of results without confidence values."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ results_file = tmp_path / "results.jsonl"
+ results = [
+ {"is_correct": True},
+ {"is_correct": False},
+ ]
+ with open(results_file, "w") as f:
+ for r in results:
+ f.write(json.dumps(r) + "\n")
+
+ metrics = calculate_metrics(str(results_file))
+
+ assert metrics["average_confidence"] == 0
+
+ def test_handles_invalid_confidence(self, tmp_path):
+ """Test handling of invalid confidence values."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ results_file = tmp_path / "results.jsonl"
+ results = [
+ {"is_correct": True, "confidence": "invalid"},
+ {"is_correct": True, "confidence": "80"},
+ ]
+ with open(results_file, "w") as f:
+ for r in results:
+ f.write(json.dumps(r) + "\n")
+
+ metrics = calculate_metrics(str(results_file))
+
+ # Should skip invalid and only use valid confidence
+ assert metrics["average_confidence"] == 80
+
+
+class TestCalculateCombinedScore:
+ """Tests for the calculate_combined_score function."""
+
+ def test_calculates_with_default_weights(self):
+ """Test combined score with default weights."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_combined_score,
+ )
+
+ metrics = {
+ "quality": {"quality_score": 0.8},
+ "speed": {"speed_score": 0.6},
+ "resource": {"resource_score": 0.9},
+ }
+
+ score = calculate_combined_score(metrics)
+
+ # Default weights: quality=0.6, speed=0.3, resource=0.1
+ expected = 0.8 * 0.6 + 0.6 * 0.3 + 0.9 * 0.1
+ assert abs(score - expected) < 0.001
+
+ def test_calculates_with_custom_weights(self):
+ """Test combined score with custom weights."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_combined_score,
+ )
+
+ metrics = {
+ "quality": {"quality_score": 1.0},
+ "speed": {"speed_score": 0.5},
+ "resource": {"resource_score": 0.0},
+ }
+ weights = {"quality": 0.5, "speed": 0.5, "resource": 0.0}
+
+ score = calculate_combined_score(metrics, weights)
+
+ expected = 1.0 * 0.5 + 0.5 * 0.5 + 0.0 * 0.0
+ assert abs(score - expected) < 0.001
+
+ def test_handles_missing_metrics(self):
+ """Test handling of missing metric categories."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_combined_score,
+ )
+
+ metrics = {
+ "quality": {"quality_score": 0.8},
+ # Missing speed and resource
+ }
+
+ score = calculate_combined_score(metrics)
+
+ # Should only count quality component
+ assert score > 0
+ assert score <= 1.0
+
+ def test_handles_zero_weights(self):
+ """Test handling of zero total weight."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_combined_score,
+ )
+
+ metrics = {
+ "quality": {"quality_score": 0.8},
+ }
+ weights = {"quality": 0, "speed": 0, "resource": 0}
+
+ score = calculate_combined_score(metrics, weights)
+
+ assert score == 0.0
+
+ def test_normalizes_weights(self):
+ """Test that weights are normalized."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_combined_score,
+ )
+
+ metrics = {
+ "quality": {"quality_score": 1.0},
+ "speed": {"speed_score": 1.0},
+ "resource": {"resource_score": 1.0},
+ }
+ # Weights that don't sum to 1
+ weights = {"quality": 2, "speed": 1, "resource": 1}
+
+ score = calculate_combined_score(metrics, weights)
+
+ # All scores are 1.0, so normalized result should be 1.0
+ assert abs(score - 1.0) < 0.001
+
+
+class TestCalculateResourceMetrics:
+ """Tests for the calculate_resource_metrics function."""
+
+ def test_calculates_resource_score(self):
+ """Test calculation of resource score."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_resource_metrics,
+ )
+
+ config = {
+ "iterations": 2,
+ "questions_per_iteration": 2,
+ "max_results": 50,
+ }
+
+ metrics = calculate_resource_metrics(config)
+
+ assert "resource_score" in metrics
+ assert "estimated_complexity" in metrics
+ assert 0 <= metrics["resource_score"] <= 1
+
+ def test_higher_complexity_lower_score(self):
+ """Test that higher complexity results in lower resource score."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_resource_metrics,
+ )
+
+ low_complexity_config = {
+ "iterations": 1,
+ "questions_per_iteration": 1,
+ "max_results": 25,
+ }
+ high_complexity_config = {
+ "iterations": 5,
+ "questions_per_iteration": 5,
+ "max_results": 100,
+ }
+
+ low_metrics = calculate_resource_metrics(low_complexity_config)
+ high_metrics = calculate_resource_metrics(high_complexity_config)
+
+ assert low_metrics["resource_score"] > high_metrics["resource_score"]
+ assert (
+ low_metrics["estimated_complexity"]
+ < high_metrics["estimated_complexity"]
+ )
+
+ def test_uses_default_values(self):
+ """Test that default values are used for missing config."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_resource_metrics,
+ )
+
+ empty_config = {}
+
+ metrics = calculate_resource_metrics(empty_config)
+
+ assert "resource_score" in metrics
+ assert metrics["resource_score"] > 0
diff --git a/tests/benchmarks/test_metrics_reporting.py b/tests/benchmarks/test_metrics_reporting.py
new file mode 100644
index 0000000000..e3bf4e7786
--- /dev/null
+++ b/tests/benchmarks/test_metrics_reporting.py
@@ -0,0 +1,397 @@
+"""
+Tests for benchmarks/metrics/reporting.py
+
+Tests cover:
+- generate_report function
+- Report formatting and structure
+"""
+
+import json
+from unittest.mock import patch
+
+
+class TestGenerateReport:
+ """Tests for the generate_report function."""
+
+ def test_generates_markdown_report(self, tmp_path):
+ """Test that a markdown report is generated."""
+ from local_deep_research.benchmarks.metrics.reporting import (
+ generate_report,
+ )
+
+ # Create a results file
+ results_file = tmp_path / "results.jsonl"
+ results = [
+ {
+ "is_correct": True,
+ "problem": "What is 2+2?",
+ "correct_answer": "4",
+ "extracted_answer": "4",
+ "reasoning": "Basic math",
+ },
+ {
+ "is_correct": False,
+ "problem": "What is the capital?",
+ "correct_answer": "Paris",
+ "extracted_answer": "London",
+ "reasoning": "Wrong answer",
+ },
+ ]
+ with open(results_file, "w") as f:
+ for r in results:
+ f.write(json.dumps(r) + "\n")
+
+ output_file = tmp_path / "report.md"
+ metrics = {
+ "total_examples": 2,
+ "graded_examples": 2,
+ "correct": 1,
+ "accuracy": 0.5,
+ }
+
+ with patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ ) as mock_write:
+ mock_write.return_value = None
+
+ generate_report(
+ metrics=metrics,
+ results_file=str(results_file),
+ output_file=str(output_file),
+ dataset_name="TestDataset",
+ )
+
+ # Check write was called
+ mock_write.assert_called_once()
+ written_content = mock_write.call_args[0][1]
+
+ # Check report structure
+ assert "# Evaluation Report: TestDataset" in written_content
+ assert "## Summary" in written_content
+ assert "**Total Examples**: 2" in written_content
+ assert "**Accuracy**: 0.500" in written_content
+
+ def test_includes_processing_time_when_available(self, tmp_path):
+ """Test that processing time is included when available."""
+ from local_deep_research.benchmarks.metrics.reporting import (
+ generate_report,
+ )
+
+ results_file = tmp_path / "results.jsonl"
+ results_file.write_text("")
+
+ metrics = {
+ "total_examples": 1,
+ "graded_examples": 1,
+ "correct": 1,
+ "accuracy": 1.0,
+ "average_processing_time": 5.25,
+ }
+
+ with patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ ) as mock_write:
+ generate_report(
+ metrics=metrics,
+ results_file=str(results_file),
+ output_file=str(tmp_path / "report.md"),
+ )
+
+ written_content = mock_write.call_args[0][1]
+ assert (
+ "**Average Processing Time**: 5.25 seconds" in written_content
+ )
+
+ def test_includes_confidence_when_available(self, tmp_path):
+ """Test that confidence is included when available."""
+ from local_deep_research.benchmarks.metrics.reporting import (
+ generate_report,
+ )
+
+ results_file = tmp_path / "results.jsonl"
+ results_file.write_text("")
+
+ metrics = {
+ "total_examples": 1,
+ "graded_examples": 1,
+ "correct": 1,
+ "accuracy": 1.0,
+ "average_confidence": 85.5,
+ }
+
+ with patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ ) as mock_write:
+ generate_report(
+ metrics=metrics,
+ results_file=str(results_file),
+ output_file=str(tmp_path / "report.md"),
+ )
+
+ written_content = mock_write.call_args[0][1]
+ assert "**Average Confidence**: 85.50%" in written_content
+
+ def test_includes_error_info_when_present(self, tmp_path):
+ """Test that error info is included when present."""
+ from local_deep_research.benchmarks.metrics.reporting import (
+ generate_report,
+ )
+
+ results_file = tmp_path / "results.jsonl"
+ results_file.write_text("")
+
+ metrics = {
+ "total_examples": 10,
+ "graded_examples": 8,
+ "correct": 6,
+ "accuracy": 0.75,
+ "error_count": 2,
+ "error_rate": 0.2,
+ }
+
+ with patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ ) as mock_write:
+ generate_report(
+ metrics=metrics,
+ results_file=str(results_file),
+ output_file=str(tmp_path / "report.md"),
+ )
+
+ written_content = mock_write.call_args[0][1]
+ assert "**Error Count**: 2" in written_content
+ assert "**Error Rate**: 0.200" in written_content
+
+ def test_includes_category_performance(self, tmp_path):
+ """Test that category performance is included."""
+ from local_deep_research.benchmarks.metrics.reporting import (
+ generate_report,
+ )
+
+ results_file = tmp_path / "results.jsonl"
+ results_file.write_text("")
+
+ metrics = {
+ "total_examples": 4,
+ "graded_examples": 4,
+ "correct": 3,
+ "accuracy": 0.75,
+ "categories": {
+ "science": {"total": 2, "correct": 2, "accuracy": 1.0},
+ "history": {"total": 2, "correct": 1, "accuracy": 0.5},
+ },
+ }
+
+ with patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ ) as mock_write:
+ generate_report(
+ metrics=metrics,
+ results_file=str(results_file),
+ output_file=str(tmp_path / "report.md"),
+ )
+
+ written_content = mock_write.call_args[0][1]
+ assert "## Category Performance" in written_content
+ assert "### science" in written_content
+ assert "### history" in written_content
+
+ def test_includes_config_info(self, tmp_path):
+ """Test that config info is included when provided."""
+ from local_deep_research.benchmarks.metrics.reporting import (
+ generate_report,
+ )
+
+ results_file = tmp_path / "results.jsonl"
+ results_file.write_text("")
+
+ metrics = {
+ "total_examples": 1,
+ "graded_examples": 1,
+ "correct": 1,
+ "accuracy": 1.0,
+ }
+
+ config_info = {
+ "model": "gpt-4",
+ "temperature": 0.0,
+ }
+
+ with patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ ) as mock_write:
+ generate_report(
+ metrics=metrics,
+ results_file=str(results_file),
+ output_file=str(tmp_path / "report.md"),
+ config_info=config_info,
+ )
+
+ written_content = mock_write.call_args[0][1]
+ assert "## Configuration" in written_content
+ assert "**model**: gpt-4" in written_content
+ assert "**temperature**: 0.0" in written_content
+
+ def test_includes_correct_examples(self, tmp_path):
+ """Test that correct examples are included."""
+ from local_deep_research.benchmarks.metrics.reporting import (
+ generate_report,
+ )
+
+ results_file = tmp_path / "results.jsonl"
+ results = [
+ {
+ "is_correct": True,
+ "problem": "Test question?",
+ "correct_answer": "Answer",
+ "extracted_answer": "Answer",
+ "reasoning": "Correct reasoning",
+ }
+ ]
+ with open(results_file, "w") as f:
+ for r in results:
+ f.write(json.dumps(r) + "\n")
+
+ metrics = {
+ "total_examples": 1,
+ "graded_examples": 1,
+ "correct": 1,
+ "accuracy": 1.0,
+ }
+
+ with patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ ) as mock_write:
+ generate_report(
+ metrics=metrics,
+ results_file=str(results_file),
+ output_file=str(tmp_path / "report.md"),
+ )
+
+ written_content = mock_write.call_args[0][1]
+ assert "## Example Correct Answers" in written_content
+ assert "Test question?" in written_content
+
+ def test_includes_incorrect_examples(self, tmp_path):
+ """Test that incorrect examples are included."""
+ from local_deep_research.benchmarks.metrics.reporting import (
+ generate_report,
+ )
+
+ results_file = tmp_path / "results.jsonl"
+ results = [
+ {
+ "is_correct": False,
+ "problem": "Wrong question?",
+ "correct_answer": "Right",
+ "extracted_answer": "Wrong",
+ "reasoning": "Bad reasoning",
+ }
+ ]
+ with open(results_file, "w") as f:
+ for r in results:
+ f.write(json.dumps(r) + "\n")
+
+ metrics = {
+ "total_examples": 1,
+ "graded_examples": 1,
+ "correct": 0,
+ "accuracy": 0.0,
+ }
+
+ with patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ ) as mock_write:
+ generate_report(
+ metrics=metrics,
+ results_file=str(results_file),
+ output_file=str(tmp_path / "report.md"),
+ )
+
+ written_content = mock_write.call_args[0][1]
+ assert "## Example Incorrect Answers" in written_content
+ assert "Wrong question?" in written_content
+
+ def test_handles_missing_results_file(self, tmp_path):
+ """Test handling of missing results file."""
+ from local_deep_research.benchmarks.metrics.reporting import (
+ generate_report,
+ )
+
+ metrics = {
+ "total_examples": 0,
+ "graded_examples": 0,
+ "correct": 0,
+ "accuracy": 0.0,
+ }
+
+ with patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ ) as mock_write:
+ # Should not raise even with missing file
+ generate_report(
+ metrics=metrics,
+ results_file=str(tmp_path / "nonexistent.jsonl"),
+ output_file=str(tmp_path / "report.md"),
+ )
+
+ mock_write.assert_called_once()
+
+ def test_includes_metadata_section(self, tmp_path):
+ """Test that metadata section is included."""
+ from local_deep_research.benchmarks.metrics.reporting import (
+ generate_report,
+ )
+
+ results_file = tmp_path / "results.jsonl"
+ results_file.write_text("")
+
+ metrics = {
+ "total_examples": 1,
+ "graded_examples": 1,
+ "correct": 1,
+ "accuracy": 1.0,
+ }
+
+ with patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ ) as mock_write:
+ generate_report(
+ metrics=metrics,
+ results_file=str(results_file),
+ output_file=str(tmp_path / "report.md"),
+ dataset_name="TestDataset",
+ )
+
+ written_content = mock_write.call_args[0][1]
+ assert "## Metadata" in written_content
+ assert "**Generated**:" in written_content
+ assert "**Dataset**: TestDataset" in written_content
+
+ def test_returns_output_file_path(self, tmp_path):
+ """Test that output file path is returned."""
+ from local_deep_research.benchmarks.metrics.reporting import (
+ generate_report,
+ )
+
+ results_file = tmp_path / "results.jsonl"
+ results_file.write_text("")
+ output_file = str(tmp_path / "report.md")
+
+ metrics = {
+ "total_examples": 0,
+ "graded_examples": 0,
+ "correct": 0,
+ "accuracy": 0.0,
+ }
+
+ with patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ ):
+ result = generate_report(
+ metrics=metrics,
+ results_file=str(results_file),
+ output_file=output_file,
+ )
+
+ assert result == output_file