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 253 high-value tests across 10 under-tested modules (round 4) (#2541)

LearningCircuitf6062ff1ae07
diff --git a/tests/advanced_search_system/constraints/test_constraint_analyzer_high_value.py b/tests/advanced_search_system/constraints/test_constraint_analyzer_high_value.py
new file mode 100644
index 0000000000..5a6fb0a1e0
--- /dev/null
+++ b/tests/advanced_search_system/constraints/test_constraint_analyzer_high_value.py
@@ -0,0 +1,257 @@
+"""High-value tests for constraint_analyzer.py.
+
+Covers edge cases and error paths:
+- Model output parsing with unusual formatting
+- Constraint parsing with multi-colon values
+- Weight parsing boundary conditions
+- Empty / whitespace-only model outputs
+- Constraint type fallback behavior
+"""
+
+from unittest.mock import Mock
+
+
+from local_deep_research.advanced_search_system.constraints.constraint_analyzer import (
+ ConstraintAnalyzer,
+)
+from local_deep_research.advanced_search_system.constraints.base_constraint import (
+ ConstraintType,
+)
+
+
+class TestExtractConstraintsEdgeCases:
+ """Edge-case tests for extract_constraints."""
+
+ def test_response_with_only_whitespace(self):
+ """Whitespace-only model output should yield zero constraints."""
+ mock_model = Mock()
+ mock_model.invoke.return_value = Mock(content=" \n\n \t ")
+ analyzer = ConstraintAnalyzer(mock_model)
+
+ constraints = analyzer.extract_constraints("What year?")
+ assert constraints == []
+
+ def test_response_with_no_constraint_markers(self):
+ """Free-form text without CONSTRAINT_ headers should yield zero constraints."""
+ mock_model = Mock()
+ mock_model.invoke.return_value = Mock(
+ content="Here are some thoughts about the question. No structure here."
+ )
+ analyzer = ConstraintAnalyzer(mock_model)
+
+ constraints = analyzer.extract_constraints("What year?")
+ assert constraints == []
+
+ def test_constraint_value_containing_colons(self):
+ """Values that themselves contain colons should be parsed correctly."""
+ mock_model = Mock()
+ mock_model.invoke.return_value = Mock(
+ content="""\
+CONSTRAINT_1:
+Type: temporal
+Description: The event happened at a specific time
+Value: Time: 3:45 PM on January 1st
+Weight: 0.9
+"""
+ )
+ analyzer = ConstraintAnalyzer(mock_model)
+ constraints = analyzer.extract_constraints("When did it happen?")
+
+ assert len(constraints) == 1
+ assert "3:45 PM" in constraints[0].value
+
+ def test_single_constraint_without_trailing_newline(self):
+ """A single constraint with no trailing newline should still be captured."""
+ mock_model = Mock()
+ mock_model.invoke.return_value = Mock(
+ content="CONSTRAINT_1:\nType: location\nDescription: Located in Europe\nValue: Europe\nWeight: 0.6"
+ )
+ analyzer = ConstraintAnalyzer(mock_model)
+ constraints = analyzer.extract_constraints("Where is it?")
+
+ assert len(constraints) == 1
+ assert constraints[0].type == ConstraintType.LOCATION
+ assert constraints[0].weight == 0.6
+
+ def test_three_constraints_ids_sequential(self):
+ """Three constraints should get sequential IDs c1, c2, c3."""
+ mock_model = Mock()
+ mock_model.invoke.return_value = Mock(
+ content="""\
+CONSTRAINT_1:
+Type: property
+Description: A
+Value: a
+
+CONSTRAINT_2:
+Type: event
+Description: B
+Value: b
+
+CONSTRAINT_3:
+Type: temporal
+Description: C
+Value: c
+"""
+ )
+ analyzer = ConstraintAnalyzer(mock_model)
+ constraints = analyzer.extract_constraints("Test")
+
+ assert len(constraints) == 3
+ assert [c.id for c in constraints] == ["c1", "c2", "c3"]
+
+ def test_constraint_with_think_tags(self):
+ """Think tags wrapping constraint content should be stripped."""
+ mock_model = Mock()
+ mock_model.invoke.return_value = Mock(
+ content="""\
+<think>
+I need to create constraints for this query...
+</think>
+CONSTRAINT_1:
+Type: comparison
+Description: Must be greater than 100
+Value: > 100
+Weight: 0.95
+"""
+ )
+ analyzer = ConstraintAnalyzer(mock_model)
+ constraints = analyzer.extract_constraints("Which has more than 100?")
+
+ assert len(constraints) == 1
+ assert constraints[0].type == ConstraintType.COMPARISON
+
+ def test_mixed_valid_and_invalid_blocks(self):
+ """Mix of valid and invalid constraint blocks."""
+ mock_model = Mock()
+ mock_model.invoke.return_value = Mock(
+ content="""\
+CONSTRAINT_1:
+Type: property
+Description: Valid first
+Value: first value
+Weight: 0.8
+
+CONSTRAINT_2:
+Type: property
+
+CONSTRAINT_3:
+Type: existence
+Description: Valid third
+Value: exists
+Weight: 0.5
+"""
+ )
+ analyzer = ConstraintAnalyzer(mock_model)
+ constraints = analyzer.extract_constraints("Test")
+
+ assert len(constraints) == 2
+ assert constraints[0].description == "Valid first"
+ assert constraints[1].description == "Valid third"
+
+ def test_model_invocation_passes_query_in_prompt(self):
+ """The query text should appear in the prompt sent to the model."""
+ mock_model = Mock()
+ mock_model.invoke.return_value = Mock(content="")
+ analyzer = ConstraintAnalyzer(mock_model)
+
+ specific_query = "What is the tallest mountain in Antarctica?"
+ analyzer.extract_constraints(specific_query)
+
+ call_args = mock_model.invoke.call_args[0][0]
+ assert specific_query in call_args
+
+
+class TestParseWeightBoundaryConditions:
+ """Boundary and edge-case tests for _parse_weight."""
+
+ def test_weight_zero_integer(self):
+ analyzer = ConstraintAnalyzer(Mock())
+ assert analyzer._parse_weight(0) == 0.0
+
+ def test_weight_zero_float(self):
+ analyzer = ConstraintAnalyzer(Mock())
+ assert analyzer._parse_weight(0.0) == 0.0
+
+ def test_weight_zero_string(self):
+ analyzer = ConstraintAnalyzer(Mock())
+ assert analyzer._parse_weight("0") == 0.0
+
+ def test_weight_greater_than_one(self):
+ """Weight > 1.0 should be returned as-is (no clamping)."""
+ analyzer = ConstraintAnalyzer(Mock())
+ assert analyzer._parse_weight(5.0) == 5.0
+
+ def test_weight_negative_float(self):
+ """Negative float weight should be returned as-is."""
+ analyzer = ConstraintAnalyzer(Mock())
+ assert analyzer._parse_weight(-0.5) == -0.5
+
+ def test_weight_string_with_leading_text(self):
+ """String with leading text before the number."""
+ analyzer = ConstraintAnalyzer(Mock())
+ result = analyzer._parse_weight("approximately 0.85")
+ assert result == 0.85
+
+ def test_weight_string_integer_only(self):
+ """String containing only an integer (no decimal)."""
+ analyzer = ConstraintAnalyzer(Mock())
+ result = analyzer._parse_weight("1")
+ assert result == 1.0
+
+ def test_weight_none_returns_default(self):
+ """None value should return default 1.0."""
+ analyzer = ConstraintAnalyzer(Mock())
+ result = analyzer._parse_weight(None)
+ assert result == 1.0
+
+ def test_weight_list_returns_default(self):
+ """Non-numeric, non-string type returns default."""
+ analyzer = ConstraintAnalyzer(Mock())
+ result = analyzer._parse_weight([0.5])
+ assert result == 1.0
+
+ def test_weight_bool_true(self):
+ """Boolean True is an int subclass, should return 1.0."""
+ analyzer = ConstraintAnalyzer(Mock())
+ result = analyzer._parse_weight(True)
+ assert result == 1.0
+
+ def test_weight_bool_false(self):
+ """Boolean False is an int subclass, should return 0.0."""
+ analyzer = ConstraintAnalyzer(Mock())
+ result = analyzer._parse_weight(False)
+ assert result == 0.0
+
+
+class TestParseConstraintTypeEdgeCases:
+ """Edge-case tests for _parse_constraint_type."""
+
+ def test_empty_string_defaults_to_property(self):
+ """Empty string type defaults to PROPERTY."""
+ analyzer = ConstraintAnalyzer(Mock())
+ assert analyzer._parse_constraint_type("") == ConstraintType.PROPERTY
+
+ def test_all_valid_types_case_insensitive(self):
+ """All constraint types should parse correctly in mixed case."""
+ analyzer = ConstraintAnalyzer(Mock())
+ expected_map = {
+ "property": ConstraintType.PROPERTY,
+ "name_pattern": ConstraintType.NAME_PATTERN,
+ "event": ConstraintType.EVENT,
+ "statistic": ConstraintType.STATISTIC,
+ "temporal": ConstraintType.TEMPORAL,
+ "location": ConstraintType.LOCATION,
+ "comparison": ConstraintType.COMPARISON,
+ "existence": ConstraintType.EXISTENCE,
+ }
+ for input_str, expected_type in expected_map.items():
+ assert analyzer._parse_constraint_type(input_str) == expected_type
+
+ def test_unknown_type_defaults_to_property(self):
+ """Unknown type string defaults to PROPERTY."""
+ analyzer = ConstraintAnalyzer(Mock())
+ assert (
+ analyzer._parse_constraint_type("unknown_type")
+ == ConstraintType.PROPERTY
+ )
diff --git a/tests/benchmarks/test_benchmark_commands_high_value.py b/tests/benchmarks/test_benchmark_commands_high_value.py
new file mode 100644
index 0000000000..9c149c2ada
--- /dev/null
+++ b/tests/benchmarks/test_benchmark_commands_high_value.py
@@ -0,0 +1,480 @@
+"""High-value tests for benchmarks/cli/benchmark_commands.py.
+
+Covers CLI output formatting, compare_configs_cli, main() verbose logging,
+argument parsing edge cases, and search/eval config building.
+"""
+
+import argparse
+import sys
+from unittest.mock import patch
+
+import pytest
+
+
+def mock_data_directory(tmp_path):
+ """Mock get_data_directory so module-level default paths use tmp_path."""
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.get_data_directory"
+ ) as mock:
+ mock.return_value = tmp_path
+ yield tmp_path
+
+
+def _make_args(**overrides):
+ """Build a minimal argparse.Namespace with sane defaults."""
+ defaults = dict(
+ examples=10,
+ iterations=3,
+ questions=2,
+ search_tool="searxng",
+ output_dir="/tmp/test_output",
+ human_eval=False,
+ no_eval=False,
+ custom_dataset=None,
+ eval_model=None,
+ eval_provider=None,
+ search_model=None,
+ search_provider=None,
+ endpoint_url=None,
+ search_strategy="source_based",
+ )
+ defaults.update(overrides)
+ return argparse.Namespace(**defaults)
+
+
+class TestSimpleqaCliOutput:
+ """Tests for run_simpleqa_cli output formatting paths."""
+
+ def test_prints_metrics_when_present(self, mock_data_directory, capsys):
+ """When result contains 'metrics', summary stats are printed."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ run_simpleqa_cli,
+ )
+
+ args = _make_args()
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.run_simpleqa_benchmark"
+ ) as mock_bench:
+ mock_bench.return_value = {
+ "metrics": {
+ "accuracy": 0.85,
+ "correct": 17,
+ "average_processing_time": 4.321,
+ },
+ "total_examples": 20,
+ "report_path": "/tmp/report.html",
+ }
+ run_simpleqa_cli(args)
+
+ out = capsys.readouterr().out
+ assert "SimpleQA Benchmark Results:" in out
+ assert "0.850" in out
+ assert "17" in out
+
+ def test_prints_no_eval_message_when_no_metrics(
+ self, mock_data_directory, capsys
+ ):
+ """When result has no 'metrics' key, no-eval summary is printed."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ run_simpleqa_cli,
+ )
+
+ args = _make_args()
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.run_simpleqa_benchmark"
+ ) as mock_bench:
+ mock_bench.return_value = {
+ "total_examples": 20,
+ "results_path": "/tmp/results.json",
+ }
+ run_simpleqa_cli(args)
+
+ out = capsys.readouterr().out
+ assert "Completed (no evaluation)" in out
+ assert "20" in out
+
+ def test_report_path_na_when_missing(self, mock_data_directory, capsys):
+ """report_path defaults to N/A when not in result dict."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ run_simpleqa_cli,
+ )
+
+ args = _make_args()
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.run_simpleqa_benchmark"
+ ) as mock_bench:
+ mock_bench.return_value = {
+ "metrics": {
+ "accuracy": 0,
+ "correct": 0,
+ "average_processing_time": 0,
+ },
+ "total_examples": 0,
+ }
+ run_simpleqa_cli(args)
+
+ out = capsys.readouterr().out
+ assert "N/A" in out
+
+
+class TestBrowsecompCliOutput:
+ """Tests for run_browsecomp_cli output formatting paths."""
+
+ def test_prints_metrics_when_present(self, mock_data_directory, capsys):
+ """BrowseComp prints metrics summary when result has 'metrics'."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ run_browsecomp_cli,
+ )
+
+ args = _make_args()
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.run_browsecomp_benchmark"
+ ) as mock_bench:
+ mock_bench.return_value = {
+ "metrics": {
+ "accuracy": 0.6,
+ "correct": 6,
+ "average_processing_time": 12.5,
+ },
+ "total_examples": 10,
+ "report_path": "/tmp/browsecomp_report.html",
+ }
+ run_browsecomp_cli(args)
+
+ out = capsys.readouterr().out
+ assert "BrowseComp Benchmark Results:" in out
+ assert "0.600" in out
+
+ def test_prints_no_eval_message_when_no_metrics(
+ self, mock_data_directory, capsys
+ ):
+ """BrowseComp prints no-eval message when result has no 'metrics'."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ run_browsecomp_cli,
+ )
+
+ args = _make_args()
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.run_browsecomp_benchmark"
+ ) as mock_bench:
+ mock_bench.return_value = {
+ "total_examples": 10,
+ "results_path": "/tmp/browse_results.json",
+ }
+ run_browsecomp_cli(args)
+
+ out = capsys.readouterr().out
+ assert "BrowseComp Benchmark Completed (no evaluation)" in out
+
+ def test_browsecomp_endpoint_url_in_search_config(
+ self, mock_data_directory
+ ):
+ """endpoint_url is mapped to openai_endpoint_url in search_config."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ run_browsecomp_cli,
+ )
+
+ args = _make_args(endpoint_url="https://api.example.com/v1")
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.run_browsecomp_benchmark"
+ ) as mock_bench:
+ mock_bench.return_value = {"total_examples": 1}
+ run_browsecomp_cli(args)
+ kw = mock_bench.call_args[1]
+ assert (
+ kw["search_config"]["openai_endpoint_url"]
+ == "https://api.example.com/v1"
+ )
+
+
+class TestSearchConfigEdgeCases:
+ """Test search config building for uncommon attribute combinations."""
+
+ def test_endpoint_url_added_to_simpleqa_search_config(
+ self, mock_data_directory
+ ):
+ """endpoint_url maps to openai_endpoint_url in SimpleQA search config."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ run_simpleqa_cli,
+ )
+
+ args = _make_args(endpoint_url="https://openrouter.ai/api/v1")
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.run_simpleqa_benchmark"
+ ) as mock_bench:
+ mock_bench.return_value = {"total_examples": 1}
+ run_simpleqa_cli(args)
+ kw = mock_bench.call_args[1]
+ assert (
+ kw["search_config"]["openai_endpoint_url"]
+ == "https://openrouter.ai/api/v1"
+ )
+
+ def test_no_eval_flag_passed_as_run_evaluation_false(
+ self, mock_data_directory
+ ):
+ """--no-eval sets run_evaluation=False in benchmark call."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ run_simpleqa_cli,
+ )
+
+ args = _make_args(no_eval=True)
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.run_simpleqa_benchmark"
+ ) as mock_bench:
+ mock_bench.return_value = {"total_examples": 1}
+ run_simpleqa_cli(args)
+ kw = mock_bench.call_args[1]
+ assert kw["run_evaluation"] is False
+
+ def test_human_eval_flag_passed_through(self, mock_data_directory):
+ """--human-eval flag is forwarded as human_evaluation=True."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ run_simpleqa_cli,
+ )
+
+ args = _make_args(human_eval=True)
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.run_simpleqa_benchmark"
+ ) as mock_bench:
+ mock_bench.return_value = {"total_examples": 1}
+ run_simpleqa_cli(args)
+ kw = mock_bench.call_args[1]
+ assert kw["human_evaluation"] is True
+
+ def test_eval_config_only_model_no_provider(self, mock_data_directory):
+ """eval_model alone creates evaluation_config with only model_name."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ run_simpleqa_cli,
+ )
+
+ args = _make_args(eval_model="claude-3")
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.run_simpleqa_benchmark"
+ ) as mock_bench:
+ mock_bench.return_value = {"total_examples": 1}
+ run_simpleqa_cli(args)
+ kw = mock_bench.call_args[1]
+ assert kw["evaluation_config"] == {"model_name": "claude-3"}
+
+
+class TestCompareConfigsCli:
+ """Tests for compare_configs_cli."""
+
+ def test_compare_calls_compare_configurations(self, mock_data_directory):
+ """compare_configs_cli delegates to compare_configurations."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ compare_configs_cli,
+ )
+
+ args = argparse.Namespace(
+ dataset="simpleqa", examples=20, output_dir="/tmp/compare"
+ )
+ with patch(
+ "local_deep_research.api.benchmark_functions.compare_configurations"
+ ) as mock_cmp:
+ mock_cmp.return_value = {
+ "configurations_tested": 2,
+ "report_path": "/tmp/compare/report.html",
+ "results": [
+ {
+ "configuration_name": "baseline",
+ "metrics": {
+ "accuracy": 0.8,
+ "average_processing_time": 3.0,
+ },
+ },
+ ],
+ }
+ compare_configs_cli(args)
+ mock_cmp.assert_called_once_with(
+ dataset_type="simpleqa",
+ num_examples=20,
+ output_dir="/tmp/compare",
+ )
+
+ def test_compare_prints_summary_table(self, mock_data_directory, capsys):
+ """compare_configs_cli prints a comparison table to stdout."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ compare_configs_cli,
+ )
+
+ args = argparse.Namespace(
+ dataset="browsecomp", examples=5, output_dir="/tmp/compare"
+ )
+ with patch(
+ "local_deep_research.api.benchmark_functions.compare_configurations"
+ ) as mock_cmp:
+ mock_cmp.return_value = {
+ "configurations_tested": 1,
+ "report_path": "/tmp/compare/report.html",
+ "results": [
+ {
+ "configuration_name": "default",
+ "metrics": {
+ "accuracy": 0.75,
+ "average_processing_time": 5.55,
+ },
+ },
+ ],
+ }
+ compare_configs_cli(args)
+
+ out = capsys.readouterr().out
+ assert "Configuration Comparison Results:" in out
+ assert "default" in out
+ assert "0.750" in out
+
+
+class TestMainEntryPoint:
+ """Tests for the main() entry point."""
+
+ def test_main_verbose_flag_sets_debug(self, mock_data_directory):
+ """--verbose adds DEBUG-level loguru handler."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import main
+
+ with patch.object(sys, "argv", ["ldr-benchmark", "--verbose", "list"]):
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.get_available_datasets"
+ ) as mock_ds:
+ mock_ds.return_value = []
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.logger"
+ ) as mock_logger:
+ main()
+ mock_logger.add.assert_called_once()
+ _, kwargs = mock_logger.add.call_args
+ assert kwargs.get("level") == "DEBUG"
+
+ def test_main_no_verbose_sets_info(self, mock_data_directory):
+ """Without --verbose, loguru handler uses INFO level."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import main
+
+ with patch.object(sys, "argv", ["ldr-benchmark", "list"]):
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.get_available_datasets"
+ ) as mock_ds:
+ mock_ds.return_value = []
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.logger"
+ ) as mock_logger:
+ main()
+ mock_logger.add.assert_called_once()
+ _, kwargs = mock_logger.add.call_args
+ assert kwargs.get("level") == "INFO"
+
+
+class TestArgumentParsingEdgeCases:
+ """Test edge cases in argument parsing."""
+
+ def test_all_search_strategies_accepted(self, mock_data_directory):
+ """All five strategy choices parse without error."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ setup_benchmark_parser,
+ )
+
+ parser = argparse.ArgumentParser()
+ subparsers = parser.add_subparsers(dest="command")
+ setup_benchmark_parser(subparsers)
+
+ for strategy in [
+ "source_based",
+ "standard",
+ "rapid",
+ "parallel",
+ "iterdrag",
+ ]:
+ args = parser.parse_args(
+ ["simpleqa", "--search-strategy", strategy]
+ )
+ assert args.search_strategy == strategy
+
+ def test_eval_model_and_provider_options(self, mock_data_directory):
+ """--eval-model and --eval-provider parse correctly."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ setup_benchmark_parser,
+ )
+
+ parser = argparse.ArgumentParser()
+ subparsers = parser.add_subparsers(dest="command")
+ setup_benchmark_parser(subparsers)
+
+ args = parser.parse_args(
+ [
+ "browsecomp",
+ "--eval-model",
+ "gpt-4o",
+ "--eval-provider",
+ "openai",
+ ]
+ )
+ assert args.eval_model == "gpt-4o"
+ assert args.eval_provider == "openai"
+
+ def test_custom_dataset_path_parsed(self, mock_data_directory):
+ """--custom-dataset stores the given path."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ setup_benchmark_parser,
+ )
+
+ parser = argparse.ArgumentParser()
+ subparsers = parser.add_subparsers(dest="command")
+ setup_benchmark_parser(subparsers)
+
+ args = parser.parse_args(
+ ["simpleqa", "--custom-dataset", "/data/my_dataset.jsonl"]
+ )
+ assert args.custom_dataset == "/data/my_dataset.jsonl"
+
+
+class TestListBenchmarksEdgeCases:
+ """Edge cases for list_benchmarks_cli."""
+
+ def test_empty_datasets_list(self, mock_data_directory, capsys):
+ """Empty datasets list prints header but no dataset entries."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ list_benchmarks_cli,
+ )
+
+ args = argparse.Namespace()
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.get_available_datasets"
+ ) as mock_ds:
+ mock_ds.return_value = []
+ list_benchmarks_cli(args)
+
+ out = capsys.readouterr().out
+ assert "Available Benchmarks:" in out
+
+ def test_multiple_datasets_all_printed(self, mock_data_directory, capsys):
+ """Multiple datasets are each printed with id, name, description, url."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ list_benchmarks_cli,
+ )
+
+ args = argparse.Namespace()
+ datasets = [
+ {
+ "id": "simpleqa",
+ "name": "SimpleQA",
+ "description": "Basic QA",
+ "url": "https://example.com/simpleqa",
+ },
+ {
+ "id": "browsecomp",
+ "name": "BrowseComp",
+ "description": "Browsing comprehension",
+ "url": "https://example.com/browsecomp",
+ },
+ ]
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.get_available_datasets"
+ ) as mock_ds:
+ mock_ds.return_value = datasets
+ list_benchmarks_cli(args)
+
+ out = capsys.readouterr().out
+ for ds in datasets:
+ assert ds["id"] in out
+ assert ds["name"] in out
diff --git a/tests/benchmarks/test_reporting_high_value.py b/tests/benchmarks/test_reporting_high_value.py
new file mode 100644
index 0000000000..9578b2481a
--- /dev/null
+++ b/tests/benchmarks/test_reporting_high_value.py
@@ -0,0 +1,331 @@
+"""High-value tests for benchmarks/metrics/reporting.py.
+
+Covers report generation, empty/null data handling, category metrics,
+config info inclusion, and file I/O error paths.
+"""
+
+import json
+
+from unittest.mock import patch
+
+
+class TestGenerateReport:
+ """Tests for generate_report function."""
+
+ def test_basic_report_generation(self, tmp_path):
+ """Basic report generates with minimal metrics."""
+ 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": 10,
+ "graded_examples": 10,
+ "correct": 8,
+ "accuracy": 0.8,
+ }
+
+ with patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ ) as mock_write:
+ result = generate_report(
+ metrics=metrics,
+ results_file=str(results_file),
+ output_file=output_file,
+ dataset_name="TestDataset",
+ )
+
+ assert result == output_file
+ mock_write.assert_called_once()
+ content = mock_write.call_args[0][1]
+ assert "TestDataset" in content
+ assert "0.800" in content
+ assert "8" in content
+
+ def test_report_with_processing_time(self, tmp_path):
+ """Report includes average processing time 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": 5,
+ "graded_examples": 5,
+ "correct": 3,
+ "accuracy": 0.6,
+ "average_processing_time": 12.345,
+ }
+
+ 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"),
+ )
+ content = mock_write.call_args[0][1]
+ assert "12.35" in content
+
+ def test_report_with_error_count(self, tmp_path):
+ """Report includes error stats when error_count > 0."""
+ 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"),
+ )
+ content = mock_write.call_args[0][1]
+ assert "Error Count" in content
+ assert "Error Rate" in content
+
+ def test_report_with_categories(self, tmp_path):
+ """Report includes per-category metrics."""
+ 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": 10,
+ "correct": 7,
+ "accuracy": 0.7,
+ "categories": {
+ "Science": {"total": 5, "correct": 4, "accuracy": 0.8},
+ "History": {"total": 5, "correct": 3, "accuracy": 0.6},
+ },
+ }
+
+ 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"),
+ )
+ content = mock_write.call_args[0][1]
+ assert "Science" in content
+ assert "History" in content
+ assert "0.800" in content
+
+ def test_report_with_config_info(self, tmp_path):
+ """Report includes configuration info 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,
+ }
+
+ 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={"model": "gpt-4", "strategy": "rapid"},
+ )
+ content = mock_write.call_args[0][1]
+ assert "Configuration" in content
+ assert "gpt-4" in content
+ assert "rapid" in content
+
+ def test_report_with_correct_examples(self, tmp_path):
+ """Report includes correct answer examples from results file."""
+ from local_deep_research.benchmarks.metrics.reporting import (
+ generate_report,
+ )
+
+ results_file = tmp_path / "results.jsonl"
+ results = [
+ {
+ "problem": "What is 2+2?",
+ "correct_answer": "4",
+ "extracted_answer": "4",
+ "is_correct": True,
+ },
+ ]
+ results_file.write_text("\n".join(json.dumps(r) for r in results))
+
+ 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"),
+ )
+ content = mock_write.call_args[0][1]
+ assert "Example Correct Answers" in content
+ assert "What is 2+2?" in content
+
+ def test_report_with_incorrect_examples(self, tmp_path):
+ """Report includes incorrect answer examples."""
+ from local_deep_research.benchmarks.metrics.reporting import (
+ generate_report,
+ )
+
+ results_file = tmp_path / "results.jsonl"
+ results = [
+ {
+ "problem": "Capital of France?",
+ "correct_answer": "Paris",
+ "extracted_answer": "London",
+ "is_correct": False,
+ },
+ ]
+ results_file.write_text("\n".join(json.dumps(r) for r in results))
+
+ 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"),
+ )
+ content = mock_write.call_args[0][1]
+ assert "Example Incorrect Answers" in content
+ assert "Capital of France?" in content
+
+ def test_report_handles_missing_results_file(self, tmp_path):
+ """Missing results file doesn't crash report generation."""
+ 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:
+ result = generate_report(
+ metrics=metrics,
+ results_file="/nonexistent/path/results.jsonl",
+ output_file=str(tmp_path / "report.md"),
+ )
+ assert result == str(tmp_path / "report.md")
+ mock_write.assert_called_once()
+
+ def test_report_limits_examples_to_five(self, tmp_path):
+ """Report limits correct/incorrect examples to 5 each."""
+ from local_deep_research.benchmarks.metrics.reporting import (
+ generate_report,
+ )
+
+ results_file = tmp_path / "results.jsonl"
+ results = [
+ {
+ "problem": f"Q{i}?",
+ "correct_answer": f"A{i}",
+ "extracted_answer": f"A{i}",
+ "is_correct": True,
+ }
+ for i in range(10)
+ ]
+ results_file.write_text("\n".join(json.dumps(r) for r in results))
+
+ metrics = {
+ "total_examples": 10,
+ "graded_examples": 10,
+ "correct": 10,
+ "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"),
+ )
+ content = mock_write.call_args[0][1]
+ # Should have exactly 5 "Example N" entries
+ assert content.count("### Example") == 5
+
+ def test_report_includes_metadata_timestamp(self, tmp_path):
+ """Report includes metadata section with timestamp."""
+ from local_deep_research.benchmarks.metrics.reporting import (
+ generate_report,
+ )
+
+ results_file = tmp_path / "results.jsonl"
+ results_file.write_text("")
+
+ 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:
+ generate_report(
+ metrics=metrics,
+ results_file=str(results_file),
+ output_file=str(tmp_path / "report.md"),
+ dataset_name="TestDS",
+ )
+ content = mock_write.call_args[0][1]
+ assert "Metadata" in content
+ assert "Generated" in content
+ assert "TestDS" in content
diff --git a/tests/benchmarks/test_visualization_high_value.py b/tests/benchmarks/test_visualization_high_value.py
new file mode 100644
index 0000000000..9b429d0529
--- /dev/null
+++ b/tests/benchmarks/test_visualization_high_value.py
@@ -0,0 +1,227 @@
+"""High-value tests for benchmarks/metrics/visualization.py.
+
+Covers matplotlib unavailable path, figure creation, file saving,
+Pareto frontier edge cases, and parameter importance sorting.
+"""
+
+import pytest
+from unittest.mock import patch
+
+
+class TestPlotOptimizationHistory:
+ """Tests for plot_optimization_history."""
+
+ def test_returns_none_when_matplotlib_unavailable(self):
+ """Returns None when MATPLOTLIB_AVAILABLE is False."""
+ with patch(
+ "local_deep_research.benchmarks.metrics.visualization.MATPLOTLIB_AVAILABLE",
+ False,
+ ):
+ from local_deep_research.benchmarks.metrics.visualization import (
+ plot_optimization_history,
+ )
+
+ result = plot_optimization_history([0.5, 0.6], [0.5, 0.6])
+ assert result is None
+
+ def test_returns_figure_with_valid_data(self):
+ """Returns a matplotlib Figure with valid inputs."""
+ from local_deep_research.benchmarks.metrics.visualization import (
+ plot_optimization_history,
+ MATPLOTLIB_AVAILABLE,
+ )
+
+ if not MATPLOTLIB_AVAILABLE:
+ pytest.skip("matplotlib not installed")
+
+ fig = plot_optimization_history([0.3, 0.5, 0.7], [0.3, 0.5, 0.7])
+ assert fig is not None
+ import matplotlib.pyplot as plt
+
+ plt.close(fig)
+
+ def test_saves_to_file_when_output_file_given(self, tmp_path):
+ """Saves figure to disk when output_file is provided."""
+ from local_deep_research.benchmarks.metrics.visualization import (
+ plot_optimization_history,
+ MATPLOTLIB_AVAILABLE,
+ )
+
+ if not MATPLOTLIB_AVAILABLE:
+ pytest.skip("matplotlib not installed")
+
+ out = str(tmp_path / "history.png")
+ fig = plot_optimization_history([0.1, 0.2], [0.1, 0.2], output_file=out)
+ assert fig is not None
+ assert (tmp_path / "history.png").exists()
+ import matplotlib.pyplot as plt
+
+ plt.close(fig)
+
+ def test_custom_title(self):
+ """Custom title is set on the axes."""
+ from local_deep_research.benchmarks.metrics.visualization import (
+ plot_optimization_history,
+ MATPLOTLIB_AVAILABLE,
+ )
+
+ if not MATPLOTLIB_AVAILABLE:
+ pytest.skip("matplotlib not installed")
+
+ fig = plot_optimization_history([0.5], [0.5], title="Custom Title")
+ assert fig is not None
+ ax = fig.get_axes()[0]
+ assert ax.get_title() == "Custom Title"
+ import matplotlib.pyplot as plt
+
+ plt.close(fig)
+
+ def test_single_trial(self):
+ """Works with a single trial value."""
+ from local_deep_research.benchmarks.metrics.visualization import (
+ plot_optimization_history,
+ MATPLOTLIB_AVAILABLE,
+ )
+
+ if not MATPLOTLIB_AVAILABLE:
+ pytest.skip("matplotlib not installed")
+
+ fig = plot_optimization_history([0.9], [0.9])
+ assert fig is not None
+ import matplotlib.pyplot as plt
+
+ plt.close(fig)
+
+
+class TestPlotParameterImportance:
+ """Tests for plot_parameter_importance."""
+
+ def test_returns_none_when_matplotlib_unavailable(self):
+ """Returns None when MATPLOTLIB_AVAILABLE is False."""
+ with patch(
+ "local_deep_research.benchmarks.metrics.visualization.MATPLOTLIB_AVAILABLE",
+ False,
+ ):
+ from local_deep_research.benchmarks.metrics.visualization import (
+ plot_parameter_importance,
+ )
+
+ result = plot_parameter_importance(["a", "b"], [0.3, 0.7])
+ assert result is None
+
+ def test_sorts_by_importance(self):
+ """Parameters are sorted by importance value."""
+ from local_deep_research.benchmarks.metrics.visualization import (
+ plot_parameter_importance,
+ MATPLOTLIB_AVAILABLE,
+ )
+
+ if not MATPLOTLIB_AVAILABLE:
+ pytest.skip("matplotlib not installed")
+
+ fig = plot_parameter_importance(["low", "high", "mid"], [0.1, 0.9, 0.5])
+ assert fig is not None
+ import matplotlib.pyplot as plt
+
+ plt.close(fig)
+
+ def test_saves_to_file(self, tmp_path):
+ """Saves figure when output_file provided."""
+ from local_deep_research.benchmarks.metrics.visualization import (
+ plot_parameter_importance,
+ MATPLOTLIB_AVAILABLE,
+ )
+
+ if not MATPLOTLIB_AVAILABLE:
+ pytest.skip("matplotlib not installed")
+
+ out = str(tmp_path / "importance.png")
+ fig = plot_parameter_importance(["a"], [0.5], output_file=out)
+ assert (tmp_path / "importance.png").exists()
+ import matplotlib.pyplot as plt
+
+ plt.close(fig)
+
+
+class TestPlotQualityVsSpeed:
+ """Tests for plot_quality_vs_speed."""
+
+ def test_returns_none_when_matplotlib_unavailable(self):
+ """Returns None when MATPLOTLIB_AVAILABLE is False."""
+ with patch(
+ "local_deep_research.benchmarks.metrics.visualization.MATPLOTLIB_AVAILABLE",
+ False,
+ ):
+ from local_deep_research.benchmarks.metrics.visualization import (
+ plot_quality_vs_speed,
+ )
+
+ result = plot_quality_vs_speed([0.5], [0.5])
+ assert result is None
+
+ def test_pareto_frontier_with_three_points(self):
+ """Pareto frontier calculation works with 3+ points."""
+ from local_deep_research.benchmarks.metrics.visualization import (
+ plot_quality_vs_speed,
+ MATPLOTLIB_AVAILABLE,
+ )
+
+ if not MATPLOTLIB_AVAILABLE:
+ pytest.skip("matplotlib not installed")
+
+ fig = plot_quality_vs_speed([0.5, 0.8, 0.3, 0.9], [0.9, 0.5, 0.3, 0.8])
+ assert fig is not None
+ import matplotlib.pyplot as plt
+
+ plt.close(fig)
+
+ def test_two_points_skips_pareto(self):
+ """With only 2 points, Pareto frontier is skipped."""
+ from local_deep_research.benchmarks.metrics.visualization import (
+ plot_quality_vs_speed,
+ MATPLOTLIB_AVAILABLE,
+ )
+
+ if not MATPLOTLIB_AVAILABLE:
+ pytest.skip("matplotlib not installed")
+
+ fig = plot_quality_vs_speed([0.5, 0.8], [0.5, 0.8])
+ assert fig is not None
+ import matplotlib.pyplot as plt
+
+ plt.close(fig)
+
+ def test_saves_to_file(self, tmp_path):
+ """Saves figure when output_file provided."""
+ from local_deep_research.benchmarks.metrics.visualization import (
+ plot_quality_vs_speed,
+ MATPLOTLIB_AVAILABLE,
+ )
+
+ if not MATPLOTLIB_AVAILABLE:
+ pytest.skip("matplotlib not installed")
+
+ out = str(tmp_path / "qvs.png")
+ fig = plot_quality_vs_speed(
+ [0.5, 0.8, 0.9], [0.9, 0.5, 0.8], output_file=out
+ )
+ assert (tmp_path / "qvs.png").exists()
+ import matplotlib.pyplot as plt
+
+ plt.close(fig)
+
+ def test_identical_points(self):
+ """Handles identical quality/speed scores gracefully."""
+ from local_deep_research.benchmarks.metrics.visualization import (
+ plot_quality_vs_speed,
+ MATPLOTLIB_AVAILABLE,
+ )
+
+ if not MATPLOTLIB_AVAILABLE:
+ pytest.skip("matplotlib not installed")
+
+ fig = plot_quality_vs_speed([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
+ assert fig is not None
+ import matplotlib.pyplot as plt
+
+ plt.close(fig)
diff --git a/tests/config/test_bootstrap_high_value.py b/tests/config/test_bootstrap_high_value.py
new file mode 100644
index 0000000000..1230ab0105
--- /dev/null
+++ b/tests/config/test_bootstrap_high_value.py
@@ -0,0 +1,157 @@
+"""High-value tests for settings/env_definitions/bootstrap.py.
+
+Tests the BOOTSTRAP_SETTINGS list: SecretSetting, StringSetting,
+BooleanSetting, PathSetting instances, their keys, defaults, and types.
+"""
+
+import pytest
+
+from local_deep_research.settings.env_definitions.bootstrap import (
+ BOOTSTRAP_SETTINGS,
+)
+from local_deep_research.settings.env_settings import (
+ BooleanSetting,
+ StringSetting,
+ PathSetting,
+ SecretSetting,
+ SettingsRegistry,
+)
+
+
+def _find(key: str):
+ """Return the setting object with the given key."""
+ for s in BOOTSTRAP_SETTINGS:
+ if s.key == key:
+ return s
+ raise KeyError(f"Setting {key!r} not found in BOOTSTRAP_SETTINGS")
+
+
+class TestBootstrapRegistry:
+ """Tests for BOOTSTRAP_SETTINGS structure."""
+
+ def test_setting_count(self):
+ """BOOTSTRAP_SETTINGS has the expected number of entries."""
+ assert len(BOOTSTRAP_SETTINGS) == 8
+
+ def test_all_keys_start_with_bootstrap(self):
+ """Every key uses the 'bootstrap.' prefix."""
+ for s in BOOTSTRAP_SETTINGS:
+ assert s.key.startswith("bootstrap."), f"{s.key} missing prefix"
+
+ def test_register_all_settings(self):
+ """All settings can be registered under the bootstrap category."""
+ registry = SettingsRegistry()
+ registry.register_category("bootstrap", BOOTSTRAP_SETTINGS)
+ for s in BOOTSTRAP_SETTINGS:
+ assert registry.is_env_only(s.key)
+
+
+class TestEncryptionKey:
+ """Tests for bootstrap.encryption_key."""
+
+ def test_is_secret_setting(self):
+ s = _find("bootstrap.encryption_key")
+ assert isinstance(s, SecretSetting)
+
+ def test_not_required(self):
+ """encryption_key is not required (allow_unencrypted may be True)."""
+ s = _find("bootstrap.encryption_key")
+ assert s.required is False
+
+
+class TestSecretKey:
+ """Tests for bootstrap.secret_key."""
+
+ def test_is_secret_setting(self):
+ s = _find("bootstrap.secret_key")
+ assert isinstance(s, SecretSetting)
+
+
+class TestDatabaseUrl:
+ """Tests for bootstrap.database_url."""
+
+ def test_is_string_setting(self):
+ s = _find("bootstrap.database_url")
+ assert isinstance(s, StringSetting)
+
+
+class TestAllowUnencrypted:
+ """Tests for bootstrap.allow_unencrypted."""
+
+ def test_is_boolean_setting(self):
+ s = _find("bootstrap.allow_unencrypted")
+ assert isinstance(s, BooleanSetting)
+
+ def test_default_is_false(self, monkeypatch):
+ """Default value is False (require encryption)."""
+ s = _find("bootstrap.allow_unencrypted")
+ monkeypatch.delenv(s.env_var, raising=False)
+ if s.deprecated_env_var:
+ monkeypatch.delenv(s.deprecated_env_var, raising=False)
+ assert s.get_value() is False
+
+ def test_deprecated_alias(self):
+ """Has deprecated env var LDR_ALLOW_UNENCRYPTED."""
+ s = _find("bootstrap.allow_unencrypted")
+ assert s.deprecated_env_var == "LDR_ALLOW_UNENCRYPTED"
+
+ def test_set_to_true(self, monkeypatch):
+ """Can be set to True via env var."""
+ s = _find("bootstrap.allow_unencrypted")
+ monkeypatch.setenv(s.env_var, "true")
+ assert s.get_value() is True
+
+ def test_set_to_false(self, monkeypatch):
+ """Can be set to False via env var."""
+ s = _find("bootstrap.allow_unencrypted")
+ monkeypatch.setenv(s.env_var, "false")
+ assert s.get_value() is False
+
+
+class TestPathSettings:
+ """Tests for bootstrap path settings."""
+
+ @pytest.mark.parametrize(
+ "key",
+ [
+ "bootstrap.data_dir",
+ "bootstrap.config_dir",
+ "bootstrap.log_dir",
+ ],
+ )
+ def test_is_path_setting(self, key):
+ s = _find(key)
+ assert isinstance(s, PathSetting)
+
+ @pytest.mark.parametrize(
+ "key",
+ [
+ "bootstrap.data_dir",
+ "bootstrap.config_dir",
+ "bootstrap.log_dir",
+ ],
+ )
+ def test_create_if_missing_is_true(self, key):
+ """Path settings should create directories if missing."""
+ s = _find(key)
+ assert s.create_if_missing is True
+
+
+class TestEnableFileLogging:
+ """Tests for bootstrap.enable_file_logging."""
+
+ def test_is_boolean_setting(self):
+ s = _find("bootstrap.enable_file_logging")
+ assert isinstance(s, BooleanSetting)
+
+ def test_default_is_false(self, monkeypatch):
+ """Default value is False."""
+ s = _find("bootstrap.enable_file_logging")
+ monkeypatch.delenv(s.env_var, raising=False)
+ assert s.get_value() is False
+
+ def test_set_to_true(self, monkeypatch):
+ """Can be enabled via env var."""
+ s = _find("bootstrap.enable_file_logging")
+ monkeypatch.setenv(s.env_var, "true")
+ assert s.get_value() is True
diff --git a/tests/config/test_db_config_high_value.py b/tests/config/test_db_config_high_value.py
new file mode 100644
index 0000000000..83da4f69e1
--- /dev/null
+++ b/tests/config/test_db_config_high_value.py
@@ -0,0 +1,342 @@
+"""High-value tests for settings/env_definitions/db_config.py.
+
+Tests the DB_CONFIG_SETTINGS list: IntegerSetting and EnumSetting instances,
+their defaults, boundaries, env-var resolution, deprecated aliases, and
+validation of invalid values.
+"""
+
+import pytest
+
+from local_deep_research.settings.env_definitions.db_config import (
+ DB_CONFIG_SETTINGS,
+)
+from local_deep_research.settings.env_settings import (
+ IntegerSetting,
+ EnumSetting,
+ SettingsRegistry,
+)
+
+
+def _find(key: str):
+ """Return the setting object with the given key."""
+ for s in DB_CONFIG_SETTINGS:
+ if s.key == key:
+ return s
+ raise KeyError(f"Setting {key!r} not found in DB_CONFIG_SETTINGS")
+
+
+class TestDbConfigRegistry:
+ """Tests for registering DB_CONFIG_SETTINGS in a SettingsRegistry."""
+
+ def test_register_all_settings(self):
+ """All settings can be registered under the db_config category."""
+ registry = SettingsRegistry()
+ registry.register_category("db_config", DB_CONFIG_SETTINGS)
+ for s in DB_CONFIG_SETTINGS:
+ assert registry.is_env_only(s.key)
+
+ def test_setting_count(self):
+ """DB_CONFIG_SETTINGS contains the expected number of settings."""
+ assert len(DB_CONFIG_SETTINGS) == 8
+
+ def test_all_keys_start_with_db_config(self):
+ """Every key should use the 'db_config.' prefix."""
+ for s in DB_CONFIG_SETTINGS:
+ assert s.key.startswith("db_config."), f"{s.key} missing prefix"
+
+
+class TestEnvVarNaming:
+ """Verify that the auto-generated env_var matches the canonical form."""
+
+ @pytest.mark.parametrize(
+ "key, expected_env_var",
+ [
+ ("db_config.cache_size_mb", "LDR_DB_CONFIG_CACHE_SIZE_MB"),
+ ("db_config.journal_mode", "LDR_DB_CONFIG_JOURNAL_MODE"),
+ ("db_config.synchronous", "LDR_DB_CONFIG_SYNCHRONOUS"),
+ ("db_config.page_size", "LDR_DB_CONFIG_PAGE_SIZE"),
+ ("db_config.kdf_iterations", "LDR_DB_CONFIG_KDF_ITERATIONS"),
+ ("db_config.kdf_algorithm", "LDR_DB_CONFIG_KDF_ALGORITHM"),
+ ("db_config.hmac_algorithm", "LDR_DB_CONFIG_HMAC_ALGORITHM"),
+ (
+ "db_config.cipher_memory_security",
+ "LDR_DB_CONFIG_CIPHER_MEMORY_SECURITY",
+ ),
+ ],
+ )
+ def test_canonical_env_var(self, key, expected_env_var):
+ s = _find(key)
+ assert s.env_var == expected_env_var
+
+
+class TestDeprecatedEnvVars:
+ """Settings that have a deprecated alias should resolve via it."""
+
+ @pytest.mark.parametrize(
+ "key, deprecated_var",
+ [
+ ("db_config.cache_size_mb", "LDR_DB_CACHE_SIZE_MB"),
+ ("db_config.journal_mode", "LDR_DB_JOURNAL_MODE"),
+ ("db_config.synchronous", "LDR_DB_SYNCHRONOUS"),
+ ("db_config.page_size", "LDR_DB_PAGE_SIZE"),
+ ("db_config.kdf_iterations", "LDR_DB_KDF_ITERATIONS"),
+ ("db_config.kdf_algorithm", "LDR_DB_KDF_ALGORITHM"),
+ ("db_config.hmac_algorithm", "LDR_DB_HMAC_ALGORITHM"),
+ ],
+ )
+ def test_deprecated_alias_stored(self, key, deprecated_var):
+ """The deprecated_env_var attribute matches expectations."""
+ s = _find(key)
+ assert s.deprecated_env_var == deprecated_var
+
+ def test_cipher_memory_security_has_no_deprecated_alias(self):
+ s = _find("db_config.cipher_memory_security")
+ assert s.deprecated_env_var is None
+
+ def test_deprecated_alias_fallback_returns_value(self, monkeypatch):
+ """When only the deprecated alias is set, the value should be resolved."""
+ s = _find("db_config.cache_size_mb")
+ monkeypatch.delenv(s.env_var, raising=False)
+ monkeypatch.setenv(s.deprecated_env_var, "128")
+ assert s.get_value() == 128
+
+ def test_canonical_takes_precedence_over_deprecated(self, monkeypatch):
+ """When both canonical and deprecated vars are set, canonical wins."""
+ s = _find("db_config.cache_size_mb")
+ monkeypatch.setenv(s.env_var, "32")
+ monkeypatch.setenv(s.deprecated_env_var, "999")
+ assert s.get_value() == 32
+
+
+class TestCacheSizeMb:
+ """Tests for db_config.cache_size_mb."""
+
+ def test_type(self):
+ assert isinstance(_find("db_config.cache_size_mb"), IntegerSetting)
+
+ def test_default_value(self, monkeypatch):
+ s = _find("db_config.cache_size_mb")
+ monkeypatch.delenv(s.env_var, raising=False)
+ monkeypatch.delenv(s.deprecated_env_var, raising=False)
+ assert s.get_value() == 64
+
+ def test_valid_value(self, monkeypatch):
+ s = _find("db_config.cache_size_mb")
+ monkeypatch.setenv(s.env_var, "256")
+ assert s.get_value() == 256
+
+ def test_min_boundary(self, monkeypatch):
+ s = _find("db_config.cache_size_mb")
+ monkeypatch.setenv(s.env_var, "1")
+ assert s.get_value() == 1
+
+ def test_below_min_raises(self, monkeypatch):
+ s = _find("db_config.cache_size_mb")
+ monkeypatch.setenv(s.env_var, "0")
+ with pytest.raises(ValueError, match="below minimum"):
+ s.get_value()
+
+ def test_max_boundary(self, monkeypatch):
+ s = _find("db_config.cache_size_mb")
+ monkeypatch.setenv(s.env_var, "10000")
+ assert s.get_value() == 10000
+
+ def test_above_max_raises(self, monkeypatch):
+ s = _find("db_config.cache_size_mb")
+ monkeypatch.setenv(s.env_var, "10001")
+ with pytest.raises(ValueError, match="above maximum"):
+ s.get_value()
+
+ def test_non_integer_returns_default(self, monkeypatch):
+ """Non-integer strings fall back to the default value."""
+ s = _find("db_config.cache_size_mb")
+ monkeypatch.setenv(s.env_var, "not_a_number")
+ assert s.get_value() == s.default
+
+ def test_negative_value_raises(self, monkeypatch):
+ """Negative values are below the minimum."""
+ s = _find("db_config.cache_size_mb")
+ monkeypatch.setenv(s.env_var, "-10")
+ with pytest.raises(ValueError, match="below minimum"):
+ s.get_value()
+
+
+class TestPageSize:
+ """Tests for db_config.page_size."""
+
+ def test_default(self, monkeypatch):
+ s = _find("db_config.page_size")
+ monkeypatch.delenv(s.env_var, raising=False)
+ monkeypatch.delenv(s.deprecated_env_var, raising=False)
+ assert s.get_value() == 16384
+
+ def test_min_boundary(self, monkeypatch):
+ s = _find("db_config.page_size")
+ monkeypatch.setenv(s.env_var, "512")
+ assert s.get_value() == 512
+
+ def test_below_min_raises(self, monkeypatch):
+ s = _find("db_config.page_size")
+ monkeypatch.setenv(s.env_var, "256")
+ with pytest.raises(ValueError, match="below minimum"):
+ s.get_value()
+
+ def test_max_boundary(self, monkeypatch):
+ s = _find("db_config.page_size")
+ monkeypatch.setenv(s.env_var, "65536")
+ assert s.get_value() == 65536
+
+ def test_above_max_raises(self, monkeypatch):
+ s = _find("db_config.page_size")
+ monkeypatch.setenv(s.env_var, "65537")
+ with pytest.raises(ValueError, match="above maximum"):
+ s.get_value()
+
+
+class TestJournalMode:
+ """Tests for db_config.journal_mode."""
+
+ def test_type(self):
+ assert isinstance(_find("db_config.journal_mode"), EnumSetting)
+
+ def test_default(self, monkeypatch):
+ s = _find("db_config.journal_mode")
+ monkeypatch.delenv(s.env_var, raising=False)
+ monkeypatch.delenv(s.deprecated_env_var, raising=False)
+ assert s.get_value() == "WAL"
+
+ @pytest.mark.parametrize(
+ "raw_input, expected",
+ [
+ ("WAL", "WAL"),
+ ("wal", "WAL"),
+ ("DELETE", "DELETE"),
+ ("TRUNCATE", "TRUNCATE"),
+ ("PERSIST", "PERSIST"),
+ ("MEMORY", "MEMORY"),
+ ("OFF", "OFF"),
+ ],
+ )
+ def test_valid_values_case_insensitive(
+ self, monkeypatch, raw_input, expected
+ ):
+ s = _find("db_config.journal_mode")
+ monkeypatch.setenv(s.env_var, raw_input)
+ assert s.get_value() == expected
+
+ def test_invalid_value_raises(self, monkeypatch):
+ s = _find("db_config.journal_mode")
+ monkeypatch.setenv(s.env_var, "INVALID_MODE")
+ with pytest.raises(ValueError, match="not in allowed values"):
+ s.get_value()
+
+
+class TestSynchronous:
+ """Tests for db_config.synchronous."""
+
+ def test_default(self, monkeypatch):
+ s = _find("db_config.synchronous")
+ monkeypatch.delenv(s.env_var, raising=False)
+ monkeypatch.delenv(s.deprecated_env_var, raising=False)
+ assert s.get_value() == "NORMAL"
+
+ @pytest.mark.parametrize("value", ["OFF", "NORMAL", "FULL", "EXTRA"])
+ def test_all_valid_values(self, monkeypatch, value):
+ s = _find("db_config.synchronous")
+ monkeypatch.setenv(s.env_var, value)
+ assert s.get_value() == value
+
+ def test_invalid_raises(self, monkeypatch):
+ s = _find("db_config.synchronous")
+ monkeypatch.setenv(s.env_var, "LAZY")
+ with pytest.raises(ValueError, match="not in allowed values"):
+ s.get_value()
+
+
+class TestKdfAlgorithm:
+ """Tests for db_config.kdf_algorithm."""
+
+ def test_default(self, monkeypatch):
+ s = _find("db_config.kdf_algorithm")
+ monkeypatch.delenv(s.env_var, raising=False)
+ monkeypatch.delenv(s.deprecated_env_var, raising=False)
+ assert s.get_value() == "PBKDF2_HMAC_SHA512"
+
+ @pytest.mark.parametrize(
+ "value",
+ ["PBKDF2_HMAC_SHA512", "PBKDF2_HMAC_SHA256", "PBKDF2_HMAC_SHA1"],
+ )
+ def test_all_valid_values(self, monkeypatch, value):
+ s = _find("db_config.kdf_algorithm")
+ monkeypatch.setenv(s.env_var, value)
+ assert s.get_value() == value
+
+ def test_invalid_raises(self, monkeypatch):
+ s = _find("db_config.kdf_algorithm")
+ monkeypatch.setenv(s.env_var, "SCRYPT")
+ with pytest.raises(ValueError, match="not in allowed values"):
+ s.get_value()
+
+
+class TestCipherMemorySecurity:
+ """Tests for db_config.cipher_memory_security."""
+
+ def test_default(self, monkeypatch):
+ s = _find("db_config.cipher_memory_security")
+ monkeypatch.delenv(s.env_var, raising=False)
+ assert s.get_value() == "OFF"
+
+ @pytest.mark.parametrize(
+ "raw_input, expected",
+ [("ON", "ON"), ("on", "ON"), ("OFF", "OFF"), ("off", "OFF")],
+ )
+ def test_valid_values(self, monkeypatch, raw_input, expected):
+ s = _find("db_config.cipher_memory_security")
+ monkeypatch.setenv(s.env_var, raw_input)
+ assert s.get_value() == expected
+
+ def test_invalid_raises(self, monkeypatch):
+ s = _find("db_config.cipher_memory_security")
+ monkeypatch.setenv(s.env_var, "YES")
+ with pytest.raises(ValueError, match="not in allowed values"):
+ s.get_value()
+
+
+class TestRegistryGetIntegration:
+ """Test SettingsRegistry.get() for db_config settings."""
+
+ def _make_registry(self):
+ r = SettingsRegistry()
+ r.register_category("db_config", DB_CONFIG_SETTINGS)
+ return r
+
+ def test_get_returns_default_when_env_not_set(self, monkeypatch):
+ """When no env var is set, registry.get() returns the setting default."""
+ r = self._make_registry()
+ s = _find("db_config.cache_size_mb")
+ monkeypatch.delenv(s.env_var, raising=False)
+ monkeypatch.delenv(s.deprecated_env_var, raising=False)
+ assert r.get("db_config.cache_size_mb") == 64
+
+ def test_get_returns_override_default_for_unknown_key(self):
+ """Unknown key returns the caller-supplied default."""
+ r = self._make_registry()
+ assert r.get("db_config.nonexistent", default=42) == 42
+
+ def test_get_returns_caller_default_on_validation_error(self, monkeypatch):
+ """When the env var fails validation, get() returns the caller default."""
+ r = self._make_registry()
+ s = _find("db_config.cache_size_mb")
+ monkeypatch.setenv(s.env_var, "0") # below minimum
+ assert r.get("db_config.cache_size_mb", default=99) == 99
+
+ def test_get_env_var_for_known_key(self):
+ r = self._make_registry()
+ assert (
+ r.get_env_var("db_config.cache_size_mb")
+ == "LDR_DB_CONFIG_CACHE_SIZE_MB"
+ )
+
+ def test_get_env_var_for_unknown_key(self):
+ r = self._make_registry()
+ assert r.get_env_var("no.such.key") is None
diff --git a/tests/llm_providers/test_anthropic_high_value.py b/tests/llm_providers/test_anthropic_high_value.py
new file mode 100644
index 0000000000..63883d259e
--- /dev/null
+++ b/tests/llm_providers/test_anthropic_high_value.py
@@ -0,0 +1,324 @@
+"""High-value tests for Anthropic LLM provider edge cases and error paths.
+
+These tests focus on error handling paths, credential validation edge cases,
+connection failure scenarios, and other under-tested behaviors in the
+AnthropicProvider implementation.
+"""
+
+import pytest
+from unittest.mock import Mock, patch
+
+from local_deep_research.llm.providers.implementations.anthropic import (
+ AnthropicProvider,
+ create_anthropic_llm,
+ is_anthropic_available,
+ register_anthropic_provider,
+)
+
+
+# Module-level patch path for the anthropic implementation
+ANTHROPIC_MOD = "local_deep_research.llm.providers.implementations.anthropic"
+GET_SETTING = f"{ANTHROPIC_MOD}.get_setting_from_snapshot"
+CHAT_ANTHROPIC = f"{ANTHROPIC_MOD}.ChatAnthropic"
+REGISTER_LLM = f"{ANTHROPIC_MOD}.register_llm"
+
+
+def _make_setting_side_effect(overrides=None):
+ """Helper to build a mock side_effect for get_setting_from_snapshot."""
+ defaults = {
+ "llm.anthropic.api_key": "test-anthropic-key",
+ "llm.max_tokens": None,
+ }
+ if overrides:
+ defaults.update(overrides)
+
+ def side_effect(key, default=None, *args, **kwargs):
+ return defaults.get(key, default)
+
+ return side_effect
+
+
+class TestAnthropicAPIKeyValidation:
+ """Tests for API key validation edge cases in create_llm."""
+
+ def test_empty_string_api_key_raises_value_error(self):
+ """An empty-string API key should raise ValueError."""
+ with patch(
+ GET_SETTING,
+ side_effect=_make_setting_side_effect(
+ {"llm.anthropic.api_key": ""}
+ ),
+ ):
+ with pytest.raises(ValueError, match="API key not configured"):
+ AnthropicProvider.create_llm()
+
+ def test_whitespace_only_api_key_passes_through(self):
+ """A whitespace-only API key passes the truthiness check and reaches ChatAnthropic."""
+ with patch(
+ GET_SETTING,
+ side_effect=_make_setting_side_effect(
+ {"llm.anthropic.api_key": " "}
+ ),
+ ):
+ with patch(CHAT_ANTHROPIC) as mock_chat:
+ mock_chat.return_value = Mock()
+ AnthropicProvider.create_llm()
+ call_kwargs = mock_chat.call_args[1]
+ assert call_kwargs["anthropic_api_key"] == " "
+
+ def test_none_api_key_raises_value_error(self):
+ """A None API key should raise ValueError."""
+ with patch(
+ GET_SETTING,
+ side_effect=_make_setting_side_effect(
+ {"llm.anthropic.api_key": None}
+ ),
+ ):
+ with pytest.raises(ValueError, match="API key not configured"):
+ AnthropicProvider.create_llm()
+
+ def test_false_api_key_raises_value_error(self):
+ """A boolean False API key should raise ValueError (falsy value)."""
+ with patch(
+ GET_SETTING,
+ side_effect=_make_setting_side_effect(
+ {"llm.anthropic.api_key": False}
+ ),
+ ):
+ with pytest.raises(ValueError):
+ AnthropicProvider.create_llm()
+
+ def test_error_message_includes_setting_key(self):
+ """ValueError message should include the settings key."""
+ with patch(
+ GET_SETTING,
+ side_effect=_make_setting_side_effect(
+ {"llm.anthropic.api_key": None}
+ ),
+ ):
+ with pytest.raises(ValueError) as exc_info:
+ AnthropicProvider.create_llm()
+ assert "llm.anthropic.api_key" in str(exc_info.value)
+
+ def test_error_message_includes_provider_name(self):
+ """ValueError message should include provider name."""
+ with patch(
+ GET_SETTING,
+ side_effect=_make_setting_side_effect(
+ {"llm.anthropic.api_key": None}
+ ),
+ ):
+ with pytest.raises(ValueError) as exc_info:
+ AnthropicProvider.create_llm()
+ assert "Anthropic" in str(exc_info.value)
+
+ def test_api_key_passed_as_anthropic_api_key_param(self):
+ """API key must be passed as 'anthropic_api_key', not 'api_key'."""
+ with patch(GET_SETTING, side_effect=_make_setting_side_effect()):
+ with patch(CHAT_ANTHROPIC) as mock_chat:
+ mock_chat.return_value = Mock()
+ AnthropicProvider.create_llm()
+ call_kwargs = mock_chat.call_args[1]
+ assert "anthropic_api_key" in call_kwargs
+ assert "api_key" not in call_kwargs
+
+
+class TestAnthropicMaxTokensHandling:
+ """Tests for max_tokens configuration edge cases."""
+
+ def test_max_tokens_not_included_when_none(self):
+ """max_tokens should not be in params when settings return None."""
+ with patch(
+ GET_SETTING,
+ side_effect=_make_setting_side_effect({"llm.max_tokens": None}),
+ ):
+ with patch(CHAT_ANTHROPIC) as mock_chat:
+ mock_chat.return_value = Mock()
+ AnthropicProvider.create_llm()
+ call_kwargs = mock_chat.call_args[1]
+ assert "max_tokens" not in call_kwargs
+
+ def test_max_tokens_not_included_when_zero(self):
+ """max_tokens should not be in params when set to 0 (falsy)."""
+ with patch(
+ GET_SETTING,
+ side_effect=_make_setting_side_effect({"llm.max_tokens": 0}),
+ ):
+ with patch(CHAT_ANTHROPIC) as mock_chat:
+ mock_chat.return_value = Mock()
+ AnthropicProvider.create_llm()
+ call_kwargs = mock_chat.call_args[1]
+ assert "max_tokens" not in call_kwargs
+
+ def test_max_tokens_converted_to_int(self):
+ """max_tokens should be converted to int even if stored as string."""
+ with patch(
+ GET_SETTING,
+ side_effect=_make_setting_side_effect({"llm.max_tokens": "8192"}),
+ ):
+ with patch(CHAT_ANTHROPIC) as mock_chat:
+ mock_chat.return_value = Mock()
+ AnthropicProvider.create_llm()
+ call_kwargs = mock_chat.call_args[1]
+ assert call_kwargs["max_tokens"] == 8192
+ assert isinstance(call_kwargs["max_tokens"], int)
+
+ def test_max_tokens_converted_to_int_from_float(self):
+ """max_tokens should be converted to int even if stored as float."""
+ with patch(
+ GET_SETTING,
+ side_effect=_make_setting_side_effect({"llm.max_tokens": 4096.0}),
+ ):
+ with patch(CHAT_ANTHROPIC) as mock_chat:
+ mock_chat.return_value = Mock()
+ AnthropicProvider.create_llm()
+ call_kwargs = mock_chat.call_args[1]
+ assert call_kwargs["max_tokens"] == 4096
+ assert isinstance(call_kwargs["max_tokens"], int)
+
+
+class TestAnthropicSettingsSnapshot:
+ """Tests for settings_snapshot passthrough behavior."""
+
+ def test_settings_snapshot_passed_through_kwargs(self):
+ """settings_snapshot should be extracted from kwargs and passed to get_setting."""
+ snapshot = {"llm.anthropic.api_key": "snap-key", "llm.max_tokens": None}
+
+ with patch(
+ GET_SETTING,
+ side_effect=_make_setting_side_effect(
+ {"llm.anthropic.api_key": "snap-key"}
+ ),
+ ) as mock_get:
+ with patch(CHAT_ANTHROPIC) as mock_chat:
+ mock_chat.return_value = Mock()
+ AnthropicProvider.create_llm(settings_snapshot=snapshot)
+
+ for call in mock_get.call_args_list:
+ assert call.kwargs.get("settings_snapshot") == snapshot
+
+ def test_create_llm_without_settings_snapshot(self):
+ """create_llm should work when no settings_snapshot is provided."""
+ with patch(GET_SETTING, side_effect=_make_setting_side_effect()):
+ with patch(CHAT_ANTHROPIC) as mock_chat:
+ mock_chat.return_value = Mock()
+ result = AnthropicProvider.create_llm()
+ assert result is mock_chat.return_value
+
+
+class TestAnthropicIsAvailableEdgeCases:
+ """Tests for is_available edge cases."""
+
+ def test_whitespace_only_key_returns_false(self):
+ """Whitespace-only API key is stripped in is_available, returns False."""
+ with patch(
+ GET_SETTING,
+ side_effect=_make_setting_side_effect(
+ {"llm.anthropic.api_key": " \t\n "}
+ ),
+ ):
+ assert AnthropicProvider.is_available() is False
+
+ def test_valid_key_with_leading_trailing_whitespace(self):
+ """A valid key with surrounding whitespace should still be available."""
+ with patch(
+ GET_SETTING,
+ side_effect=_make_setting_side_effect(
+ {"llm.anthropic.api_key": " sk-ant-valid-key "}
+ ),
+ ):
+ assert AnthropicProvider.is_available() is True
+
+ def test_is_available_catches_runtime_error(self):
+ """is_available should catch RuntimeError from missing settings context."""
+ with patch(GET_SETTING) as mock_get:
+ mock_get.side_effect = RuntimeError("No settings context")
+ assert AnthropicProvider.is_available() is False
+
+ def test_is_available_catches_type_error(self):
+ """is_available should catch TypeError."""
+ with patch(GET_SETTING) as mock_get:
+ mock_get.side_effect = TypeError("unexpected type")
+ assert AnthropicProvider.is_available() is False
+
+
+class TestAnthropicChatConstruction:
+ """Tests verifying ChatAnthropic is constructed with correct params."""
+
+ def test_default_temperature_is_0_7(self):
+ """Default temperature should be 0.7 when not specified."""
+ with patch(GET_SETTING, side_effect=_make_setting_side_effect()):
+ with patch(CHAT_ANTHROPIC) as mock_chat:
+ mock_chat.return_value = Mock()
+ AnthropicProvider.create_llm()
+ call_kwargs = mock_chat.call_args[1]
+ assert call_kwargs["temperature"] == 0.7
+
+ def test_zero_temperature(self):
+ """Temperature of 0.0 should be passed through correctly."""
+ with patch(GET_SETTING, side_effect=_make_setting_side_effect()):
+ with patch(CHAT_ANTHROPIC) as mock_chat:
+ mock_chat.return_value = Mock()
+ AnthropicProvider.create_llm(temperature=0.0)
+ call_kwargs = mock_chat.call_args[1]
+ assert call_kwargs["temperature"] == 0.0
+
+ def test_chat_anthropic_exception_propagates(self):
+ """If ChatAnthropic constructor raises, it should propagate."""
+ with patch(GET_SETTING, side_effect=_make_setting_side_effect()):
+ with patch(CHAT_ANTHROPIC) as mock_chat:
+ mock_chat.side_effect = Exception("Connection refused")
+ with pytest.raises(Exception, match="Connection refused"):
+ AnthropicProvider.create_llm()
+
+ def test_only_expected_params_passed_without_max_tokens(self):
+ """Without max_tokens, only model, anthropic_api_key, temperature should be passed."""
+ with patch(GET_SETTING, side_effect=_make_setting_side_effect()):
+ with patch(CHAT_ANTHROPIC) as mock_chat:
+ mock_chat.return_value = Mock()
+ AnthropicProvider.create_llm()
+ call_kwargs = mock_chat.call_args[1]
+ expected_keys = {"model", "anthropic_api_key", "temperature"}
+ assert set(call_kwargs.keys()) == expected_keys
+
+
+class TestAnthropicBackwardCompatibility:
+ """Edge cases for backward compatibility standalone functions."""
+
+ def test_create_anthropic_llm_passes_kwargs(self):
+ """create_anthropic_llm should pass through kwargs like settings_snapshot."""
+ snapshot = {"llm.anthropic.api_key": "test"}
+ with patch.object(AnthropicProvider, "create_llm") as mock_create:
+ mock_create.return_value = Mock()
+ create_anthropic_llm(
+ model_name="claude-3-haiku-20240307",
+ temperature=0.3,
+ settings_snapshot=snapshot,
+ )
+ mock_create.assert_called_once_with(
+ "claude-3-haiku-20240307", 0.3, settings_snapshot=snapshot
+ )
+
+ def test_create_anthropic_llm_default_args(self):
+ """create_anthropic_llm should use defaults when no args provided."""
+ with patch.object(AnthropicProvider, "create_llm") as mock_create:
+ mock_create.return_value = Mock()
+ create_anthropic_llm()
+ mock_create.assert_called_once_with(None, 0.7)
+
+ def test_is_anthropic_available_passes_snapshot(self):
+ """is_anthropic_available should pass settings_snapshot to provider."""
+ snapshot = {"llm.anthropic.api_key": "key"}
+ with patch.object(AnthropicProvider, "is_available") as mock_avail:
+ mock_avail.return_value = True
+ result = is_anthropic_available(settings_snapshot=snapshot)
+ mock_avail.assert_called_once_with(snapshot)
+ assert result is True
+
+ def test_register_anthropic_provider_registers_correct_function(self):
+ """register_anthropic_provider should register create_anthropic_llm."""
+ with patch(REGISTER_LLM) as mock_register:
+ register_anthropic_provider()
+ mock_register.assert_called_once_with(
+ "anthropic", create_anthropic_llm
+ )
diff --git a/tests/llm_providers/test_custom_openai_high_value.py b/tests/llm_providers/test_custom_openai_high_value.py
new file mode 100644
index 0000000000..2e67922539
--- /dev/null
+++ b/tests/llm_providers/test_custom_openai_high_value.py
@@ -0,0 +1,211 @@
+"""High-value tests for Custom OpenAI endpoint provider edge cases.
+
+Focuses on the unique is_available logic (URL-based availability),
+create_llm URL passthrough, and backward compatibility functions.
+"""
+
+from unittest.mock import Mock, patch
+
+from local_deep_research.llm.providers.implementations.custom_openai_endpoint import (
+ CustomOpenAIEndpointProvider,
+ create_openai_endpoint_llm,
+ is_openai_endpoint_available,
+ register_custom_openai_endpoint_provider,
+)
+from local_deep_research.llm.providers.openai_base import (
+ OpenAICompatibleProvider,
+)
+
+
+CUSTOM_MOD = (
+ "local_deep_research.llm.providers.implementations.custom_openai_endpoint"
+)
+GET_SETTING = f"{CUSTOM_MOD}.get_setting_from_snapshot"
+REGISTER_LLM = f"{CUSTOM_MOD}.register_llm"
+PARENT_CREATE = "local_deep_research.llm.providers.openai_base.OpenAICompatibleProvider.create_llm"
+
+
+class TestCustomOpenAIIsAvailable:
+ """Tests for the unique is_available logic (api_key OR custom URL)."""
+
+ def test_available_with_api_key_only(self):
+ """Provider is available when only API key is set."""
+
+ def side_effect(key, default=None, **kwargs):
+ if key == "llm.openai_endpoint.api_key":
+ return "my-key"
+ return default
+
+ with patch(GET_SETTING, side_effect=side_effect):
+ assert CustomOpenAIEndpointProvider.is_available() is True
+
+ def test_available_with_custom_url_only(self):
+ """Provider is available when custom URL differs from default."""
+
+ def side_effect(key, default=None, **kwargs):
+ if key == "llm.openai_endpoint.api_key":
+ return None
+ if key == "llm.openai_endpoint.url":
+ return "http://localhost:8080/v1"
+ return default
+
+ with patch(GET_SETTING, side_effect=side_effect):
+ assert CustomOpenAIEndpointProvider.is_available() is True
+
+ def test_not_available_with_default_url_and_no_key(self):
+ """Provider is NOT available when URL equals default and no API key."""
+
+ def side_effect(key, default=None, **kwargs):
+ if key == "llm.openai_endpoint.api_key":
+ return None
+ if key == "llm.openai_endpoint.url":
+ return "https://api.openai.com/v1"
+ return default
+
+ with patch(GET_SETTING, side_effect=side_effect):
+ assert CustomOpenAIEndpointProvider.is_available() is False
+
+ def test_not_available_with_none_url_and_no_key(self):
+ """Provider is NOT available when both URL and key are None."""
+ with patch(GET_SETTING, return_value=None):
+ assert CustomOpenAIEndpointProvider.is_available() is False
+
+ def test_whitespace_api_key_not_available(self):
+ """Whitespace-only API key does not make provider available."""
+
+ def side_effect(key, default=None, **kwargs):
+ if key == "llm.openai_endpoint.api_key":
+ return " "
+ if key == "llm.openai_endpoint.url":
+ return None
+ return default
+
+ with patch(GET_SETTING, side_effect=side_effect):
+ assert CustomOpenAIEndpointProvider.is_available() is False
+
+ def test_whitespace_url_not_available(self):
+ """Whitespace-only URL does not make provider available."""
+
+ def side_effect(key, default=None, **kwargs):
+ if key == "llm.openai_endpoint.api_key":
+ return None
+ if key == "llm.openai_endpoint.url":
+ return " "
+ return default
+
+ with patch(GET_SETTING, side_effect=side_effect):
+ assert CustomOpenAIEndpointProvider.is_available() is False
+
+ def test_exception_in_api_key_check_falls_through_to_url(self):
+ """Exception reading API key falls through to URL check."""
+ call_count = 0
+
+ def side_effect(key, default=None, **kwargs):
+ nonlocal call_count
+ call_count += 1
+ if key == "llm.openai_endpoint.api_key":
+ raise RuntimeError("settings error")
+ if key == "llm.openai_endpoint.url":
+ return "http://myserver:5000/v1"
+ return default
+
+ with patch(GET_SETTING, side_effect=side_effect):
+ assert CustomOpenAIEndpointProvider.is_available() is True
+
+ def test_both_exceptions_return_false(self):
+ """Exceptions in both api_key and url checks return False."""
+ with patch(GET_SETTING, side_effect=RuntimeError("boom")):
+ assert CustomOpenAIEndpointProvider.is_available() is False
+
+
+class TestCustomOpenAICreateLlm:
+ """Tests for create_llm URL passthrough."""
+
+ def test_custom_url_passed_to_parent(self):
+ """Custom URL from settings is passed as base_url to parent."""
+
+ def side_effect(key, default=None, **kwargs):
+ if key == "llm.openai_endpoint.url":
+ return "http://myserver:9000/v1"
+ if key == "llm.openai_endpoint.api_key":
+ return "test-key"
+ return default
+
+ with patch(GET_SETTING, side_effect=side_effect):
+ with patch(PARENT_CREATE) as mock_parent:
+ mock_parent.return_value = Mock()
+ CustomOpenAIEndpointProvider.create_llm()
+ _, kwargs = mock_parent.call_args
+ assert "base_url" in kwargs
+
+ def test_none_url_uses_default(self):
+ """None URL falls back to default_base_url."""
+
+ def side_effect(key, default=None, **kwargs):
+ if key == "llm.openai_endpoint.url":
+ return None
+ if key == "llm.openai_endpoint.api_key":
+ return "test-key"
+ return default
+
+ with patch(GET_SETTING, side_effect=side_effect):
+ with patch(PARENT_CREATE) as mock_parent:
+ mock_parent.return_value = Mock()
+ CustomOpenAIEndpointProvider.create_llm()
+ _, kwargs = mock_parent.call_args
+ assert (
+ kwargs["base_url"]
+ == CustomOpenAIEndpointProvider.default_base_url
+ )
+
+
+class TestCustomOpenAIClassAttributes:
+ """Tests for class-level metadata."""
+
+ def test_inherits_from_openai_compatible(self):
+ """Inherits from OpenAICompatibleProvider."""
+ assert issubclass(
+ CustomOpenAIEndpointProvider, OpenAICompatibleProvider
+ )
+
+ def test_provider_key(self):
+ """Provider key is OPENAI_ENDPOINT."""
+ assert CustomOpenAIEndpointProvider.provider_key == "OPENAI_ENDPOINT"
+
+ def test_is_cloud_is_none(self):
+ """is_cloud is None (could be local or cloud)."""
+ assert CustomOpenAIEndpointProvider.is_cloud is None
+
+ def test_requires_auth_for_models_returns_false(self):
+ """Custom endpoints don't require auth for model listing."""
+ assert CustomOpenAIEndpointProvider.requires_auth_for_models() is False
+
+
+class TestCustomOpenAIBackwardCompat:
+ """Tests for backward compatibility standalone functions."""
+
+ def test_create_openai_endpoint_llm_delegates(self):
+ """create_openai_endpoint_llm delegates to provider class."""
+ with patch.object(
+ CustomOpenAIEndpointProvider, "create_llm"
+ ) as mock_create:
+ mock_create.return_value = Mock()
+ create_openai_endpoint_llm(model_name="gpt-4", temperature=0.5)
+ mock_create.assert_called_once_with("gpt-4", 0.5)
+
+ def test_is_openai_endpoint_available_delegates(self):
+ """is_openai_endpoint_available delegates to provider class."""
+ with patch.object(
+ CustomOpenAIEndpointProvider, "is_available"
+ ) as mock_avail:
+ mock_avail.return_value = True
+ result = is_openai_endpoint_available()
+ assert result is True
+
+ def test_register_custom_openai_endpoint_provider(self):
+ """register function registers the correct factory."""
+ with patch(REGISTER_LLM) as mock_register:
+ register_custom_openai_endpoint_provider()
+ mock_register.assert_called_once_with(
+ "openai_endpoint", create_openai_endpoint_llm
+ )
diff --git a/tests/llm_providers/test_providers_high_value.py b/tests/llm_providers/test_providers_high_value.py
new file mode 100644
index 0000000000..6de2e0b1c6
--- /dev/null
+++ b/tests/llm_providers/test_providers_high_value.py
@@ -0,0 +1,336 @@
+"""High-value edge case tests for LM Studio, OpenRouter, xAI, and IONOS providers.
+
+Focuses on error handling paths, cross-provider consistency, edge cases in
+configuration, list_models behavior, and provider-specific quirks.
+"""
+
+import pytest
+from unittest.mock import Mock, patch
+
+from local_deep_research.llm.providers.implementations.lmstudio import (
+ LMStudioProvider,
+)
+from local_deep_research.llm.providers.implementations.openrouter import (
+ OpenRouterProvider,
+)
+from local_deep_research.llm.providers.implementations.xai import (
+ XAIProvider,
+)
+from local_deep_research.llm.providers.implementations.ionos import (
+ IONOSProvider,
+)
+from local_deep_research.llm.providers.openai_base import (
+ OpenAICompatibleProvider,
+)
+from local_deep_research.llm.providers.base import BaseLLMProvider
+
+
+def _lmstudio_settings(url_value, extras=None):
+ """Side-effect factory for LM Studio (no API key, URL-based)."""
+ base = {
+ "llm.lmstudio.url": url_value,
+ "llm.max_tokens": None,
+ }
+ if extras:
+ base.update(extras)
+
+ def _side_effect(*args, **kwargs):
+ key = args[0] if args else kwargs.get("key", "")
+ default = args[1] if len(args) > 1 else kwargs.get("default", None)
+ return base.get(key, default)
+
+ return _side_effect
+
+
+def _cloud_settings(api_key_setting, api_key_value, extras=None):
+ """Build a mock side-effect for cloud provider settings."""
+ base = {
+ api_key_setting: api_key_value,
+ "llm.max_tokens": None,
+ "llm.streaming": None,
+ "llm.max_retries": None,
+ "llm.request_timeout": None,
+ }
+ if extras:
+ base.update(extras)
+
+ def _side_effect(key, default=None, *args, **kwargs):
+ return base.get(key, default)
+
+ return _side_effect
+
+
+# ===========================================================================
+# LM Studio edge cases
+# ===========================================================================
+
+
+class TestLMStudioEdgeCases:
+ """Edge cases unique to the LM Studio provider."""
+
+ def test_is_available_with_non_200_status_codes(self):
+ """Various non-200 codes return False."""
+ for status in [301, 403, 404, 502, 503]:
+ with patch(
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
+ ) as mock_gs:
+ mock_gs.side_effect = _lmstudio_settings(
+ "http://localhost:1234/v1"
+ )
+ with patch("local_deep_research.security.safe_get") as mock_get:
+ mock_response = Mock(status_code=status)
+ mock_get.return_value = mock_response
+ assert LMStudioProvider.is_available() is False, (
+ f"Expected False for HTTP {status}"
+ )
+
+ def test_is_available_timeout_returns_false(self):
+ """A connection timeout is handled gracefully."""
+ with patch(
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
+ ) as mock_gs:
+ mock_gs.side_effect = _lmstudio_settings("http://localhost:1234/v1")
+ with patch("local_deep_research.security.safe_get") as mock_get:
+ mock_get.side_effect = TimeoutError("Connection timed out")
+ assert LMStudioProvider.is_available() is False
+
+ def test_lmstudio_inherits_from_openai_compatible(self):
+ """LM Studio provider inherits from OpenAICompatibleProvider."""
+ assert issubclass(LMStudioProvider, OpenAICompatibleProvider)
+ assert issubclass(LMStudioProvider, BaseLLMProvider)
+
+
+# ===========================================================================
+# OpenRouter edge cases
+# ===========================================================================
+
+
+class TestOpenRouterEdgeCases:
+ """Edge cases unique to the OpenRouter provider."""
+
+ def test_create_llm_with_whitespace_only_api_key(self):
+ """Whitespace-only API key passes truthiness check (not stripped in create_llm)."""
+ with patch(
+ "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ ) as mock_gs:
+ mock_gs.side_effect = _cloud_settings(
+ "llm.openrouter.api_key", " "
+ )
+ with patch(
+ "local_deep_research.llm.providers.openai_base.ChatOpenAI"
+ ) as mock_chat:
+ mock_chat.return_value = Mock()
+ OpenRouterProvider.create_llm()
+ call_kwargs = mock_chat.call_args[1]
+ assert call_kwargs["api_key"] == " "
+
+ def test_create_llm_error_message_contains_setting_name(self):
+ """Error message tells user which setting to configure."""
+ with patch(
+ "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ ) as mock_gs:
+ mock_gs.side_effect = _cloud_settings(
+ "llm.openrouter.api_key", None
+ )
+ with pytest.raises(ValueError) as exc_info:
+ OpenRouterProvider.create_llm()
+ assert "llm.openrouter.api_key" in str(exc_info.value)
+
+ def test_list_models_for_api_connection_error_returns_empty(self):
+ """Network error returns empty list, not exception."""
+ with patch("openai.OpenAI") as mock_openai:
+ mock_openai.side_effect = ConnectionError("Network unreachable")
+ result = OpenRouterProvider.list_models_for_api(api_key="key")
+ assert result == []
+
+ def test_openrouter_inherits_from_openai_compatible(self):
+ """OpenRouter provider inherits from OpenAICompatibleProvider."""
+ assert issubclass(OpenRouterProvider, OpenAICompatibleProvider)
+ assert issubclass(OpenRouterProvider, BaseLLMProvider)
+
+ def test_create_llm_passes_max_tokens_when_configured(self):
+ """max_tokens from settings is forwarded to ChatOpenAI."""
+ with patch(
+ "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ ) as mock_gs:
+ mock_gs.side_effect = _cloud_settings(
+ "llm.openrouter.api_key",
+ "test-key",
+ extras={"llm.max_tokens": 2048},
+ )
+ with patch(
+ "local_deep_research.llm.providers.openai_base.ChatOpenAI"
+ ) as mock_chat:
+ mock_chat.return_value = Mock()
+ OpenRouterProvider.create_llm()
+ call_kwargs = mock_chat.call_args[1]
+ assert call_kwargs["max_tokens"] == 2048
+
+
+# ===========================================================================
+# xAI edge cases
+# ===========================================================================
+
+
+class TestXAIEdgeCases:
+ """Edge cases unique to the xAI Grok provider."""
+
+ def test_create_llm_with_empty_string_api_key(self):
+ """Empty string API key raises ValueError."""
+ with patch(
+ "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ ) as mock_gs:
+ mock_gs.side_effect = _cloud_settings("llm.xai.api_key", "")
+ with pytest.raises(ValueError, match="(?i)api key"):
+ XAIProvider.create_llm()
+
+ def test_create_llm_error_message_contains_xai_setting(self):
+ """Error message references the correct xAI setting key."""
+ with patch(
+ "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ ) as mock_gs:
+ mock_gs.side_effect = _cloud_settings("llm.xai.api_key", None)
+ with pytest.raises(ValueError) as exc_info:
+ XAIProvider.create_llm()
+ assert "llm.xai.api_key" in str(exc_info.value)
+
+ def test_list_models_for_api_requires_key(self):
+ """xAI requires auth so list_models_for_api returns [] without key."""
+ result = XAIProvider.list_models_for_api(api_key=None)
+ assert result == []
+
+ def test_is_available_with_exception_in_settings(self):
+ """Exception during settings retrieval returns False."""
+ with patch(
+ "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ ) as mock_gs:
+ mock_gs.side_effect = RuntimeError("settings DB corrupted")
+ assert XAIProvider.is_available() is False
+
+ def test_xai_inherits_from_openai_compatible(self):
+ """xAI provider inherits from OpenAICompatibleProvider."""
+ assert issubclass(XAIProvider, OpenAICompatibleProvider)
+ assert issubclass(XAIProvider, BaseLLMProvider)
+
+
+# ===========================================================================
+# IONOS edge cases
+# ===========================================================================
+
+
+class TestIONOSEdgeCases:
+ """Edge cases unique to the IONOS provider."""
+
+ def test_create_llm_with_none_api_key_raises(self):
+ """Explicitly None API key raises ValueError."""
+ with patch(
+ "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ ) as mock_gs:
+ mock_gs.side_effect = _cloud_settings("llm.ionos.api_key", None)
+ with pytest.raises(ValueError, match="(?i)api key"):
+ IONOSProvider.create_llm()
+
+ def test_create_llm_error_message_references_ionos_setting(self):
+ """Error message tells the user exactly which setting is missing."""
+ with patch(
+ "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ ) as mock_gs:
+ mock_gs.side_effect = _cloud_settings("llm.ionos.api_key", None)
+ with pytest.raises(ValueError) as exc_info:
+ IONOSProvider.create_llm()
+ assert "llm.ionos.api_key" in str(exc_info.value)
+
+ def test_list_models_for_api_without_key_returns_empty(self):
+ """IONOS requires auth so returns [] without a key."""
+ result = IONOSProvider.list_models_for_api(api_key=None)
+ assert result == []
+
+ def test_is_available_with_whitespace_only_key(self):
+ """Whitespace-only API key is treated as unavailable."""
+ with patch(
+ "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ ) as mock_gs:
+ mock_gs.return_value = " "
+ assert IONOSProvider.is_available() is False
+
+ def test_ionos_inherits_from_openai_compatible(self):
+ """IONOS provider inherits from OpenAICompatibleProvider."""
+ assert issubclass(IONOSProvider, OpenAICompatibleProvider)
+ assert issubclass(IONOSProvider, BaseLLMProvider)
+
+
+# ===========================================================================
+# Cross-provider consistency tests
+# ===========================================================================
+
+
+class TestCrossProviderConsistency:
+ """Verify consistent behaviour across all four providers."""
+
+ @pytest.mark.parametrize(
+ "provider_cls,expected_key",
+ [
+ (LMStudioProvider, "LMSTUDIO"),
+ (OpenRouterProvider, "OPENROUTER"),
+ (XAIProvider, "XAI"),
+ (IONOSProvider, "IONOS"),
+ ],
+ )
+ def test_provider_key_is_uppercase(self, provider_cls, expected_key):
+ """All provider_key values should be uppercase identifiers."""
+ assert provider_cls.provider_key == expected_key
+
+ @pytest.mark.parametrize(
+ "provider_cls,is_cloud",
+ [
+ (LMStudioProvider, False),
+ (OpenRouterProvider, True),
+ (XAIProvider, True),
+ (IONOSProvider, True),
+ ],
+ )
+ def test_cloud_flag_consistency(self, provider_cls, is_cloud):
+ """Cloud flag matches expected value for each provider."""
+ assert provider_cls.is_cloud is is_cloud
+
+ @pytest.mark.parametrize(
+ "provider_cls",
+ [LMStudioProvider, OpenRouterProvider, XAIProvider, IONOSProvider],
+ )
+ def test_default_base_url_is_valid(self, provider_cls):
+ """All providers must have a non-empty default_base_url with a scheme."""
+ url = provider_cls.default_base_url
+ assert url is not None
+ assert url.startswith("http://") or url.startswith("https://")
+
+ @pytest.mark.parametrize(
+ "provider_cls",
+ [LMStudioProvider, OpenRouterProvider, XAIProvider, IONOSProvider],
+ )
+ def test_default_model_is_non_empty(self, provider_cls):
+ """Every provider must declare a non-empty default model."""
+ assert provider_cls.default_model
+ assert len(provider_cls.default_model) > 0
+
+ @pytest.mark.parametrize(
+ "provider_cls",
+ [OpenRouterProvider, XAIProvider, IONOSProvider],
+ )
+ def test_cloud_providers_require_api_key_setting(self, provider_cls):
+ """Cloud providers must define an api_key_setting."""
+ assert provider_cls.api_key_setting is not None
+ assert provider_cls.api_key_setting.startswith("llm.")
+
+ def test_local_provider_does_not_require_api_key(self):
+ """LM Studio (local) should not require an API key."""
+ assert LMStudioProvider.api_key_setting is None
+
+ @pytest.mark.parametrize(
+ "provider_cls",
+ [LMStudioProvider, OpenRouterProvider, XAIProvider, IONOSProvider],
+ )
+ def test_all_providers_have_company_name(self, provider_cls):
+ """Every provider must have a company_name for UI display."""
+ assert provider_cls.company_name
+ assert isinstance(provider_cls.company_name, str)
+ assert len(provider_cls.company_name) > 0
diff --git a/tests/metrics/test_cost_calculator_high_value.py b/tests/metrics/test_cost_calculator_high_value.py
new file mode 100644
index 0000000000..2df4012f5d
--- /dev/null
+++ b/tests/metrics/test_cost_calculator_high_value.py
@@ -0,0 +1,204 @@
+"""High-value tests for metrics/pricing/cost_calculator.py.
+
+Covers sync cost calculation, batch cost edge cases, model name resolution,
+zero/negative tokens, and research cost summary aggregation.
+"""
+
+import pytest
+
+from local_deep_research.metrics.pricing.cost_calculator import CostCalculator
+
+
+class TestCostCalculatorInit:
+ """Tests for CostCalculator initialization."""
+
+ def test_init_creates_cache(self):
+ """CostCalculator creates a PricingCache on init."""
+ calc = CostCalculator()
+ assert calc.cache is not None
+
+ def test_init_pricing_fetcher_is_none(self):
+ """Pricing fetcher is None until async context is entered."""
+ calc = CostCalculator()
+ assert calc.pricing_fetcher is None
+
+
+class TestCalculateCostSync:
+ """Tests for synchronous cost calculation."""
+
+ def test_known_model_returns_cost(self):
+ """Known model (gpt-4) returns correct cost."""
+ calc = CostCalculator()
+ result = calc.calculate_cost_sync("gpt-4", 1000, 500)
+ assert result["prompt_cost"] > 0
+ assert result["completion_cost"] > 0
+ assert (
+ result["total_cost"]
+ == result["prompt_cost"] + result["completion_cost"]
+ )
+ assert result["pricing_used"] is not None
+
+ def test_unknown_model_returns_zero_cost(self):
+ """Unknown model returns zero cost with error message."""
+ calc = CostCalculator()
+ result = calc.calculate_cost_sync(
+ "totally-unknown-model-xyz", 1000, 500
+ )
+ assert result["prompt_cost"] == 0.0
+ assert result["completion_cost"] == 0.0
+ assert result["total_cost"] == 0.0
+ assert "error" in result
+
+ def test_zero_tokens_returns_zero_cost(self):
+ """Zero tokens should return zero cost."""
+ calc = CostCalculator()
+ result = calc.calculate_cost_sync("gpt-4", 0, 0)
+ assert result["total_cost"] == 0.0
+
+ def test_large_token_count(self):
+ """Large token counts produce proportional costs."""
+ calc = CostCalculator()
+ small = calc.calculate_cost_sync("gpt-4", 1000, 1000)
+ large = calc.calculate_cost_sync("gpt-4", 10000, 10000)
+ if small["pricing_used"]:
+ assert large["total_cost"] == pytest.approx(
+ small["total_cost"] * 10, rel=1e-4
+ )
+
+ def test_cost_precision_is_six_decimals(self):
+ """Costs are rounded to 6 decimal places."""
+ calc = CostCalculator()
+ result = calc.calculate_cost_sync("gpt-4", 1, 1)
+ if result["pricing_used"]:
+ # Check the string representation has at most 6 decimal places
+ prompt_str = f"{result['prompt_cost']:.10f}"
+ parts = prompt_str.split(".")
+ # The value after rounding should have trailing zeros after 6th decimal
+ assert len(parts[1].rstrip("0")) <= 6
+
+ def test_model_with_provider_prefix(self):
+ """Model name with provider prefix like 'openai/gpt-4' strips prefix."""
+ calc = CostCalculator()
+ result = calc.calculate_cost_sync("openai/gpt-4", 1000, 500)
+ # Should find pricing via the stripped model name
+ assert result["pricing_used"] is not None
+
+ def test_local_model_returns_zero(self):
+ """Local models (ollama) should return zero cost."""
+ calc = CostCalculator()
+ result = calc.calculate_cost_sync("ollama", 5000, 3000)
+ assert result["total_cost"] == 0.0
+ assert result["pricing_used"] is not None
+
+ def test_cached_pricing_used_first(self):
+ """Cached pricing is used before static fallback."""
+ calc = CostCalculator()
+ calc.cache.set_model_pricing(
+ "custom-model", {"prompt": 0.01, "completion": 0.02}
+ )
+ result = calc.calculate_cost_sync("custom-model", 1000, 1000)
+ assert result["prompt_cost"] == pytest.approx(0.01, rel=1e-4)
+ assert result["completion_cost"] == pytest.approx(0.02, rel=1e-4)
+
+
+class TestCalculateCostAsync:
+ """Tests for async cost calculation."""
+
+ @pytest.mark.asyncio
+ async def test_calculate_cost_no_pricing_returns_zero(self):
+ """When no pricing found, returns zero with error message."""
+ calc = CostCalculator()
+ result = await calc.calculate_cost("nonexistent-model", 1000, 500)
+ assert result["total_cost"] == 0.0
+ assert "error" in result
+
+ @pytest.mark.asyncio
+ async def test_calculate_cost_with_cached_pricing(self):
+ """Uses cached pricing when available."""
+ calc = CostCalculator()
+ calc.cache.set(
+ "model:test-model", {"prompt": 0.005, "completion": 0.01}
+ )
+ result = await calc.calculate_cost("test-model", 2000, 1000)
+ assert result["prompt_cost"] == pytest.approx(0.01, rel=1e-4)
+ assert result["completion_cost"] == pytest.approx(0.01, rel=1e-4)
+
+ @pytest.mark.asyncio
+ async def test_calculate_cost_with_provider(self):
+ """Provider-prefixed cache key is used."""
+ calc = CostCalculator()
+ calc.cache.set(
+ "model:openai:gpt-4", {"prompt": 0.03, "completion": 0.06}
+ )
+ result = await calc.calculate_cost(
+ "gpt-4", 1000, 1000, provider="openai"
+ )
+ assert result["prompt_cost"] == pytest.approx(0.03, rel=1e-4)
+
+
+class TestCalculateBatchCosts:
+ """Tests for batch cost calculation."""
+
+ @pytest.mark.asyncio
+ async def test_empty_batch_returns_empty(self):
+ """Empty usage records returns empty list."""
+ calc = CostCalculator()
+ result = await calc.calculate_batch_costs([])
+ assert result == []
+
+ @pytest.mark.asyncio
+ async def test_batch_with_error_records_still_returns_all(self):
+ """Records that fail still get zero-cost entries."""
+ calc = CostCalculator()
+ records = [
+ {
+ "model_name": "nonexistent",
+ "prompt_tokens": 100,
+ "completion_tokens": 50,
+ },
+ ]
+ result = await calc.calculate_batch_costs(records)
+ assert len(result) == 1
+ assert result[0]["total_cost"] == 0.0
+
+
+class TestGetResearchCostSummary:
+ """Tests for research cost summary aggregation."""
+
+ @pytest.mark.asyncio
+ async def test_empty_records_returns_zero_summary(self):
+ """Empty records return zero-value summary."""
+ calc = CostCalculator()
+ result = await calc.get_research_cost_summary([])
+ assert result["total_cost"] == 0.0
+ assert result["total_calls"] == 0
+ assert result["avg_cost_per_call"] == 0.0
+
+ @pytest.mark.asyncio
+ async def test_summary_aggregates_multiple_models(self):
+ """Summary aggregates costs across different models."""
+ calc = CostCalculator()
+ calc.cache.set("model:gpt-4", {"prompt": 0.03, "completion": 0.06})
+ calc.cache.set(
+ "model:gpt-3.5-turbo", {"prompt": 0.001, "completion": 0.002}
+ )
+
+ records = [
+ {
+ "model_name": "gpt-4",
+ "prompt_tokens": 1000,
+ "completion_tokens": 500,
+ },
+ {
+ "model_name": "gpt-3.5-turbo",
+ "prompt_tokens": 2000,
+ "completion_tokens": 1000,
+ },
+ ]
+ result = await calc.get_research_cost_summary(records)
+
+ assert result["total_calls"] == 2
+ assert result["total_tokens"] == 4500
+ assert "model_breakdown" in result
+ assert "gpt-4" in result["model_breakdown"]
+ assert "gpt-3.5-turbo" in result["model_breakdown"]