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 11 coverage tests for history_routes.py (#2838)

LearningCircuit143fddc41e4d
diff --git a/tests/benchmarks/test_benchmark_functions_coverage.py b/tests/benchmarks/test_benchmark_functions_coverage.py
index fcd6181e91..f18d4fbef8 100644
--- a/tests/benchmarks/test_benchmark_functions_coverage.py
+++ b/tests/benchmarks/test_benchmark_functions_coverage.py
@@ -36,7 +36,9 @@ class TestSimpleqaSearchModelConfig:
def test_search_model_added_to_config(self):
with (
patch(f"{MODULE}.run_simpleqa_benchmark") as mock_run,
- patch(f"{MODULE}.get_setting_from_snapshot", side_effect=_no_settings),
+ patch(
+ f"{MODULE}.get_setting_from_snapshot", side_effect=_no_settings
+ ),
):
mock_run.return_value = {}
from local_deep_research.benchmarks.benchmark_functions import (
@@ -50,7 +52,9 @@ class TestSimpleqaSearchModelConfig:
def test_search_provider_added_to_config(self):
with (
patch(f"{MODULE}.run_simpleqa_benchmark") as mock_run,
- patch(f"{MODULE}.get_setting_from_snapshot", side_effect=_no_settings),
+ patch(
+ f"{MODULE}.get_setting_from_snapshot", side_effect=_no_settings
+ ),
):
mock_run.return_value = {}
from local_deep_research.benchmarks.benchmark_functions import (
@@ -64,14 +68,18 @@ class TestSimpleqaSearchModelConfig:
def test_endpoint_url_added_to_config(self):
with (
patch(f"{MODULE}.run_simpleqa_benchmark") as mock_run,
- patch(f"{MODULE}.get_setting_from_snapshot", side_effect=_no_settings),
+ patch(
+ f"{MODULE}.get_setting_from_snapshot", side_effect=_no_settings
+ ),
):
mock_run.return_value = {}
from local_deep_research.benchmarks.benchmark_functions import (
evaluate_simpleqa,
)
- evaluate_simpleqa(num_examples=1, endpoint_url="http://my-endpoint.com")
+ evaluate_simpleqa(
+ num_examples=1, endpoint_url="http://my-endpoint.com"
+ )
sc = mock_run.call_args[1]["search_config"]
assert sc["openai_endpoint_url"] == "http://my-endpoint.com"
@@ -80,7 +88,9 @@ class TestSimpleqaOpenaiEndpointEvaluation:
def test_openai_endpoint_uses_explicit_url(self):
with (
patch(f"{MODULE}.run_simpleqa_benchmark") as mock_run,
- patch(f"{MODULE}.get_setting_from_snapshot", side_effect=_no_settings),
+ patch(
+ f"{MODULE}.get_setting_from_snapshot", side_effect=_no_settings
+ ),
):
mock_run.return_value = {}
from local_deep_research.benchmarks.benchmark_functions import (
@@ -117,7 +127,9 @@ class TestSimpleqaOpenaiEndpointEvaluation:
evaluation_provider="openai_endpoint",
)
ec = mock_run.call_args[1]["evaluation_config"]
- assert ec["openai_endpoint_url"] == "http://env-endpoint.example.com"
+ assert (
+ ec["openai_endpoint_url"] == "http://env-endpoint.example.com"
+ )
def test_non_openai_endpoint_provider_no_url(self):
with (
@@ -172,7 +184,9 @@ class TestSimpleqaEvaluationTemperature:
def test_temperature_zero_with_model_only(self):
with (
patch(f"{MODULE}.run_simpleqa_benchmark") as mock_run,
- patch(f"{MODULE}.get_setting_from_snapshot", side_effect=_no_settings),
+ patch(
+ f"{MODULE}.get_setting_from_snapshot", side_effect=_no_settings
+ ),
):
mock_run.return_value = {}
from local_deep_research.benchmarks.benchmark_functions import (
@@ -188,7 +202,9 @@ class TestSimpleqaEvaluationTemperature:
def test_no_evaluation_config_when_no_eval_params(self):
with (
patch(f"{MODULE}.run_simpleqa_benchmark") as mock_run,
- patch(f"{MODULE}.get_setting_from_snapshot", side_effect=_no_settings),
+ patch(
+ f"{MODULE}.get_setting_from_snapshot", side_effect=_no_settings
+ ),
):
mock_run.return_value = {}
from local_deep_research.benchmarks.benchmark_functions import (
@@ -204,7 +220,9 @@ class TestBrowsecompSearchModelConfig:
def test_search_model_and_provider_in_config(self):
with (
patch(f"{MODULE}.run_browsecomp_benchmark") as mock_run,
- patch(f"{MODULE}.get_setting_from_snapshot", side_effect=_no_settings),
+ patch(
+ f"{MODULE}.get_setting_from_snapshot", side_effect=_no_settings
+ ),
):
mock_run.return_value = {}
from local_deep_research.benchmarks.benchmark_functions import (
@@ -225,7 +243,9 @@ class TestBrowsecompSearchModelConfig:
def test_evaluation_openai_endpoint_with_explicit_url(self):
with (
patch(f"{MODULE}.run_browsecomp_benchmark") as mock_run,
- patch(f"{MODULE}.get_setting_from_snapshot", side_effect=_no_settings),
+ patch(
+ f"{MODULE}.get_setting_from_snapshot", side_effect=_no_settings
+ ),
):
mock_run.return_value = {}
from local_deep_research.benchmarks.benchmark_functions import (
@@ -260,14 +280,18 @@ class TestBrowsecompSearchModelConfig:
evaluation_provider="openai_endpoint",
)
ec = mock_run.call_args[1]["evaluation_config"]
- assert ec["openai_endpoint_url"] == "http://env-endpoint.example.com"
+ assert (
+ ec["openai_endpoint_url"] == "http://env-endpoint.example.com"
+ )
class TestXbenchDeepsearchDefaults:
def test_default_iterations_is_4(self):
with (
patch(f"{MODULE}.run_xbench_deepsearch_benchmark") as mock_run,
- patch(f"{MODULE}.get_setting_from_snapshot", side_effect=_no_settings),
+ patch(
+ f"{MODULE}.get_setting_from_snapshot", side_effect=_no_settings
+ ),
):
mock_run.return_value = {}
from local_deep_research.benchmarks.benchmark_functions import (
@@ -281,7 +305,9 @@ class TestXbenchDeepsearchDefaults:
def test_search_model_and_endpoint_in_config(self):
with (
patch(f"{MODULE}.run_xbench_deepsearch_benchmark") as mock_run,
- patch(f"{MODULE}.get_setting_from_snapshot", side_effect=_no_settings),
+ patch(
+ f"{MODULE}.get_setting_from_snapshot", side_effect=_no_settings
+ ),
):
mock_run.return_value = {}
from local_deep_research.benchmarks.benchmark_functions import (
@@ -319,7 +345,9 @@ class TestXbenchDeepsearchDefaults:
)
ec = mock_run.call_args[1]["evaluation_config"]
assert ec["temperature"] == 0
- assert ec["openai_endpoint_url"] == "http://env-endpoint.example.com"
+ assert (
+ ec["openai_endpoint_url"] == "http://env-endpoint.example.com"
+ )
def test_settings_override_search_config(self):
with (
diff --git a/tests/web/routes/test_history_routes_coverage.py b/tests/web/routes/test_history_routes_coverage.py
new file mode 100644
index 0000000000..8beeb5ca8a
--- /dev/null
+++ b/tests/web/routes/test_history_routes_coverage.py
@@ -0,0 +1,507 @@
+"""
+Coverage tests for history_routes.py targeting uncovered statements and branches.
+
+Covers:
+- get_history: duration recalculation exception path (lines 102-104)
+- get_research_status: non-active, non-completed status with progress_log
+ parse and parse failure (lines 165-172)
+- get_research_details: database exception returning 500 (lines 210-212)
+- get_research_details: active research with in-memory log merging (lines 231-243)
+- get_report: report_data is empty/None returning 404 (line 292)
+- get_report: storage exception returning 500 (lines 323-324)
+- get_markdown: research not found returning 404 (line 344)
+- get_markdown: content is empty/None returning 404 (line 354)
+- get_markdown: storage exception returning 500 (lines 359-360)
+"""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+from flask import Flask
+
+from local_deep_research.web.auth import auth_bp
+from local_deep_research.web.routes.history_routes import history_bp
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+MODULE = "local_deep_research.web.routes.history_routes"
+AUTH_DB_MANAGER = "local_deep_research.web.auth.decorators.db_manager"
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _mock_auth():
+ """Return a MagicMock that satisfies login_required db_manager check."""
+ return MagicMock(is_user_connected=MagicMock(return_value=True))
+
+
+def _make_db_ctx(mock_session):
+ """Build a mock context-manager for get_user_db_session."""
+ ctx = MagicMock()
+ ctx.__enter__ = MagicMock(return_value=mock_session)
+ ctx.__exit__ = MagicMock(return_value=None)
+ return ctx
+
+
+def _make_db_ctx_raising(exc):
+ """Build a context-manager that raises on __enter__."""
+ ctx = MagicMock()
+ ctx.__enter__ = MagicMock(side_effect=exc)
+ ctx.__exit__ = MagicMock(return_value=None)
+ return ctx
+
+
+def _build_join_chain(results):
+ """Build chained SQLAlchemy mock query for the JOIN used in get_history."""
+ q = MagicMock()
+ (
+ q.outerjoin.return_value.group_by.return_value.order_by.return_value.limit.return_value.offset.return_value.all
+ ).return_value = results
+ return q
+
+
+def _build_filter_chain(result):
+ """Build chained SQLAlchemy mock query for filter_by().first()."""
+ q = MagicMock()
+ q.filter_by.return_value.first.return_value = result
+ return q
+
+
+def _make_research(**overrides):
+ """Create a mock ResearchHistory object with sensible defaults."""
+ r = MagicMock()
+ defaults = {
+ "id": "test-id",
+ "title": "Test",
+ "query": "test query",
+ "mode": "quick",
+ "status": "completed",
+ "created_at": "2024-01-01T10:00:00",
+ "completed_at": "2024-01-01T10:05:00",
+ "duration_seconds": 300,
+ "research_meta": None,
+ "progress_log": "[]",
+ "report_path": None,
+ }
+ defaults.update(overrides)
+ for k, v in defaults.items():
+ setattr(r, k, v)
+ return r
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+def app():
+ """Minimal Flask app with auth and history blueprints."""
+ application = Flask(__name__)
+ application.config["SECRET_KEY"] = "test-secret"
+ application.config["TESTING"] = True
+ application.register_blueprint(auth_bp)
+ application.register_blueprint(history_bp)
+ return application
+
+
+def _authed_get(app, path, **kwargs):
+ """Issue an authenticated GET request and return the response."""
+ with app.test_client() as c:
+ with c.session_transaction() as sess:
+ sess["username"] = "testuser"
+ return c.get(path, **kwargs)
+
+
+# ---------------------------------------------------------------------------
+# get_history: duration recalculation exception (lines 102-104)
+# ---------------------------------------------------------------------------
+
+
+class TestGetHistoryDurationRecalcError:
+ """Duration recalculation when dateutil parsing fails."""
+
+ def test_duration_recalc_exception_sets_none(self, app):
+ """When timestamp parsing raises, duration_seconds stays None."""
+ research = _make_research(
+ id="dur-err",
+ duration_seconds=None,
+ created_at="not-a-date",
+ completed_at="also-not-a-date",
+ )
+ mock_session = MagicMock()
+ mock_session.query.return_value = _build_join_chain([(research, 0)])
+
+ with (
+ patch(
+ f"{MODULE}.get_user_db_session",
+ return_value=_make_db_ctx(mock_session),
+ ),
+ patch(AUTH_DB_MANAGER, _mock_auth()),
+ ):
+ resp = _authed_get(app, "/history/api")
+
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data["items"][0]["duration_seconds"] is None
+
+
+# ---------------------------------------------------------------------------
+# get_research_status: non-active, non-completed (lines 165-172)
+# ---------------------------------------------------------------------------
+
+
+class TestGetResearchStatusNonCompleted:
+ """Status route for research that is neither active nor completed."""
+
+ def test_non_completed_non_active_returns_progress_zero(self, app):
+ """Non-active, non-completed research returns progress=0 and parses log."""
+ research = _make_research(
+ id="pending-1",
+ status="in_progress",
+ progress_log='[{"time":"10:00","msg":"started"}]',
+ )
+ mock_session = MagicMock()
+ mock_session.query.return_value = _build_filter_chain(research)
+
+ with (
+ patch(
+ f"{MODULE}.get_user_db_session",
+ return_value=_make_db_ctx(mock_session),
+ ),
+ patch(f"{MODULE}.get_active_research_snapshot", return_value=None),
+ patch(AUTH_DB_MANAGER, _mock_auth()),
+ ):
+ resp = _authed_get(app, "/history/status/pending-1")
+
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data["progress"] == 0
+ assert isinstance(data["log"], list)
+
+ def test_non_completed_invalid_progress_log_returns_empty_list(self, app):
+ """When progress_log is invalid JSON, log defaults to []."""
+ research = _make_research(
+ id="bad-log",
+ status="failed",
+ progress_log="not valid json {{",
+ )
+ mock_session = MagicMock()
+ mock_session.query.return_value = _build_filter_chain(research)
+
+ with (
+ patch(
+ f"{MODULE}.get_user_db_session",
+ return_value=_make_db_ctx(mock_session),
+ ),
+ patch(f"{MODULE}.get_active_research_snapshot", return_value=None),
+ patch(AUTH_DB_MANAGER, _mock_auth()),
+ ):
+ resp = _authed_get(app, "/history/status/bad-log")
+
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data["progress"] == 0
+ assert data["log"] == []
+
+
+# ---------------------------------------------------------------------------
+# get_research_details: database exception (lines 210-212)
+# ---------------------------------------------------------------------------
+
+
+class TestGetResearchDetailsDbError:
+ """Details route when database raises an exception."""
+
+ def test_database_exception_returns_500(self, app):
+ """Database error in details route returns 500 with error message."""
+ with (
+ patch(
+ f"{MODULE}.get_user_db_session",
+ return_value=_make_db_ctx_raising(RuntimeError("db down")),
+ ),
+ patch(AUTH_DB_MANAGER, _mock_auth()),
+ ):
+ resp = _authed_get(app, "/history/details/some-id")
+
+ assert resp.status_code == 500
+ data = resp.get_json()
+ assert data["status"] == "error"
+ assert "database" in data["message"].lower()
+
+
+# ---------------------------------------------------------------------------
+# get_research_details: active research with memory logs (lines 231-243)
+# ---------------------------------------------------------------------------
+
+
+class TestGetResearchDetailsActiveWithLogs:
+ """Details route when research is active and has in-memory logs."""
+
+ def test_active_research_merges_memory_logs(self, app):
+ """Active research merges in-memory logs with DB logs, deduplicating."""
+ research = _make_research(id="active-1", status="in_progress")
+ mock_session = MagicMock()
+ mock_session.query.return_value = _build_filter_chain(research)
+
+ db_logs = [
+ {"time": "10:00:00", "message": "step 1"},
+ {"time": "10:01:00", "message": "step 2"},
+ ]
+ memory_logs = [
+ {"time": "10:01:00", "message": "step 2"}, # duplicate
+ {"time": "10:02:00", "message": "step 3"}, # new
+ ]
+ snapshot = {"progress": 55, "log": memory_logs}
+
+ with (
+ patch(
+ f"{MODULE}.get_user_db_session",
+ return_value=_make_db_ctx(mock_session),
+ ),
+ patch(f"{MODULE}.get_logs_for_research", return_value=db_logs),
+ patch(f"{MODULE}.get_research_strategy", return_value="standard"),
+ patch(
+ f"{MODULE}.get_active_research_snapshot", return_value=snapshot
+ ),
+ patch(AUTH_DB_MANAGER, _mock_auth()),
+ ):
+ resp = _authed_get(app, "/history/details/active-1")
+
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data["progress"] == 55
+ # Should have 3 unique logs (deduped by time), sorted
+ assert len(data["log"]) == 3
+ times = [entry["time"] for entry in data["log"]]
+ assert times == sorted(times)
+
+
+# ---------------------------------------------------------------------------
+# get_report: report_data is None (line 292)
+# ---------------------------------------------------------------------------
+
+
+class TestGetReportContentNotFound:
+ """Report route when storage returns no report data."""
+
+ def test_report_data_none_returns_404(self, app):
+ """When storage.get_report_with_metadata returns None, return 404."""
+ research = _make_research(id="no-report")
+ mock_session = MagicMock()
+ mock_session.query.return_value = _build_filter_chain(research)
+
+ mock_storage = MagicMock()
+ mock_storage.get_report_with_metadata.return_value = None
+
+ with (
+ patch(
+ f"{MODULE}.get_user_db_session",
+ return_value=_make_db_ctx(mock_session),
+ ),
+ patch(
+ "local_deep_research.storage.get_report_storage",
+ return_value=mock_storage,
+ ),
+ patch(
+ "local_deep_research.web.auth.decorators.current_user",
+ return_value="testuser",
+ ),
+ patch(AUTH_DB_MANAGER, _mock_auth()),
+ ):
+ resp = _authed_get(app, "/history/report/no-report")
+
+ assert resp.status_code == 404
+ data = resp.get_json()
+ assert data["status"] == "error"
+ assert "not found" in data["message"].lower()
+
+
+# ---------------------------------------------------------------------------
+# get_report: storage exception (lines 323-324)
+# ---------------------------------------------------------------------------
+
+
+class TestGetReportStorageException:
+ """Report route when storage raises an exception."""
+
+ def test_storage_exception_returns_500(self, app):
+ """When storage raises, return 500 with error message."""
+ research = _make_research(id="err-report")
+ mock_session = MagicMock()
+ mock_session.query.return_value = _build_filter_chain(research)
+
+ mock_storage = MagicMock()
+ mock_storage.get_report_with_metadata.side_effect = RuntimeError(
+ "disk fail"
+ )
+
+ with (
+ patch(
+ f"{MODULE}.get_user_db_session",
+ return_value=_make_db_ctx(mock_session),
+ ),
+ patch(
+ "local_deep_research.storage.get_report_storage",
+ return_value=mock_storage,
+ ),
+ patch(
+ "local_deep_research.web.auth.decorators.current_user",
+ return_value="testuser",
+ ),
+ patch(AUTH_DB_MANAGER, _mock_auth()),
+ ):
+ resp = _authed_get(app, "/history/report/err-report")
+
+ assert resp.status_code == 500
+ data = resp.get_json()
+ assert data["status"] == "error"
+
+
+# ---------------------------------------------------------------------------
+# get_markdown: research not found (line 344)
+# ---------------------------------------------------------------------------
+
+
+class TestGetMarkdownNotFound:
+ """Markdown route when research does not exist."""
+
+ def test_research_not_found_returns_404(self, app):
+ """When research record is missing, return 404."""
+ mock_session = MagicMock()
+ mock_session.query.return_value = _build_filter_chain(None)
+
+ with (
+ patch(
+ f"{MODULE}.get_user_db_session",
+ return_value=_make_db_ctx(mock_session),
+ ),
+ patch(
+ "local_deep_research.web.auth.decorators.current_user",
+ return_value="testuser",
+ ),
+ patch(AUTH_DB_MANAGER, _mock_auth()),
+ ):
+ resp = _authed_get(app, "/history/markdown/missing-id")
+
+ assert resp.status_code == 404
+ data = resp.get_json()
+ assert data["status"] == "error"
+
+
+# ---------------------------------------------------------------------------
+# get_markdown: content is empty (line 354)
+# ---------------------------------------------------------------------------
+
+
+class TestGetMarkdownContentEmpty:
+ """Markdown route when storage returns empty content."""
+
+ def test_empty_content_returns_404(self, app):
+ """When storage.get_report returns empty string, return 404."""
+ research = _make_research(id="empty-md")
+ mock_session = MagicMock()
+ mock_session.query.return_value = _build_filter_chain(research)
+
+ mock_storage = MagicMock()
+ mock_storage.get_report.return_value = ""
+
+ with (
+ patch(
+ f"{MODULE}.get_user_db_session",
+ return_value=_make_db_ctx(mock_session),
+ ),
+ patch(
+ "local_deep_research.storage.get_report_storage",
+ return_value=mock_storage,
+ ),
+ patch(
+ "local_deep_research.web.auth.decorators.current_user",
+ return_value="testuser",
+ ),
+ patch(AUTH_DB_MANAGER, _mock_auth()),
+ ):
+ resp = _authed_get(app, "/history/markdown/empty-md")
+
+ assert resp.status_code == 404
+ data = resp.get_json()
+ assert data["status"] == "error"
+ assert "not found" in data["message"].lower()
+
+
+# ---------------------------------------------------------------------------
+# get_markdown: storage exception (lines 359-360)
+# ---------------------------------------------------------------------------
+
+
+class TestGetMarkdownStorageException:
+ """Markdown route when storage raises an exception."""
+
+ def test_storage_exception_returns_500(self, app):
+ """When storage.get_report raises, return 500."""
+ research = _make_research(id="err-md")
+ mock_session = MagicMock()
+ mock_session.query.return_value = _build_filter_chain(research)
+
+ mock_storage = MagicMock()
+ mock_storage.get_report.side_effect = RuntimeError("io error")
+
+ with (
+ patch(
+ f"{MODULE}.get_user_db_session",
+ return_value=_make_db_ctx(mock_session),
+ ),
+ patch(
+ "local_deep_research.storage.get_report_storage",
+ return_value=mock_storage,
+ ),
+ patch(
+ "local_deep_research.web.auth.decorators.current_user",
+ return_value="testuser",
+ ),
+ patch(AUTH_DB_MANAGER, _mock_auth()),
+ ):
+ resp = _authed_get(app, "/history/markdown/err-md")
+
+ assert resp.status_code == 500
+ data = resp.get_json()
+ assert data["status"] == "error"
+
+
+# ---------------------------------------------------------------------------
+# get_research_status: completed with invalid progress_log (line 165 branch)
+# ---------------------------------------------------------------------------
+
+
+class TestGetResearchStatusCompletedBadLog:
+ """Status route for completed research with invalid progress_log JSON."""
+
+ def test_completed_invalid_log_returns_empty_list(self, app):
+ """Completed research with unparseable progress_log defaults log to []."""
+ research = _make_research(
+ id="comp-bad-log",
+ status="completed",
+ progress_log="{broken json",
+ )
+ mock_session = MagicMock()
+ mock_session.query.return_value = _build_filter_chain(research)
+
+ with (
+ patch(
+ f"{MODULE}.get_user_db_session",
+ return_value=_make_db_ctx(mock_session),
+ ),
+ patch(f"{MODULE}.get_active_research_snapshot", return_value=None),
+ patch(AUTH_DB_MANAGER, _mock_auth()),
+ ):
+ resp = _authed_get(app, "/history/status/comp-bad-log")
+
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data["progress"] == 100
+ assert data["log"] == []