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 ~150 new tests for Phase 3 coverage expansion

LearningCircuit1615eba2a781
diff --git a/tests/benchmarks/efficiency/__init__.py b/tests/benchmarks/efficiency/__init__.py
new file mode 100644
index 0000000000..a095baff80
--- /dev/null
+++ b/tests/benchmarks/efficiency/__init__.py
@@ -0,0 +1 @@
+"""Tests for benchmarks efficiency module."""
diff --git a/tests/benchmarks/efficiency/test_speed_profiler.py b/tests/benchmarks/efficiency/test_speed_profiler.py
new file mode 100644
index 0000000000..49e27549af
--- /dev/null
+++ b/tests/benchmarks/efficiency/test_speed_profiler.py
@@ -0,0 +1,548 @@
+"""
+Tests for benchmarks/efficiency/speed_profiler.py
+
+Tests cover:
+- SpeedProfiler initialization
+- Session start/stop
+- Timer management (start, stop, context manager)
+- Timing retrieval and summary
+- time_function decorator
+"""
+
+import time
+from unittest.mock import patch
+
+
+class TestSpeedProfilerInit:
+ """Tests for SpeedProfiler initialization."""
+
+ def test_init_creates_empty_timings(self):
+ """Test that initialization creates empty timings dict."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+
+ assert profiler.timings == {}
+
+ def test_init_creates_empty_current_timers(self):
+ """Test that initialization creates empty current_timers dict."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+
+ assert profiler.current_timers == {}
+
+ def test_init_total_start_time_is_none(self):
+ """Test that total_start_time is None on init."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+
+ assert profiler.total_start_time is None
+
+ def test_init_total_end_time_is_none(self):
+ """Test that total_end_time is None on init."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+
+ assert profiler.total_end_time is None
+
+
+class TestSpeedProfilerStartStop:
+ """Tests for session start/stop."""
+
+ def test_start_sets_total_start_time(self):
+ """Test that start() sets total_start_time."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+ before = time.time()
+ profiler.start()
+ after = time.time()
+
+ assert profiler.total_start_time is not None
+ assert before <= profiler.total_start_time <= after
+
+ def test_start_clears_timings(self):
+ """Test that start() clears any existing timings."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+ profiler.timings = {"old_timer": {"total": 1.0}}
+ profiler.current_timers = {"running": time.time()}
+
+ profiler.start()
+
+ assert profiler.timings == {}
+ assert profiler.current_timers == {}
+
+ def test_stop_sets_total_end_time(self):
+ """Test that stop() sets total_end_time."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+ profiler.start()
+ before = time.time()
+ profiler.stop()
+ after = time.time()
+
+ assert profiler.total_end_time is not None
+ assert before <= profiler.total_end_time <= after
+
+ def test_stop_stops_running_timers(self):
+ """Test that stop() stops any running timers."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+ profiler.start()
+ profiler.start_timer("running_timer")
+
+ assert "running_timer" in profiler.current_timers
+
+ profiler.stop()
+
+ assert "running_timer" not in profiler.current_timers
+ assert "running_timer" in profiler.timings
+
+ def test_stop_records_total_duration(self):
+ """Test that stop() allows calculating total duration."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+ profiler.start()
+ time.sleep(0.01) # Small delay
+ profiler.stop()
+
+ duration = profiler.total_end_time - profiler.total_start_time
+ assert duration >= 0.01
+
+
+class TestSpeedProfilerTimers:
+ """Tests for timer management."""
+
+ def test_start_timer_adds_to_current_timers(self):
+ """Test that start_timer adds timer to current_timers."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+ before = time.time()
+ profiler.start_timer("my_timer")
+ after = time.time()
+
+ assert "my_timer" in profiler.current_timers
+ assert before <= profiler.current_timers["my_timer"] <= after
+
+ def test_start_timer_restarts_existing_timer(self):
+ """Test that starting an existing timer restarts it."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+ profiler.start_timer("my_timer")
+ old_time = profiler.current_timers["my_timer"]
+
+ time.sleep(0.01)
+ profiler.start_timer("my_timer")
+ new_time = profiler.current_timers["my_timer"]
+
+ assert new_time > old_time
+
+ def test_stop_timer_removes_from_current_timers(self):
+ """Test that stop_timer removes from current_timers."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+ profiler.start_timer("my_timer")
+ profiler.stop_timer("my_timer")
+
+ assert "my_timer" not in profiler.current_timers
+
+ def test_stop_timer_adds_to_timings(self):
+ """Test that stop_timer adds timing data."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+ profiler.start_timer("my_timer")
+ time.sleep(0.01)
+ profiler.stop_timer("my_timer")
+
+ assert "my_timer" in profiler.timings
+ assert profiler.timings["my_timer"]["count"] == 1
+ assert profiler.timings["my_timer"]["total"] >= 0.01
+
+ def test_stop_timer_accumulates_count(self):
+ """Test that multiple timer runs accumulate count."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+
+ for _ in range(3):
+ profiler.start_timer("my_timer")
+ profiler.stop_timer("my_timer")
+
+ assert profiler.timings["my_timer"]["count"] == 3
+
+ def test_stop_timer_tracks_min_max(self):
+ """Test that timer tracks min and max values."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+
+ # First run
+ profiler.start_timer("my_timer")
+ time.sleep(0.01)
+ profiler.stop_timer("my_timer")
+
+ # Second run
+ profiler.start_timer("my_timer")
+ time.sleep(0.02)
+ profiler.stop_timer("my_timer")
+
+ assert (
+ profiler.timings["my_timer"]["min"]
+ < profiler.timings["my_timer"]["max"]
+ )
+
+ def test_stop_timer_not_started_does_nothing(self):
+ """Test that stopping a non-existent timer does nothing."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+ profiler.stop_timer("nonexistent")
+
+ assert "nonexistent" not in profiler.timings
+
+ def test_timer_context_manager_starts_and_stops(self):
+ """Test timer context manager starts and stops timer."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+
+ with profiler.timer("context_timer"):
+ assert "context_timer" in profiler.current_timers
+
+ assert "context_timer" not in profiler.current_timers
+ assert "context_timer" in profiler.timings
+
+ def test_timer_context_manager_records_time(self):
+ """Test timer context manager records elapsed time."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+
+ with profiler.timer("context_timer"):
+ time.sleep(0.01)
+
+ assert profiler.timings["context_timer"]["total"] >= 0.01
+
+
+class TestSpeedProfilerGetTimings:
+ """Tests for timing retrieval."""
+
+ def test_get_timings_returns_copy(self):
+ """Test that get_timings returns a copy of timings."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+ profiler.start_timer("test")
+ profiler.stop_timer("test")
+
+ result = profiler.get_timings()
+ result["modified"] = True
+
+ assert "modified" not in profiler.timings
+
+ def test_get_timings_calculates_averages(self):
+ """Test that get_timings calculates averages."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+
+ for _ in range(4):
+ profiler.start_timer("test")
+ profiler.stop_timer("test")
+
+ result = profiler.get_timings()
+
+ assert "avg" in result["test"]
+ expected_avg = result["test"]["total"] / result["test"]["count"]
+ assert abs(result["test"]["avg"] - expected_avg) < 0.0001
+
+ def test_get_timings_includes_total_duration(self):
+ """Test that get_timings includes total session duration."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+ profiler.start()
+ time.sleep(0.01)
+ profiler.stop()
+
+ result = profiler.get_timings()
+
+ assert "total" in result
+ assert result["total"]["total"] >= 0.01
+
+ def test_get_timings_empty_when_no_timers(self):
+ """Test that get_timings returns empty dict when no timers used."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+
+ result = profiler.get_timings()
+
+ assert result == {}
+
+
+class TestSpeedProfilerGetSummary:
+ """Tests for summary generation."""
+
+ def test_get_summary_includes_total_duration(self):
+ """Test that summary includes total_duration."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+ profiler.start()
+ time.sleep(0.01)
+ profiler.stop()
+
+ summary = profiler.get_summary()
+
+ assert "total_duration" in summary
+ assert summary["total_duration"] >= 0.01
+
+ def test_get_summary_calculates_percentages(self):
+ """Test that summary calculates component percentages."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+ profiler.start()
+
+ with profiler.timer("component"):
+ time.sleep(0.01)
+
+ profiler.stop()
+
+ summary = profiler.get_summary()
+
+ assert "component_percent" in summary
+ assert 0 <= summary["component_percent"] <= 100
+
+ def test_get_summary_includes_per_operation_times(self):
+ """Test that summary includes per-operation times."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+
+ for _ in range(3):
+ profiler.start_timer("op")
+ profiler.stop_timer("op")
+
+ summary = profiler.get_summary()
+
+ assert "op_per_operation" in summary
+
+ def test_get_summary_handles_zero_duration(self):
+ """Test that summary handles zero total duration gracefully."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+ profiler.start_timer("test")
+ profiler.stop_timer("test")
+
+ # Don't call start/stop, so total_duration comes from sum of timers
+ summary = profiler.get_summary()
+
+ # Should not raise division by zero
+ assert "total_duration" in summary
+
+
+class TestSpeedProfilerPrintSummary:
+ """Tests for print_summary."""
+
+ def test_print_summary_outputs_header(self, capsys):
+ """Test that print_summary outputs header."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+ profiler.start()
+ profiler.stop()
+
+ profiler.print_summary()
+
+ captured = capsys.readouterr()
+ assert "SPEED PROFILE SUMMARY" in captured.out
+
+ def test_print_summary_shows_total_time(self, capsys):
+ """Test that print_summary shows total execution time."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+ profiler.start()
+ time.sleep(0.01)
+ profiler.stop()
+
+ profiler.print_summary()
+
+ captured = capsys.readouterr()
+ assert "Total execution time:" in captured.out
+
+
+class TestTimeFunctionDecorator:
+ """Tests for time_function decorator."""
+
+ def test_time_function_returns_result(self):
+ """Test that decorated function returns correct result."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ time_function,
+ )
+
+ @time_function
+ def add(a, b):
+ return a + b
+
+ result = add(2, 3)
+
+ assert result == 5
+
+ def test_time_function_logs_execution_time(self):
+ """Test that decorator logs execution time."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ time_function,
+ )
+
+ @time_function
+ def slow_function():
+ time.sleep(0.01)
+ return "done"
+
+ with patch(
+ "local_deep_research.benchmarks.efficiency.speed_profiler.logger"
+ ) as mock_logger:
+ slow_function()
+
+ mock_logger.info.assert_called_once()
+ call_args = mock_logger.info.call_args[0][0]
+ assert "slow_function" in call_args
+ assert "seconds" in call_args
+
+ def test_time_function_preserves_args_kwargs(self):
+ """Test that decorator preserves function arguments."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ time_function,
+ )
+
+ @time_function
+ def greet(name, greeting="Hello"):
+ return f"{greeting}, {name}!"
+
+ result = greet("World", greeting="Hi")
+
+ assert result == "Hi, World!"
+
+
+class TestSpeedProfilerTimingData:
+ """Tests for timing data structure."""
+
+ def test_timing_data_includes_starts_list(self):
+ """Test that timing data includes list of start times."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+
+ for _ in range(3):
+ profiler.start_timer("test")
+ profiler.stop_timer("test")
+
+ assert "starts" in profiler.timings["test"]
+ assert len(profiler.timings["test"]["starts"]) == 3
+
+ def test_timing_data_includes_durations_list(self):
+ """Test that timing data includes list of durations."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+
+ for _ in range(3):
+ profiler.start_timer("test")
+ profiler.stop_timer("test")
+
+ assert "durations" in profiler.timings["test"]
+ assert len(profiler.timings["test"]["durations"]) == 3
+
+ def test_timing_data_total_equals_sum_of_durations(self):
+ """Test that total equals sum of individual durations."""
+ from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+ )
+
+ profiler = SpeedProfiler()
+
+ for _ in range(3):
+ profiler.start_timer("test")
+ time.sleep(0.01)
+ profiler.stop_timer("test")
+
+ total = profiler.timings["test"]["total"]
+ sum_durations = sum(profiler.timings["test"]["durations"])
+
+ assert abs(total - sum_durations) < 0.0001
diff --git a/tests/benchmarks/test_cli.py b/tests/benchmarks/test_cli.py
new file mode 100644
index 0000000000..7d079e5cd3
--- /dev/null
+++ b/tests/benchmarks/test_cli.py
@@ -0,0 +1,643 @@
+"""
+Tests for benchmarks/cli (benchmark_commands.py)
+
+Tests cover:
+- setup_benchmark_parser - argument parsing for benchmark commands
+- run_simpleqa_cli - SimpleQA benchmark execution
+- run_browsecomp_cli - BrowseComp benchmark execution
+- list_benchmarks_cli - listing benchmarks
+- main function behavior
+"""
+
+import argparse
+import sys
+from unittest.mock import patch, MagicMock
+import pytest
+
+
+def mock_data_directory(tmp_path):
+ """Mock the data directory to use a temporary path."""
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.get_data_directory"
+ ) as mock:
+ mock.return_value = tmp_path
+ yield tmp_path
+
+
+class TestSetupBenchmarkParser:
+ """Tests for setup_benchmark_parser function."""
+
+ def test_simpleqa_command_exists(self, mock_data_directory):
+ """Test that simpleqa command is added to parser."""
+ 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"])
+ assert args.command == "simpleqa"
+
+ def test_browsecomp_command_exists(self, mock_data_directory):
+ """Test that browsecomp command is added to parser."""
+ 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"])
+ assert args.command == "browsecomp"
+
+ def test_list_command_exists(self, mock_data_directory):
+ """Test that list command is added to parser."""
+ 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(["list"])
+ assert args.command == "list"
+
+ def test_compare_command_exists(self, mock_data_directory):
+ """Test that compare command is added to parser."""
+ 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(["compare"])
+ assert args.command == "compare"
+
+ def test_simpleqa_default_examples(self, mock_data_directory):
+ """Test that simpleqa has default examples of 100."""
+ 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"])
+ assert args.examples == 100
+
+ def test_simpleqa_custom_examples(self, mock_data_directory):
+ """Test that simpleqa accepts custom examples."""
+ 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", "--examples", "50"])
+ assert args.examples == 50
+
+ def test_simpleqa_default_iterations(self, mock_data_directory):
+ """Test that simpleqa has default iterations of 3."""
+ 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"])
+ assert args.iterations == 3
+
+ def test_simpleqa_custom_iterations(self, mock_data_directory):
+ """Test that simpleqa accepts custom iterations."""
+ 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", "--iterations", "5"])
+ assert args.iterations == 5
+
+ def test_simpleqa_default_questions(self, mock_data_directory):
+ """Test that simpleqa has default questions of 3."""
+ 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"])
+ assert args.questions == 3
+
+ def test_simpleqa_default_search_tool(self, mock_data_directory):
+ """Test that simpleqa has default search_tool of searxng."""
+ 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"])
+ assert args.search_tool == "searxng"
+
+ def test_simpleqa_custom_search_tool(self, mock_data_directory):
+ """Test that simpleqa accepts custom search_tool."""
+ 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", "--search-tool", "duckduckgo"])
+ assert args.search_tool == "duckduckgo"
+
+ def test_simpleqa_human_eval_flag(self, mock_data_directory):
+ """Test that simpleqa accepts human-eval flag."""
+ 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", "--human-eval"])
+ assert args.human_eval is True
+
+ def test_simpleqa_no_eval_flag(self, mock_data_directory):
+ """Test that simpleqa accepts no-eval flag."""
+ 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", "--no-eval"])
+ assert args.no_eval is True
+
+ def test_simpleqa_custom_output_dir(self, mock_data_directory):
+ """Test that simpleqa accepts custom output-dir."""
+ 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", "--output-dir", "/custom/path"])
+ assert args.output_dir == "/custom/path"
+
+ def test_simpleqa_search_model_option(self, mock_data_directory):
+ """Test that simpleqa accepts search-model option."""
+ 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", "--search-model", "gpt-4"])
+ assert args.search_model == "gpt-4"
+
+ def test_simpleqa_search_provider_option(self, mock_data_directory):
+ """Test that simpleqa accepts search-provider option."""
+ 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", "--search-provider", "openai"])
+ assert args.search_provider == "openai"
+
+ def test_simpleqa_search_strategy_option(self, mock_data_directory):
+ """Test that simpleqa accepts search-strategy option."""
+ 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", "--search-strategy", "parallel"])
+ assert args.search_strategy == "parallel"
+
+ def test_simpleqa_default_search_strategy(self, mock_data_directory):
+ """Test that simpleqa has default search-strategy of source_based."""
+ 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"])
+ assert args.search_strategy == "source_based"
+
+ def test_compare_default_dataset(self, mock_data_directory):
+ """Test that compare has default dataset of simpleqa."""
+ 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(["compare"])
+ assert args.dataset == "simpleqa"
+
+ def test_compare_custom_dataset(self, mock_data_directory):
+ """Test that compare accepts custom dataset."""
+ 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(["compare", "--dataset", "browsecomp"])
+ assert args.dataset == "browsecomp"
+
+ def test_compare_default_examples(self, mock_data_directory):
+ """Test that compare has default examples of 20."""
+ 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(["compare"])
+ assert args.examples == 20
+
+
+class TestRunSimpleqaCli:
+ """Tests for run_simpleqa_cli function."""
+
+ def test_run_simpleqa_calls_benchmark(self, mock_data_directory):
+ """Test that run_simpleqa_cli calls run_simpleqa_benchmark."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ run_simpleqa_cli,
+ )
+
+ args = MagicMock()
+ args.examples = 10
+ args.iterations = 2
+ args.questions = 2
+ args.search_tool = "searxng"
+ args.output_dir = "/tmp/output"
+ args.human_eval = False
+ args.no_eval = False
+ args.custom_dataset = None
+ args.eval_model = None
+ args.eval_provider = None
+ args.search_model = None
+ args.search_provider = None
+ args.endpoint_url = None
+ args.search_strategy = "source_based"
+
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.run_simpleqa_benchmark"
+ ) as mock_benchmark:
+ mock_benchmark.return_value = {
+ "metrics": {
+ "accuracy": 0.8,
+ "correct": 8,
+ "average_processing_time": 5.0,
+ },
+ "total_examples": 10,
+ "report_path": "/tmp/report.html",
+ }
+
+ run_simpleqa_cli(args)
+
+ mock_benchmark.assert_called_once()
+
+ def test_run_simpleqa_passes_search_config(self, mock_data_directory):
+ """Test that run_simpleqa_cli passes search config correctly."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ run_simpleqa_cli,
+ )
+
+ args = MagicMock()
+ args.examples = 10
+ args.iterations = 5
+ args.questions = 4
+ args.search_tool = "duckduckgo"
+ args.output_dir = "/tmp/output"
+ args.human_eval = False
+ args.no_eval = False
+ args.custom_dataset = None
+ args.eval_model = None
+ args.eval_provider = None
+ args.search_model = "gpt-4"
+ args.search_provider = "openai"
+ args.endpoint_url = None
+ args.search_strategy = "parallel"
+
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.run_simpleqa_benchmark"
+ ) as mock_benchmark:
+ mock_benchmark.return_value = {"metrics": {}, "total_examples": 10}
+
+ run_simpleqa_cli(args)
+
+ call_kwargs = mock_benchmark.call_args[1]
+ assert call_kwargs["search_config"]["iterations"] == 5
+ assert call_kwargs["search_config"]["questions_per_iteration"] == 4
+ assert call_kwargs["search_config"]["search_tool"] == "duckduckgo"
+ assert call_kwargs["search_config"]["model_name"] == "gpt-4"
+ assert call_kwargs["search_config"]["provider"] == "openai"
+
+
+class TestRunBrowsecompCli:
+ """Tests for run_browsecomp_cli function."""
+
+ def test_run_browsecomp_calls_benchmark(self, mock_data_directory):
+ """Test that run_browsecomp_cli calls run_browsecomp_benchmark."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ run_browsecomp_cli,
+ )
+
+ args = MagicMock()
+ args.examples = 10
+ args.iterations = 2
+ args.questions = 2
+ args.search_tool = "searxng"
+ args.output_dir = "/tmp/output"
+ args.human_eval = False
+ args.no_eval = False
+ args.custom_dataset = None
+ args.eval_model = None
+ args.eval_provider = None
+ args.search_model = None
+ args.search_provider = None
+ args.endpoint_url = None
+ args.search_strategy = "source_based"
+
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.run_browsecomp_benchmark"
+ ) as mock_benchmark:
+ mock_benchmark.return_value = {
+ "metrics": {
+ "accuracy": 0.7,
+ "correct": 7,
+ "average_processing_time": 6.0,
+ },
+ "total_examples": 10,
+ "report_path": "/tmp/report.html",
+ }
+
+ run_browsecomp_cli(args)
+
+ mock_benchmark.assert_called_once()
+
+
+class TestListBenchmarksCli:
+ """Tests for list_benchmarks_cli function."""
+
+ def test_list_benchmarks_calls_get_available_datasets(
+ self, mock_data_directory, capsys
+ ):
+ """Test that list_benchmarks_cli calls get_available_datasets."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ list_benchmarks_cli,
+ )
+
+ args = MagicMock()
+
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.get_available_datasets"
+ ) as mock_datasets:
+ mock_datasets.return_value = [
+ {
+ "id": "simpleqa",
+ "name": "SimpleQA",
+ "description": "Simple QA benchmark",
+ "url": "http://example.com",
+ }
+ ]
+
+ list_benchmarks_cli(args)
+
+ mock_datasets.assert_called_once()
+
+ def test_list_benchmarks_prints_datasets(self, mock_data_directory, capsys):
+ """Test that list_benchmarks_cli prints dataset information."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ list_benchmarks_cli,
+ )
+
+ args = MagicMock()
+
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.get_available_datasets"
+ ) as mock_datasets:
+ mock_datasets.return_value = [
+ {
+ "id": "simpleqa",
+ "name": "SimpleQA",
+ "description": "Simple QA benchmark",
+ "url": "http://example.com",
+ }
+ ]
+
+ list_benchmarks_cli(args)
+
+ captured = capsys.readouterr()
+ assert "simpleqa" in captured.out
+ assert "SimpleQA" in captured.out
+
+
+class TestMain:
+ """Tests for main function."""
+
+ def test_main_requires_command(self, mock_data_directory):
+ """Test that main requires a command."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import main
+
+ with patch.object(sys, "argv", ["ldr-benchmark"]):
+ with pytest.raises(SystemExit):
+ main()
+
+ def test_main_with_list_command(self, mock_data_directory, capsys):
+ """Test that main handles list command."""
+ 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_datasets:
+ mock_datasets.return_value = [
+ {
+ "id": "test",
+ "name": "Test",
+ "description": "Test",
+ "url": "http://test.com",
+ }
+ ]
+ main()
+
+ captured = capsys.readouterr()
+ assert "Available Benchmarks" in captured.out
+
+
+class TestSearchConfigBuilding:
+ """Tests for search config building logic."""
+
+ def test_search_config_includes_basic_params(self, mock_data_directory):
+ """Test that search config includes basic parameters."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ run_simpleqa_cli,
+ )
+
+ args = MagicMock()
+ args.examples = 10
+ args.iterations = 3
+ args.questions = 2
+ args.search_tool = "searxng"
+ args.output_dir = "/tmp/output"
+ args.human_eval = False
+ args.no_eval = False
+ args.custom_dataset = None
+ args.eval_model = None
+ args.eval_provider = None
+ args.search_model = None
+ args.search_provider = None
+ args.endpoint_url = None
+ args.search_strategy = "standard"
+
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.run_simpleqa_benchmark"
+ ) as mock_benchmark:
+ mock_benchmark.return_value = {"metrics": {}, "total_examples": 10}
+
+ run_simpleqa_cli(args)
+
+ call_kwargs = mock_benchmark.call_args[1]
+ assert "search_config" in call_kwargs
+ assert call_kwargs["search_config"]["iterations"] == 3
+ assert call_kwargs["search_config"]["questions_per_iteration"] == 2
+ assert call_kwargs["search_config"]["search_tool"] == "searxng"
+
+ def test_evaluation_config_set_when_eval_model_provided(
+ self, mock_data_directory
+ ):
+ """Test that evaluation config is set when eval_model is provided."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ run_simpleqa_cli,
+ )
+
+ args = MagicMock()
+ args.examples = 10
+ args.iterations = 3
+ args.questions = 2
+ args.search_tool = "searxng"
+ args.output_dir = "/tmp/output"
+ args.human_eval = False
+ args.no_eval = False
+ args.custom_dataset = None
+ args.eval_model = "gpt-4"
+ args.eval_provider = "openai"
+ args.search_model = None
+ args.search_provider = None
+ args.endpoint_url = None
+ args.search_strategy = "standard"
+
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.run_simpleqa_benchmark"
+ ) as mock_benchmark:
+ mock_benchmark.return_value = {"metrics": {}, "total_examples": 10}
+
+ run_simpleqa_cli(args)
+
+ call_kwargs = mock_benchmark.call_args[1]
+ assert call_kwargs["evaluation_config"] is not None
+ assert call_kwargs["evaluation_config"]["model_name"] == "gpt-4"
+ assert call_kwargs["evaluation_config"]["provider"] == "openai"
+
+ def test_evaluation_config_none_when_no_eval_args(
+ self, mock_data_directory
+ ):
+ """Test that evaluation config is None when no eval args provided."""
+ from local_deep_research.benchmarks.cli.benchmark_commands import (
+ run_simpleqa_cli,
+ )
+
+ args = MagicMock()
+ args.examples = 10
+ args.iterations = 3
+ args.questions = 2
+ args.search_tool = "searxng"
+ args.output_dir = "/tmp/output"
+ args.human_eval = False
+ args.no_eval = False
+ args.custom_dataset = None
+ args.eval_model = None
+ args.eval_provider = None
+ args.search_model = None
+ args.search_provider = None
+ args.endpoint_url = None
+ args.search_strategy = "standard"
+
+ with patch(
+ "local_deep_research.benchmarks.cli.benchmark_commands.run_simpleqa_benchmark"
+ ) as mock_benchmark:
+ mock_benchmark.return_value = {"metrics": {}, "total_examples": 10}
+
+ run_simpleqa_cli(args)
+
+ call_kwargs = mock_benchmark.call_args[1]
+ assert call_kwargs["evaluation_config"] is None
diff --git a/tests/benchmarks/test_resource_monitor.py b/tests/benchmarks/test_resource_monitor.py
index e18098b895..92d78d8661 100644
--- a/tests/benchmarks/test_resource_monitor.py
+++ b/tests/benchmarks/test_resource_monitor.py
@@ -465,3 +465,480 @@ class TestCheckSystemResources:
assert "disk_total_gb" in result
else:
assert result["available"] is False
+
+
+class TestResourceMonitorSamplingInterval:
+ """Tests for sampling interval configuration."""
+
+ def test_default_sampling_interval(self):
+ """Test default sampling interval is 1.0 seconds."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor()
+
+ assert monitor.sampling_interval == 1.0
+
+ def test_custom_sampling_interval(self):
+ """Test custom sampling interval is stored correctly."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor(sampling_interval=0.25)
+
+ assert monitor.sampling_interval == 0.25
+
+ def test_very_small_sampling_interval(self):
+ """Test very small sampling interval is accepted."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor(sampling_interval=0.01)
+
+ assert monitor.sampling_interval == 0.01
+
+
+class TestResourceMonitorTrackingOptions:
+ """Tests for process/system tracking options."""
+
+ def test_track_process_only(self):
+ """Test tracking only process resources."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor(track_process=True, track_system=False)
+
+ assert monitor.track_process is True
+ assert monitor.track_system is False
+
+ def test_track_system_only(self):
+ """Test tracking only system resources."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor(track_process=False, track_system=True)
+
+ assert monitor.track_process is False
+ assert monitor.track_system is True
+
+ def test_track_both(self):
+ """Test tracking both process and system resources."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor(track_process=True, track_system=True)
+
+ assert monitor.track_process is True
+ assert monitor.track_system is True
+
+ def test_track_neither(self):
+ """Test tracking neither process nor system resources."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor(track_process=False, track_system=False)
+
+ assert monitor.track_process is False
+ assert monitor.track_system is False
+
+
+class TestResourceMonitorMemoryCalculations:
+ """Tests for memory calculation logic."""
+
+ def test_memory_rss_conversion_to_mb(self):
+ """Test that memory RSS is correctly converted to MB."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor()
+ monitor.start_time = time.time() - 10
+ monitor.end_time = time.time()
+ # 100 MB in bytes
+ monitor.process_data = [
+ {
+ "timestamp": time.time(),
+ "cpu_percent": 50.0,
+ "memory_rss": 104_857_600, # 100 MB in bytes
+ "num_threads": 4,
+ },
+ ]
+
+ stats = monitor.get_process_stats()
+
+ # Should be converted to MB
+ assert 99 < stats["memory_max_mb"] < 101
+
+ def test_memory_stats_min_max_avg(self):
+ """Test memory min/max/avg calculations."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor()
+ monitor.start_time = time.time() - 10
+ monitor.end_time = time.time()
+ monitor.process_data = [
+ {
+ "timestamp": time.time(),
+ "cpu_percent": 50.0,
+ "memory_rss": 50_000_000, # ~47.68 MB
+ "num_threads": 4,
+ },
+ {
+ "timestamp": time.time(),
+ "cpu_percent": 50.0,
+ "memory_rss": 100_000_000, # ~95.37 MB
+ "num_threads": 4,
+ },
+ {
+ "timestamp": time.time(),
+ "cpu_percent": 50.0,
+ "memory_rss": 150_000_000, # ~143.05 MB
+ "num_threads": 4,
+ },
+ ]
+
+ stats = monitor.get_process_stats()
+
+ assert (
+ stats["memory_min_mb"]
+ < stats["memory_avg_mb"]
+ < stats["memory_max_mb"]
+ )
+
+
+class TestResourceMonitorCPUCalculations:
+ """Tests for CPU calculation logic."""
+
+ def test_cpu_stats_with_varying_values(self):
+ """Test CPU stats with varying values."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor()
+ monitor.start_time = time.time() - 10
+ monitor.end_time = time.time()
+ monitor.process_data = [
+ {
+ "timestamp": time.time(),
+ "cpu_percent": 10.0,
+ "memory_rss": 100_000_000,
+ "num_threads": 4,
+ },
+ {
+ "timestamp": time.time(),
+ "cpu_percent": 50.0,
+ "memory_rss": 100_000_000,
+ "num_threads": 4,
+ },
+ {
+ "timestamp": time.time(),
+ "cpu_percent": 90.0,
+ "memory_rss": 100_000_000,
+ "num_threads": 4,
+ },
+ ]
+
+ stats = monitor.get_process_stats()
+
+ assert stats["cpu_min"] == 10.0
+ assert stats["cpu_max"] == 90.0
+ assert stats["cpu_avg"] == 50.0
+
+
+class TestResourceMonitorSystemStats:
+ """Tests for system stats calculations."""
+
+ def test_system_disk_stats(self):
+ """Test system disk stats calculation."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor()
+ monitor.start_time = time.time() - 10
+ monitor.end_time = time.time()
+ monitor.system_data = [
+ {
+ "timestamp": time.time(),
+ "cpu_percent": 30.0,
+ "memory_percent": 50.0,
+ "disk_percent": 40.0,
+ "memory_total": 16_000_000_000,
+ "disk_total": 500_000_000_000,
+ },
+ {
+ "timestamp": time.time(),
+ "cpu_percent": 40.0,
+ "memory_percent": 55.0,
+ "disk_percent": 60.0,
+ "memory_total": 16_000_000_000,
+ "disk_total": 500_000_000_000,
+ },
+ ]
+
+ stats = monitor.get_system_stats()
+
+ assert stats["disk_min_percent"] == 40.0
+ assert stats["disk_max_percent"] == 60.0
+ assert stats["disk_avg_percent"] == 50.0
+
+ def test_system_memory_total_conversion(self):
+ """Test that system memory total is converted to GB."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor()
+ monitor.start_time = time.time() - 10
+ monitor.end_time = time.time()
+ # 16 GB in bytes
+ monitor.system_data = [
+ {
+ "timestamp": time.time(),
+ "cpu_percent": 30.0,
+ "memory_percent": 50.0,
+ "disk_percent": 40.0,
+ "memory_total": 17_179_869_184, # 16 GB
+ "disk_total": 500_000_000_000,
+ },
+ ]
+
+ stats = monitor.get_system_stats()
+
+ assert 15.9 < stats["memory_total_gb"] < 16.1
+
+
+class TestResourceMonitorCombinedStats:
+ """Additional tests for combined stats."""
+
+ def test_combined_stats_process_memory_percent(self):
+ """Test that combined stats calculates process memory percent."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor()
+ monitor.start_time = time.time() - 10
+ monitor.end_time = time.time()
+ # Process using 1GB of 16GB system memory
+ monitor.process_data = [
+ {
+ "timestamp": time.time(),
+ "cpu_percent": 50.0,
+ "memory_rss": 1_073_741_824, # 1 GB
+ "num_threads": 4,
+ },
+ ]
+ monitor.system_data = [
+ {
+ "timestamp": time.time(),
+ "cpu_percent": 30.0,
+ "memory_percent": 50.0,
+ "disk_percent": 40.0,
+ "memory_total": 17_179_869_184, # 16 GB
+ "disk_total": 500_000_000_000,
+ },
+ ]
+
+ stats = monitor.get_combined_stats()
+
+ # 1 GB / 16 GB = 6.25%
+ assert "process_memory_percent" in stats
+ assert 6.0 < stats["process_memory_percent"] < 6.5
+
+ def test_combined_stats_includes_duration(self):
+ """Test that combined stats includes duration."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor()
+ monitor.start_time = time.time() - 5.0
+ monitor.end_time = time.time()
+
+ stats = monitor.get_combined_stats()
+
+ assert "duration" in stats
+ assert 4.9 < stats["duration"] < 5.1
+
+
+class TestResourceMonitorExport:
+ """Tests for data export functionality."""
+
+ def test_export_data_includes_timestamps(self):
+ """Test that exported data includes timestamps."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor()
+ monitor.start_time = time.time() - 10
+ monitor.end_time = time.time()
+
+ data = monitor.export_data()
+
+ assert "start_time" in data
+ assert "end_time" in data
+ assert data["start_time"] is not None
+ assert data["end_time"] is not None
+
+ def test_export_data_includes_sampling_interval(self):
+ """Test that exported data includes sampling interval."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor(sampling_interval=0.5)
+
+ data = monitor.export_data()
+
+ assert data["sampling_interval"] == 0.5
+
+ def test_export_data_includes_empty_lists_when_no_data(self):
+ """Test that export returns empty lists when no data collected."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor()
+
+ data = monitor.export_data()
+
+ assert data["process_data"] == []
+ assert data["system_data"] == []
+
+
+class TestResourceMonitorEdgeCases:
+ """Edge case tests for ResourceMonitor."""
+
+ def test_stats_with_single_sample(self):
+ """Test stats calculation with single sample."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor()
+ monitor.start_time = time.time() - 1
+ monitor.end_time = time.time()
+ monitor.process_data = [
+ {
+ "timestamp": time.time(),
+ "cpu_percent": 50.0,
+ "memory_rss": 100_000_000,
+ "num_threads": 4,
+ },
+ ]
+
+ stats = monitor.get_process_stats()
+
+ # With single sample, min == max == avg
+ assert stats["cpu_min"] == stats["cpu_max"] == stats["cpu_avg"]
+
+ def test_duration_none_when_end_time_not_set(self):
+ """Test that duration is None when end_time not set."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor()
+ monitor.start_time = time.time()
+ monitor.end_time = None
+ monitor.process_data = [
+ {
+ "timestamp": time.time(),
+ "cpu_percent": 50.0,
+ "memory_rss": 100_000_000,
+ "num_threads": 4,
+ },
+ ]
+
+ stats = monitor.get_process_stats()
+
+ assert stats["duration"] is None
+
+ def test_thread_max_tracking(self):
+ """Test that max thread count is tracked correctly."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor()
+ monitor.start_time = time.time() - 10
+ monitor.end_time = time.time()
+ monitor.process_data = [
+ {
+ "timestamp": time.time(),
+ "cpu_percent": 50.0,
+ "memory_rss": 100_000_000,
+ "num_threads": 4,
+ },
+ {
+ "timestamp": time.time(),
+ "cpu_percent": 50.0,
+ "memory_rss": 100_000_000,
+ "num_threads": 8,
+ },
+ {
+ "timestamp": time.time(),
+ "cpu_percent": 50.0,
+ "memory_rss": 100_000_000,
+ "num_threads": 6,
+ },
+ ]
+
+ stats = monitor.get_process_stats()
+
+ assert stats["thread_max"] == 8
+
+ def test_print_summary_with_empty_data(self, capsys):
+ """Test print_summary handles empty data gracefully."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor()
+
+ # Should not raise
+ monitor.print_summary()
+
+ captured = capsys.readouterr()
+ assert "RESOURCE USAGE SUMMARY" in captured.out
+
+
+class TestResourceMonitorCanMonitorFlag:
+ """Tests for can_monitor flag behavior."""
+
+ def test_can_monitor_matches_psutil_available(self):
+ """Test that can_monitor matches PSUTIL_AVAILABLE."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ PSUTIL_AVAILABLE,
+ )
+
+ monitor = ResourceMonitor()
+
+ assert monitor.can_monitor == PSUTIL_AVAILABLE
+
+ def test_start_does_nothing_when_cannot_monitor(self):
+ """Test that start does nothing when can_monitor is False."""
+ from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+ )
+
+ monitor = ResourceMonitor()
+ monitor.can_monitor = False
+
+ monitor.start()
+
+ assert monitor.monitoring is False
+ assert monitor.start_time is None
diff --git a/tests/news/test_folder_manager.py b/tests/news/test_folder_manager.py
new file mode 100644
index 0000000000..3cea28330e
--- /dev/null
+++ b/tests/news/test_folder_manager.py
@@ -0,0 +1,591 @@
+"""
+Tests for news/folder_manager.py
+
+Tests cover:
+- FolderManager initialization
+- _sub_to_dict - subscription to dictionary conversion
+- update_subscription - update logic with refresh interval recalculation
+- get_subscription_stats - statistics calculation
+- Folder CRUD operations
+"""
+
+from datetime import datetime, timezone, timedelta
+from unittest.mock import MagicMock, patch
+
+
+class TestFolderManagerInit:
+ """Tests for FolderManager initialization."""
+
+ def test_init_stores_session(self):
+ """Test that initialization stores the session."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ manager = FolderManager(mock_session)
+
+ assert manager.session == mock_session
+
+
+class TestSubToDict:
+ """Tests for _sub_to_dict method."""
+
+ def test_sub_to_dict_includes_id(self):
+ """Test that _sub_to_dict includes the subscription id."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ manager = FolderManager(mock_session)
+
+ mock_sub = MagicMock()
+ mock_sub.id = "sub-123"
+ mock_sub.subscription_type = "search"
+ mock_sub.query_or_topic = "test query"
+ mock_sub.created_at = datetime.now(timezone.utc)
+ mock_sub.last_refresh = None
+ mock_sub.next_refresh = None
+ mock_sub.refresh_interval_minutes = 60
+ mock_sub.status = "active"
+
+ result = manager._sub_to_dict(mock_sub)
+
+ assert result["id"] == "sub-123"
+
+ def test_sub_to_dict_includes_type(self):
+ """Test that _sub_to_dict includes subscription type."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ manager = FolderManager(mock_session)
+
+ mock_sub = MagicMock()
+ mock_sub.id = "sub-123"
+ mock_sub.subscription_type = "topic"
+ mock_sub.query_or_topic = "AI News"
+ mock_sub.created_at = datetime.now(timezone.utc)
+ mock_sub.last_refresh = None
+ mock_sub.next_refresh = None
+ mock_sub.refresh_interval_minutes = 60
+ mock_sub.status = "active"
+
+ result = manager._sub_to_dict(mock_sub)
+
+ assert result["type"] == "topic"
+
+ def test_sub_to_dict_includes_query_or_topic(self):
+ """Test that _sub_to_dict includes query_or_topic."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ manager = FolderManager(mock_session)
+
+ mock_sub = MagicMock()
+ mock_sub.id = "sub-123"
+ mock_sub.subscription_type = "search"
+ mock_sub.query_or_topic = "machine learning news"
+ mock_sub.created_at = datetime.now(timezone.utc)
+ mock_sub.last_refresh = None
+ mock_sub.next_refresh = None
+ mock_sub.refresh_interval_minutes = 60
+ mock_sub.status = "active"
+
+ result = manager._sub_to_dict(mock_sub)
+
+ assert result["query_or_topic"] == "machine learning news"
+
+ def test_sub_to_dict_formats_created_at_iso(self):
+ """Test that _sub_to_dict formats created_at as ISO string."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ manager = FolderManager(mock_session)
+
+ created = datetime(2024, 1, 15, 10, 30, 0, tzinfo=timezone.utc)
+ mock_sub = MagicMock()
+ mock_sub.id = "sub-123"
+ mock_sub.subscription_type = "search"
+ mock_sub.query_or_topic = "test"
+ mock_sub.created_at = created
+ mock_sub.last_refresh = None
+ mock_sub.next_refresh = None
+ mock_sub.refresh_interval_minutes = 60
+ mock_sub.status = "active"
+
+ result = manager._sub_to_dict(mock_sub)
+
+ assert result["created_at"] == "2024-01-15T10:30:00+00:00"
+
+ def test_sub_to_dict_handles_none_created_at(self):
+ """Test that _sub_to_dict handles None created_at."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ manager = FolderManager(mock_session)
+
+ mock_sub = MagicMock()
+ mock_sub.id = "sub-123"
+ mock_sub.subscription_type = "search"
+ mock_sub.query_or_topic = "test"
+ mock_sub.created_at = None
+ mock_sub.last_refresh = None
+ mock_sub.next_refresh = None
+ mock_sub.refresh_interval_minutes = 60
+ mock_sub.status = "active"
+
+ result = manager._sub_to_dict(mock_sub)
+
+ assert result["created_at"] is None
+
+ def test_sub_to_dict_handles_none_last_refresh(self):
+ """Test that _sub_to_dict handles None last_refresh."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ manager = FolderManager(mock_session)
+
+ mock_sub = MagicMock()
+ mock_sub.id = "sub-123"
+ mock_sub.subscription_type = "search"
+ mock_sub.query_or_topic = "test"
+ mock_sub.created_at = datetime.now(timezone.utc)
+ mock_sub.last_refresh = None
+ mock_sub.next_refresh = None
+ mock_sub.refresh_interval_minutes = 60
+ mock_sub.status = "active"
+
+ result = manager._sub_to_dict(mock_sub)
+
+ assert result["last_refresh"] is None
+
+ def test_sub_to_dict_formats_last_refresh_iso(self):
+ """Test that _sub_to_dict formats last_refresh as ISO string."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ manager = FolderManager(mock_session)
+
+ last_refresh = datetime(2024, 1, 15, 12, 0, 0, tzinfo=timezone.utc)
+ mock_sub = MagicMock()
+ mock_sub.id = "sub-123"
+ mock_sub.subscription_type = "search"
+ mock_sub.query_or_topic = "test"
+ mock_sub.created_at = datetime.now(timezone.utc)
+ mock_sub.last_refresh = last_refresh
+ mock_sub.next_refresh = None
+ mock_sub.refresh_interval_minutes = 60
+ mock_sub.status = "active"
+
+ result = manager._sub_to_dict(mock_sub)
+
+ assert result["last_refresh"] == "2024-01-15T12:00:00+00:00"
+
+ def test_sub_to_dict_formats_next_refresh_iso(self):
+ """Test that _sub_to_dict formats next_refresh as ISO string."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ manager = FolderManager(mock_session)
+
+ next_refresh = datetime(2024, 1, 15, 13, 0, 0, tzinfo=timezone.utc)
+ mock_sub = MagicMock()
+ mock_sub.id = "sub-123"
+ mock_sub.subscription_type = "search"
+ mock_sub.query_or_topic = "test"
+ mock_sub.created_at = datetime.now(timezone.utc)
+ mock_sub.last_refresh = None
+ mock_sub.next_refresh = next_refresh
+ mock_sub.refresh_interval_minutes = 60
+ mock_sub.status = "active"
+
+ result = manager._sub_to_dict(mock_sub)
+
+ assert result["next_refresh"] == "2024-01-15T13:00:00+00:00"
+
+ def test_sub_to_dict_includes_refresh_interval_minutes(self):
+ """Test that _sub_to_dict includes refresh_interval_minutes."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ manager = FolderManager(mock_session)
+
+ mock_sub = MagicMock()
+ mock_sub.id = "sub-123"
+ mock_sub.subscription_type = "search"
+ mock_sub.query_or_topic = "test"
+ mock_sub.created_at = datetime.now(timezone.utc)
+ mock_sub.last_refresh = None
+ mock_sub.next_refresh = None
+ mock_sub.refresh_interval_minutes = 120
+ mock_sub.status = "active"
+
+ result = manager._sub_to_dict(mock_sub)
+
+ assert result["refresh_interval_minutes"] == 120
+
+ def test_sub_to_dict_includes_status(self):
+ """Test that _sub_to_dict includes status."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ manager = FolderManager(mock_session)
+
+ mock_sub = MagicMock()
+ mock_sub.id = "sub-123"
+ mock_sub.subscription_type = "search"
+ mock_sub.query_or_topic = "test"
+ mock_sub.created_at = datetime.now(timezone.utc)
+ mock_sub.last_refresh = None
+ mock_sub.next_refresh = None
+ mock_sub.refresh_interval_minutes = 60
+ mock_sub.status = "paused"
+
+ result = manager._sub_to_dict(mock_sub)
+
+ assert result["status"] == "paused"
+
+
+class TestUpdateSubscription:
+ """Tests for update_subscription method."""
+
+ def test_update_returns_none_for_nonexistent(self):
+ """Test that update_subscription returns None for nonexistent subscription."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = None
+ mock_session.query.return_value = mock_query
+
+ manager = FolderManager(mock_session)
+
+ result = manager.update_subscription("nonexistent-id", status="paused")
+
+ assert result is None
+
+ def test_update_changes_status(self):
+ """Test that update_subscription changes status."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ mock_sub = MagicMock()
+ mock_sub.id = "sub-123"
+ mock_sub.status = "active"
+ mock_sub.updated_at = None
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = mock_sub
+ mock_session.query.return_value = mock_query
+
+ manager = FolderManager(mock_session)
+
+ result = manager.update_subscription("sub-123", status="paused")
+
+ assert mock_sub.status == "paused"
+ assert result == mock_sub
+
+ def test_update_recalculates_next_refresh_with_last_refresh(self):
+ """Test that updating refresh_interval_minutes recalculates next_refresh based on last_refresh."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ mock_sub = MagicMock()
+ mock_sub.id = "sub-123"
+ mock_sub.last_refresh = datetime(
+ 2024, 1, 15, 10, 0, 0, tzinfo=timezone.utc
+ )
+ mock_sub.next_refresh = datetime(
+ 2024, 1, 15, 11, 0, 0, tzinfo=timezone.utc
+ ) # Old: 60 min
+ mock_sub.updated_at = None
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = mock_sub
+ mock_session.query.return_value = mock_query
+
+ manager = FolderManager(mock_session)
+
+ # Change to 120 minutes
+ manager.update_subscription("sub-123", refresh_interval_minutes=120)
+
+ # next_refresh should be last_refresh + 120 minutes
+ expected_next = datetime(2024, 1, 15, 12, 0, 0, tzinfo=timezone.utc)
+ assert mock_sub.next_refresh == expected_next
+
+ def test_update_recalculates_next_refresh_without_last_refresh(self):
+ """Test that updating refresh_interval_minutes calculates from now when no last_refresh."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ mock_sub = MagicMock()
+ mock_sub.id = "sub-123"
+ mock_sub.last_refresh = None
+ mock_sub.next_refresh = None
+ mock_sub.updated_at = None
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = mock_sub
+ mock_session.query.return_value = mock_query
+
+ manager = FolderManager(mock_session)
+
+ before = datetime.now(timezone.utc)
+ manager.update_subscription("sub-123", refresh_interval_minutes=60)
+ after = datetime.now(timezone.utc)
+
+ # next_refresh should be approximately now + 60 minutes
+ expected_min = before + timedelta(minutes=60)
+ expected_max = after + timedelta(minutes=60)
+ assert expected_min <= mock_sub.next_refresh <= expected_max
+
+ def test_update_sets_updated_at(self):
+ """Test that update_subscription sets updated_at."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ mock_sub = MagicMock()
+ mock_sub.id = "sub-123"
+ mock_sub.updated_at = None
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = mock_sub
+ mock_session.query.return_value = mock_query
+
+ manager = FolderManager(mock_session)
+
+ before = datetime.now(timezone.utc)
+ manager.update_subscription("sub-123", status="paused")
+ after = datetime.now(timezone.utc)
+
+ assert mock_sub.updated_at is not None
+ assert before <= mock_sub.updated_at <= after
+
+ def test_update_does_not_modify_id(self):
+ """Test that update_subscription does not modify id."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ mock_sub = MagicMock()
+ mock_sub.id = "sub-123"
+ mock_sub.updated_at = None
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = mock_sub
+ mock_session.query.return_value = mock_query
+
+ manager = FolderManager(mock_session)
+
+ # Try to update id (should be ignored)
+ manager.update_subscription("sub-123", id="new-id")
+
+ assert mock_sub.id == "sub-123"
+
+ def test_update_does_not_modify_created_at(self):
+ """Test that update_subscription does not modify created_at."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ original_created = datetime(2024, 1, 1, 0, 0, 0, tzinfo=timezone.utc)
+ mock_sub = MagicMock()
+ mock_sub.id = "sub-123"
+ mock_sub.created_at = original_created
+ mock_sub.updated_at = None
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = mock_sub
+ mock_session.query.return_value = mock_query
+
+ manager = FolderManager(mock_session)
+
+ # Try to update created_at (should be ignored)
+ new_created = datetime(2024, 6, 1, 0, 0, 0, tzinfo=timezone.utc)
+ manager.update_subscription("sub-123", created_at=new_created)
+
+ assert mock_sub.created_at == original_created
+
+
+class TestGetSubscriptionStats:
+ """Tests for get_subscription_stats method."""
+
+ def test_stats_includes_total_count(self):
+ """Test that stats includes total count."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ mock_session.query.return_value.count.return_value = 10
+ mock_session.query.return_value.filter_by.return_value.count.return_value = 5
+ mock_session.query.return_value.order_by.return_value.all.return_value = []
+
+ manager = FolderManager(mock_session)
+
+ result = manager.get_subscription_stats("user-123")
+
+ assert result["total"] == 10
+
+ def test_stats_includes_active_count(self):
+ """Test that stats includes active count."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+
+ def mock_filter_by(**kwargs):
+ mock_result = MagicMock()
+ if kwargs.get("status") == "active":
+ mock_result.count.return_value = 8
+ elif kwargs.get("subscription_type") == "search":
+ mock_result.count.return_value = 5
+ elif kwargs.get("subscription_type") == "topic":
+ mock_result.count.return_value = 3
+ else:
+ mock_result.count.return_value = 0
+ return mock_result
+
+ mock_session.query.return_value.count.return_value = 10
+ mock_session.query.return_value.filter_by = mock_filter_by
+ mock_session.query.return_value.order_by.return_value.all.return_value = []
+
+ manager = FolderManager(mock_session)
+
+ result = manager.get_subscription_stats("user-123")
+
+ assert result["active"] == 8
+
+ def test_stats_includes_by_type(self):
+ """Test that stats includes counts by type."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+
+ type_counts = {"search": 5, "topic": 3}
+
+ def mock_filter_by(**kwargs):
+ mock_result = MagicMock()
+ sub_type = kwargs.get("subscription_type")
+ status = kwargs.get("status")
+ if sub_type and status == "active":
+ mock_result.count.return_value = type_counts.get(sub_type, 0)
+ elif status == "active":
+ mock_result.count.return_value = 8
+ else:
+ mock_result.count.return_value = 0
+ return mock_result
+
+ mock_session.query.return_value.count.return_value = 10
+ mock_session.query.return_value.filter_by = mock_filter_by
+ mock_session.query.return_value.order_by.return_value.all.return_value = []
+
+ manager = FolderManager(mock_session)
+
+ result = manager.get_subscription_stats("user-123")
+
+ assert "by_type" in result
+ assert result["by_type"]["search"] == 5
+ assert result["by_type"]["topic"] == 3
+
+ def test_stats_includes_folder_count(self):
+ """Test that stats includes folder count."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ mock_session.query.return_value.count.return_value = 10
+ mock_session.query.return_value.filter_by.return_value.count.return_value = 5
+ mock_session.query.return_value.order_by.return_value.all.return_value = [
+ MagicMock(),
+ MagicMock(),
+ MagicMock(), # 3 folders
+ ]
+
+ manager = FolderManager(mock_session)
+
+ result = manager.get_subscription_stats("user-123")
+
+ assert result["folders"] == 3
+
+
+class TestDeleteSubscription:
+ """Tests for delete_subscription method."""
+
+ def test_delete_returns_false_for_nonexistent(self):
+ """Test that delete_subscription returns False for nonexistent subscription."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = None
+ mock_session.query.return_value = mock_query
+
+ manager = FolderManager(mock_session)
+
+ result = manager.delete_subscription("nonexistent-id")
+
+ assert result is False
+
+ def test_delete_returns_true_for_success(self):
+ """Test that delete_subscription returns True on success."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ mock_sub = MagicMock()
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = mock_sub
+ mock_session.query.return_value = mock_query
+
+ manager = FolderManager(mock_session)
+
+ result = manager.delete_subscription("sub-123")
+
+ assert result is True
+ mock_session.delete.assert_called_once_with(mock_sub)
+ mock_session.commit.assert_called_once()
+
+
+class TestGetUserFolders:
+ """Tests for get_user_folders method."""
+
+ def test_returns_all_folders_ordered_by_name(self):
+ """Test that get_user_folders returns folders ordered by name."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ mock_folders = [MagicMock(name="Alpha"), MagicMock(name="Beta")]
+
+ mock_query = MagicMock()
+ mock_query.order_by.return_value.all.return_value = mock_folders
+ mock_session.query.return_value = mock_query
+
+ manager = FolderManager(mock_session)
+
+ result = manager.get_user_folders("user-123")
+
+ assert result == mock_folders
+
+
+class TestCreateFolder:
+ """Tests for create_folder method."""
+
+ def test_create_folder_with_name_only(self):
+ """Test creating folder with name only."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ manager = FolderManager(mock_session)
+
+ with patch("uuid.uuid4") as mock_uuid:
+ mock_uuid.return_value = MagicMock(__str__=lambda x: "test-uuid")
+ manager.create_folder("My Folder")
+
+ mock_session.add.assert_called_once()
+ mock_session.commit.assert_called_once()
+
+ def test_create_folder_with_description(self):
+ """Test creating folder with description."""
+ from local_deep_research.news.folder_manager import FolderManager
+
+ mock_session = MagicMock()
+ manager = FolderManager(mock_session)
+
+ with patch("uuid.uuid4") as mock_uuid:
+ mock_uuid.return_value = MagicMock(__str__=lambda x: "test-uuid")
+ manager.create_folder("My Folder", description="A test folder")
+
+ mock_session.add.assert_called_once()
+ added_folder = mock_session.add.call_args[0][0]
+ assert added_folder.description == "A test folder"
diff --git a/tests/web/auth/test_middleware_optimizer.py b/tests/web/auth/test_middleware_optimizer.py
new file mode 100644
index 0000000000..d338c51813
--- /dev/null
+++ b/tests/web/auth/test_middleware_optimizer.py
@@ -0,0 +1,385 @@
+"""
+Tests for web/auth/middleware_optimizer.py
+
+Tests cover:
+- should_skip_database_middleware - path-based skip logic
+- should_skip_queue_checks - method/path skip logic
+- should_skip_session_cleanup - probabilistic skip logic
+"""
+
+import pytest
+from flask import Flask
+from unittest.mock import patch
+
+
+def app():
+ """Create a Flask test app."""
+ app = Flask(__name__)
+ app.config["TESTING"] = True
+ return app
+
+
+class TestShouldSkipDatabaseMiddleware:
+ """Tests for should_skip_database_middleware function."""
+
+ def test_skip_static_files(self, app):
+ """Test that static file paths are skipped."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_database_middleware,
+ )
+
+ with app.test_request_context("/static/js/app.js", method="GET"):
+ result = should_skip_database_middleware()
+ assert result is True
+
+ def test_skip_static_css(self, app):
+ """Test that static CSS files are skipped."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_database_middleware,
+ )
+
+ with app.test_request_context("/static/css/style.css", method="GET"):
+ result = should_skip_database_middleware()
+ assert result is True
+
+ def test_skip_static_images(self, app):
+ """Test that static image files are skipped."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_database_middleware,
+ )
+
+ with app.test_request_context("/static/images/logo.png", method="GET"):
+ result = should_skip_database_middleware()
+ assert result is True
+
+ def test_skip_favicon(self, app):
+ """Test that favicon.ico is skipped."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_database_middleware,
+ )
+
+ with app.test_request_context("/favicon.ico", method="GET"):
+ result = should_skip_database_middleware()
+ assert result is True
+
+ def test_skip_robots_txt(self, app):
+ """Test that robots.txt is skipped."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_database_middleware,
+ )
+
+ with app.test_request_context("/robots.txt", method="GET"):
+ result = should_skip_database_middleware()
+ assert result is True
+
+ def test_skip_health_endpoint(self, app):
+ """Test that health endpoint is skipped."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_database_middleware,
+ )
+
+ with app.test_request_context("/health", method="GET"):
+ result = should_skip_database_middleware()
+ assert result is True
+
+ def test_skip_socket_io_polling(self, app):
+ """Test that Socket.IO polling paths are skipped."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_database_middleware,
+ )
+
+ with app.test_request_context(
+ "/socket.io/?EIO=4&transport=polling", method="GET"
+ ):
+ result = should_skip_database_middleware()
+ assert result is True
+
+ def test_skip_socket_io_websocket(self, app):
+ """Test that Socket.IO websocket paths are skipped."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_database_middleware,
+ )
+
+ with app.test_request_context(
+ "/socket.io/?EIO=4&transport=websocket", method="GET"
+ ):
+ result = should_skip_database_middleware()
+ assert result is True
+
+ def test_skip_auth_login(self, app):
+ """Test that auth/login path is skipped."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_database_middleware,
+ )
+
+ with app.test_request_context("/auth/login", method="POST"):
+ result = should_skip_database_middleware()
+ assert result is True
+
+ def test_skip_auth_register(self, app):
+ """Test that auth/register path is skipped."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_database_middleware,
+ )
+
+ with app.test_request_context("/auth/register", method="POST"):
+ result = should_skip_database_middleware()
+ assert result is True
+
+ def test_skip_auth_logout(self, app):
+ """Test that auth/logout path is skipped."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_database_middleware,
+ )
+
+ with app.test_request_context("/auth/logout", method="POST"):
+ result = should_skip_database_middleware()
+ assert result is True
+
+ def test_skip_options_preflight(self, app):
+ """Test that OPTIONS preflight requests are skipped."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_database_middleware,
+ )
+
+ with app.test_request_context("/api/research", method="OPTIONS"):
+ result = should_skip_database_middleware()
+ assert result is True
+
+ def test_no_skip_api_endpoint(self, app):
+ """Test that API endpoints are not skipped."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_database_middleware,
+ )
+
+ with app.test_request_context("/api/research", method="GET"):
+ result = should_skip_database_middleware()
+ assert result is False
+
+ def test_no_skip_api_post(self, app):
+ """Test that API POST requests are not skipped."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_database_middleware,
+ )
+
+ with app.test_request_context("/api/research", method="POST"):
+ result = should_skip_database_middleware()
+ assert result is False
+
+ def test_no_skip_root_path(self, app):
+ """Test that root path is not skipped."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_database_middleware,
+ )
+
+ with app.test_request_context("/", method="GET"):
+ result = should_skip_database_middleware()
+ assert result is False
+
+ def test_no_skip_dashboard(self, app):
+ """Test that dashboard path is not skipped."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_database_middleware,
+ )
+
+ with app.test_request_context("/dashboard", method="GET"):
+ result = should_skip_database_middleware()
+ assert result is False
+
+
+class TestShouldSkipQueueChecks:
+ """Tests for should_skip_queue_checks function."""
+
+ def test_skip_get_requests(self, app):
+ """Test that GET requests are skipped."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_queue_checks,
+ )
+
+ with app.test_request_context("/api/research", method="GET"):
+ result = should_skip_queue_checks()
+ assert result is True
+
+ def test_no_skip_post_requests(self, app):
+ """Test that POST requests to API are not skipped."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_queue_checks,
+ )
+
+ with app.test_request_context("/api/research", method="POST"):
+ result = should_skip_queue_checks()
+ assert result is False
+
+ def test_no_skip_put_requests(self, app):
+ """Test that PUT requests to API are not skipped."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_queue_checks,
+ )
+
+ with app.test_request_context("/api/research/123", method="PUT"):
+ result = should_skip_queue_checks()
+ assert result is False
+
+ def test_no_skip_delete_requests(self, app):
+ """Test that DELETE requests to API are not skipped."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_queue_checks,
+ )
+
+ with app.test_request_context("/api/research/123", method="DELETE"):
+ result = should_skip_queue_checks()
+ assert result is False
+
+ def test_skip_static_files_post(self, app):
+ """Test that static files are skipped even with POST."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_queue_checks,
+ )
+
+ with app.test_request_context("/static/js/app.js", method="POST"):
+ result = should_skip_queue_checks()
+ assert result is True
+
+ def test_skip_health_post(self, app):
+ """Test that health endpoint is skipped even with POST."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_queue_checks,
+ )
+
+ with app.test_request_context("/health", method="POST"):
+ result = should_skip_queue_checks()
+ assert result is True
+
+ def test_skip_socket_io_post(self, app):
+ """Test that socket.io is skipped even with POST."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_queue_checks,
+ )
+
+ with app.test_request_context(
+ "/socket.io/?EIO=4&transport=polling", method="POST"
+ ):
+ result = should_skip_queue_checks()
+ assert result is True
+
+ def test_skip_options_always(self, app):
+ """Test that OPTIONS requests are always skipped."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_queue_checks,
+ )
+
+ with app.test_request_context("/api/research", method="OPTIONS"):
+ result = should_skip_queue_checks()
+ assert result is True
+
+
+class TestShouldSkipSessionCleanup:
+ """Tests for should_skip_session_cleanup function."""
+
+ def test_skip_static_files(self, app):
+ """Test that static files always skip session cleanup."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_session_cleanup,
+ )
+
+ with app.test_request_context("/static/js/app.js", method="GET"):
+ with patch("random.randint", return_value=1): # Would normally run
+ result = should_skip_session_cleanup()
+ # Static files always skip, regardless of random
+ assert result is True
+
+ def test_skip_health_endpoint(self, app):
+ """Test that health endpoint always skips session cleanup."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_session_cleanup,
+ )
+
+ with app.test_request_context("/health", method="GET"):
+ with patch("random.randint", return_value=1): # Would normally run
+ result = should_skip_session_cleanup()
+ assert result is True
+
+ def test_skip_99_percent_of_time(self, app):
+ """Test that cleanup is skipped 99% of the time (random > 1)."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_session_cleanup,
+ )
+
+ with app.test_request_context("/api/research", method="GET"):
+ # Test with random values > 1 (should skip)
+ for rand_val in [2, 50, 100]:
+ with patch("random.randint", return_value=rand_val):
+ result = should_skip_session_cleanup()
+ assert result is True, (
+ f"Expected skip for random={rand_val}"
+ )
+
+ def test_run_cleanup_1_percent(self, app):
+ """Test that cleanup runs when random returns 1."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_session_cleanup,
+ )
+
+ with app.test_request_context("/api/research", method="GET"):
+ with patch("random.randint", return_value=1):
+ result = should_skip_session_cleanup()
+ # When random returns 1, we should NOT skip (run cleanup)
+ assert result is False
+
+ def test_skip_auth_routes(self, app):
+ """Test that auth routes skip cleanup."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_session_cleanup,
+ )
+
+ with app.test_request_context("/auth/login", method="POST"):
+ with patch("random.randint", return_value=1): # Would normally run
+ result = should_skip_session_cleanup()
+ assert result is True
+
+ def test_skip_favicon(self, app):
+ """Test that favicon skips cleanup."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_session_cleanup,
+ )
+
+ with app.test_request_context("/favicon.ico", method="GET"):
+ with patch("random.randint", return_value=1): # Would normally run
+ result = should_skip_session_cleanup()
+ assert result is True
+
+ def test_skip_socket_io(self, app):
+ """Test that socket.io paths skip cleanup."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_session_cleanup,
+ )
+
+ with app.test_request_context(
+ "/socket.io/?EIO=4&transport=polling", method="GET"
+ ):
+ with patch("random.randint", return_value=1): # Would normally run
+ result = should_skip_session_cleanup()
+ assert result is True
+
+ def test_skip_robots_txt(self, app):
+ """Test that robots.txt skips cleanup."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_session_cleanup,
+ )
+
+ with app.test_request_context("/robots.txt", method="GET"):
+ with patch("random.randint", return_value=1):
+ result = should_skip_session_cleanup()
+ assert result is True
+
+ def test_skip_options_preflight(self, app):
+ """Test that OPTIONS preflight requests skip cleanup."""
+ from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_session_cleanup,
+ )
+
+ with app.test_request_context("/api/research", method="OPTIONS"):
+ with patch("random.randint", return_value=1):
+ result = should_skip_session_cleanup()
+ assert result is True