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 88 coverage tests across 6 files (round 4) (#2907)

LearningCircuita1a899e810ef
diff --git a/tests/config/test_thread_settings_extra.py b/tests/config/test_thread_settings_extra.py
new file mode 100644
index 0000000000..e850e4d6ba
--- /dev/null
+++ b/tests/config/test_thread_settings_extra.py
@@ -0,0 +1,228 @@
+"""Extra coverage tests for config/thread_settings.py — untested branches."""
+
+import os
+from unittest.mock import patch
+
+import pytest
+
+from local_deep_research.config.thread_settings import (
+ NoSettingsContextError,
+ get_bool_setting_from_snapshot,
+ get_llm_setting_from_snapshot,
+ get_setting_from_snapshot,
+)
+
+MODULE = "local_deep_research.config.thread_settings"
+
+
+class TestGetSettingFromSnapshotChildKeys:
+ def test_child_keys_built_into_dict(self):
+ """When snapshot has 'parent.child' keys, they're assembled into a dict."""
+ snapshot = {
+ "search.engine.web.searxng.url": "http://localhost:8888",
+ "search.engine.web.searxng.enabled": True,
+ }
+ result = get_setting_from_snapshot(
+ "search.engine.web.searxng",
+ settings_snapshot=snapshot,
+ )
+ assert isinstance(result, dict)
+ assert result["url"] == "http://localhost:8888"
+ assert result["enabled"] is True
+
+ def test_child_keys_with_value_dict_format(self):
+ """Child keys in {'value': x, 'ui_element': y} format are extracted."""
+ snapshot = {
+ "llm.provider.model": {"value": "gpt-4", "ui_element": "text"},
+ }
+ result = get_setting_from_snapshot(
+ "llm.provider",
+ settings_snapshot=snapshot,
+ )
+ assert isinstance(result, dict)
+ assert result["model"] == "gpt-4"
+
+ def test_child_keys_with_simplified_format(self):
+ """Child keys as raw values (not dicts) pass through directly."""
+ snapshot = {
+ "app.settings.theme": "dark",
+ "app.settings.lang": "en",
+ }
+ result = get_setting_from_snapshot(
+ "app.settings",
+ settings_snapshot=snapshot,
+ )
+ assert result == {"theme": "dark", "lang": "en"}
+
+ def test_direct_key_takes_priority(self):
+ """Direct key match is returned before child key search."""
+ snapshot = {
+ "key": "direct_value",
+ "key.child": "child_value",
+ }
+ result = get_setting_from_snapshot("key", settings_snapshot=snapshot)
+ assert result == "direct_value"
+
+
+class TestGetSettingFromSnapshotValueExtraction:
+ def test_dict_with_value_key_extracted(self):
+ snapshot = {"my.setting": {"value": 42, "ui_element": "number"}}
+ result = get_setting_from_snapshot(
+ "my.setting", settings_snapshot=snapshot
+ )
+ assert result == 42
+
+ def test_dict_without_value_key_returned_as_is(self):
+ snapshot = {"my.setting": {"custom_field": "data"}}
+ result = get_setting_from_snapshot(
+ "my.setting", settings_snapshot=snapshot
+ )
+ assert result == {"custom_field": "data"}
+
+ def test_plain_value_returned_directly(self):
+ snapshot = {"my.setting": "plain_string"}
+ result = get_setting_from_snapshot(
+ "my.setting", settings_snapshot=snapshot
+ )
+ assert result == "plain_string"
+
+
+class TestGetSettingFromSnapshotFallbacks:
+ def test_settings_context_fallback(self):
+ """When snapshot doesn't have key, thread context is checked."""
+ mock_ctx = type(
+ "Ctx", (), {"get_setting": lambda s, k, d: "from_ctx"}
+ )()
+
+ with patch(f"{MODULE}._thread_local") as mock_tl:
+ mock_tl.settings_context = mock_ctx
+ result = get_setting_from_snapshot("missing.key")
+
+ assert result == "from_ctx"
+
+ def test_default_returned_when_nothing_found(self):
+ result = get_setting_from_snapshot(
+ "nonexistent.key",
+ default="fallback",
+ settings_snapshot={},
+ )
+ assert result == "fallback"
+
+ def test_raises_when_no_default_and_nothing_found(self):
+ with pytest.raises(NoSettingsContextError):
+ get_setting_from_snapshot(
+ "nonexistent.key",
+ settings_snapshot={},
+ )
+
+ def test_fallback_llm_env_returns_default(self):
+ with patch.dict(
+ os.environ,
+ {"LDR_USE_FALLBACK_LLM": "true"},
+ clear=False,
+ ):
+ result = get_setting_from_snapshot(
+ "missing.key",
+ default="fallback_val",
+ settings_snapshot={},
+ check_fallback_llm=True,
+ )
+ assert result == "fallback_val"
+
+ def test_fallback_llm_env_with_testing_mocks_skipped(self):
+ """LDR_TESTING_WITH_MOCKS disables the fallback LLM path."""
+ with patch.dict(
+ os.environ,
+ {"LDR_USE_FALLBACK_LLM": "true", "LDR_TESTING_WITH_MOCKS": "1"},
+ clear=False,
+ ):
+ # Should NOT use the fallback path, should raise since no default
+ with pytest.raises(NoSettingsContextError):
+ get_setting_from_snapshot(
+ "missing.key",
+ settings_snapshot={},
+ check_fallback_llm=True,
+ )
+
+
+class TestGetLlmSettingFromSnapshot:
+ def test_delegates_with_check_fallback(self):
+ snapshot = {"llm.model": "gpt-4"}
+ result = get_llm_setting_from_snapshot(
+ "llm.model", settings_snapshot=snapshot
+ )
+ assert result == "gpt-4"
+
+ def test_uses_fallback_env(self):
+ with patch.dict(
+ os.environ,
+ {"LDR_USE_FALLBACK_LLM": "true"},
+ clear=False,
+ ):
+ result = get_llm_setting_from_snapshot(
+ "missing", default="default_val", settings_snapshot={}
+ )
+ assert result == "default_val"
+
+
+class TestGetBoolSettingFromSnapshot:
+ def test_true_string(self):
+ snapshot = {"feature.enabled": "true"}
+ assert (
+ get_bool_setting_from_snapshot(
+ "feature.enabled", settings_snapshot=snapshot
+ )
+ is True
+ )
+
+ def test_false_string(self):
+ snapshot = {"feature.enabled": "false"}
+ assert (
+ get_bool_setting_from_snapshot(
+ "feature.enabled", settings_snapshot=snapshot
+ )
+ is False
+ )
+
+ def test_default_when_missing(self):
+ assert (
+ get_bool_setting_from_snapshot(
+ "missing.key", default=True, settings_snapshot={}
+ )
+ is True
+ )
+
+ def test_integer_one(self):
+ snapshot = {"flag": 1}
+ assert (
+ get_bool_setting_from_snapshot("flag", settings_snapshot=snapshot)
+ is True
+ )
+
+ def test_integer_zero(self):
+ snapshot = {"flag": 0}
+ assert (
+ get_bool_setting_from_snapshot("flag", settings_snapshot=snapshot)
+ is False
+ )
+
+ def test_bool_passthrough(self):
+ snapshot = {"flag": True}
+ assert (
+ get_bool_setting_from_snapshot("flag", settings_snapshot=snapshot)
+ is True
+ )
+
+ def test_yes_string(self):
+ snapshot = {"flag": "yes"}
+ assert (
+ get_bool_setting_from_snapshot("flag", settings_snapshot=snapshot)
+ is True
+ )
+
+ def test_on_string(self):
+ snapshot = {"flag": "on"}
+ assert (
+ get_bool_setting_from_snapshot("flag", settings_snapshot=snapshot)
+ is True
+ )
diff --git a/tests/database/test_session_passwords_extra.py b/tests/database/test_session_passwords_extra.py
new file mode 100644
index 0000000000..4c15b17b98
--- /dev/null
+++ b/tests/database/test_session_passwords_extra.py
@@ -0,0 +1,64 @@
+"""Extra coverage tests for session_passwords.py — clear_all_for_user and aliases."""
+
+from local_deep_research.database.session_passwords import SessionPasswordStore
+
+
+class TestClearAllForUser:
+ def test_clears_all_sessions_for_user(self):
+ store = SessionPasswordStore(ttl_hours=1)
+ store.store_session_password("alice", "s1", "pw1")
+ store.store_session_password("alice", "s2", "pw2")
+ store.store_session_password("bob", "s3", "pw3")
+
+ store.clear_all_for_user("alice")
+
+ assert store.get_session_password("alice", "s1") is None
+ assert store.get_session_password("alice", "s2") is None
+ assert store.get_session_password("bob", "s3") == "pw3"
+
+ def test_clears_nothing_when_user_not_found(self):
+ store = SessionPasswordStore(ttl_hours=1)
+ store.store_session_password("alice", "s1", "pw1")
+
+ store.clear_all_for_user("nonexistent")
+
+ assert store.get_session_password("alice", "s1") == "pw1"
+
+ def test_clears_nothing_on_empty_store(self):
+ store = SessionPasswordStore(ttl_hours=1)
+ store.clear_all_for_user("alice") # should not raise
+
+ def test_does_not_clear_similar_prefix(self):
+ """'alice' should not clear 'alice2:...' entries."""
+ store = SessionPasswordStore(ttl_hours=1)
+ store.store_session_password("alice", "s1", "pw1")
+ store.store_session_password("alice2", "s1", "pw2")
+
+ store.clear_all_for_user("alice")
+
+ assert store.get_session_password("alice", "s1") is None
+ assert store.get_session_password("alice2", "s1") == "pw2"
+
+ def test_clears_single_session(self):
+ store = SessionPasswordStore(ttl_hours=1)
+ store.store_session_password("alice", "only-one", "pw")
+
+ store.clear_all_for_user("alice")
+
+ assert store.get_session_password("alice", "only-one") is None
+
+
+class TestAliases:
+ def test_store_alias(self):
+ store = SessionPasswordStore(ttl_hours=1)
+ store.store("user", "sid", "pass")
+ assert store.get_session_password("user", "sid") == "pass"
+
+ def test_retrieve_alias(self):
+ store = SessionPasswordStore(ttl_hours=1)
+ store.store_session_password("user", "sid", "pass")
+ assert store.retrieve("user", "sid") == "pass"
+
+ def test_retrieve_returns_none_when_missing(self):
+ store = SessionPasswordStore(ttl_hours=1)
+ assert store.retrieve("user", "nosid") is None
diff --git a/tests/notifications/test_templates_coverage.py b/tests/notifications/test_templates_coverage.py
new file mode 100644
index 0000000000..d99674c40d
--- /dev/null
+++ b/tests/notifications/test_templates_coverage.py
@@ -0,0 +1,203 @@
+"""Coverage tests for notifications/templates.py — template rendering branches."""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from local_deep_research.notifications.templates import (
+ EventType,
+ NotificationTemplate,
+)
+
+MODULE = "local_deep_research.notifications.templates"
+
+
[email protected](autouse=True)
+def _reset_jinja_env():
+ """Reset cached Jinja2 env between tests."""
+ NotificationTemplate._jinja_env = None
+ yield
+ NotificationTemplate._jinja_env = None
+
+
+class TestFormatWithCustomTemplate:
+ def test_custom_template_success(self):
+ result = NotificationTemplate.format(
+ EventType.TEST,
+ {"query": "climate change", "status": "done"},
+ custom_template={
+ "title": "Research: {query}",
+ "body": "Status: {status}",
+ },
+ )
+ assert result["title"] == "Research: climate change"
+ assert result["body"] == "Status: done"
+
+ def test_custom_template_missing_variable(self):
+ result = NotificationTemplate.format(
+ EventType.TEST,
+ {"query": "test"},
+ custom_template={
+ "title": "Research: {query}",
+ "body": "By: {username}",
+ },
+ )
+ assert "Missing variable" in result["body"]
+
+ def test_custom_template_sanitizes_context(self):
+ """Context values are coerced to strings to prevent format attacks."""
+ result = NotificationTemplate.format(
+ EventType.TEST,
+ {"query": 42, "none_val": None},
+ custom_template={
+ "title": "{query}",
+ "body": "{none_val}",
+ },
+ )
+ assert result["title"] == "42"
+ assert result["body"] == ""
+
+
+class TestFormatWithJinjaTemplates:
+ def test_research_completed_template(self):
+ result = NotificationTemplate.format(
+ EventType.RESEARCH_COMPLETED,
+ {
+ "query": "test query",
+ "research_url": "http://localhost/research/123",
+ "duration": "5m",
+ },
+ )
+ assert "title" in result
+ assert "body" in result
+ assert isinstance(result["title"], str)
+
+ def test_research_failed_template(self):
+ result = NotificationTemplate.format(
+ EventType.RESEARCH_FAILED,
+ {
+ "query": "test",
+ "error": "Connection timeout",
+ "research_url": "http://localhost/research/456",
+ },
+ )
+ assert "title" in result
+
+ def test_research_queued_template(self):
+ result = NotificationTemplate.format(
+ EventType.RESEARCH_QUEUED,
+ {
+ "query": "test",
+ "position": 3,
+ },
+ )
+ assert "title" in result
+
+ def test_test_event_template(self):
+ result = NotificationTemplate.format(
+ EventType.TEST,
+ {"message": "hello"},
+ )
+ assert "title" in result
+
+
+class TestFormatUnknownEventType:
+ def test_unmapped_event_returns_fallback(self):
+ """EventType without template file → generic fallback."""
+ # Use RATE_LIMIT_WARNING which may not have a template file
+ result = NotificationTemplate.format(
+ EventType.RATE_LIMIT_WARNING,
+ {"detail": "rate limited"},
+ )
+ assert "title" in result
+ assert isinstance(result["title"], str)
+
+
+class TestFormatJinjaUnavailable:
+ def test_fallback_when_jinja_env_none(self):
+ with patch.object(
+ NotificationTemplate, "_get_jinja_env", return_value=None
+ ):
+ result = NotificationTemplate.format(
+ EventType.RESEARCH_COMPLETED,
+ {"query": "test"},
+ )
+ assert "title" in result
+ assert "Notification" in result["title"]
+
+ def test_fallback_when_jinja_render_fails(self):
+ mock_env = MagicMock()
+ mock_env.get_template.side_effect = RuntimeError("render error")
+
+ with patch.object(
+ NotificationTemplate, "_get_jinja_env", return_value=mock_env
+ ):
+ result = NotificationTemplate.format(
+ EventType.RESEARCH_COMPLETED,
+ {"query": "test"},
+ )
+ assert "title" in result
+
+
+class TestGetFallbackTemplate:
+ def test_returns_title_and_body(self):
+ result = NotificationTemplate._get_fallback_template(
+ EventType.RESEARCH_COMPLETED,
+ {"query": "test"},
+ )
+ assert "Research Completed" in result["title"]
+ assert "Details:" in result["body"]
+
+
+class TestGetRequiredContext:
+ def test_known_event_returns_list(self):
+ result = NotificationTemplate.get_required_context(
+ EventType.RESEARCH_COMPLETED
+ )
+ assert isinstance(result, list)
+
+ def test_unknown_event_returns_empty(self):
+ result = NotificationTemplate.get_required_context(
+ EventType.RATE_LIMIT_WARNING
+ )
+ assert isinstance(result, list)
+
+ def test_jinja_unavailable_returns_empty(self):
+ with patch.object(
+ NotificationTemplate, "_get_jinja_env", return_value=None
+ ):
+ result = NotificationTemplate.get_required_context(
+ EventType.RESEARCH_COMPLETED
+ )
+ assert result == []
+
+
+class TestGetJinjaEnv:
+ def test_returns_environment_object(self):
+ env = NotificationTemplate._get_jinja_env()
+ assert env is not None
+
+ def test_caches_environment(self):
+ env1 = NotificationTemplate._get_jinja_env()
+ env2 = NotificationTemplate._get_jinja_env()
+ assert env1 is env2
+
+ def test_missing_templates_dir_returns_none(self):
+ with patch(f"{MODULE}.Path") as mock_path:
+ mock_path.return_value.__truediv__ = MagicMock(
+ return_value=MagicMock(exists=MagicMock(return_value=False))
+ )
+ NotificationTemplate._jinja_env = None
+ NotificationTemplate._get_jinja_env()
+ # May return None or cached env depending on Path mock depth
+
+
+class TestEventTypeEnum:
+ def test_all_event_types_exist(self):
+ assert EventType.RESEARCH_COMPLETED.value == "research_completed"
+ assert EventType.RESEARCH_FAILED.value == "research_failed"
+ assert EventType.RESEARCH_QUEUED.value == "research_queued"
+ assert EventType.TEST.value == "test"
+
+ def test_event_type_count(self):
+ assert len(EventType) >= 9
diff --git a/tests/notifications/test_url_builder_coverage.py b/tests/notifications/test_url_builder_coverage.py
new file mode 100644
index 0000000000..c4b5fc534e
--- /dev/null
+++ b/tests/notifications/test_url_builder_coverage.py
@@ -0,0 +1,119 @@
+"""Coverage tests for notifications/url_builder.py — build_notification_url."""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from local_deep_research.notifications.url_builder import (
+ build_notification_url,
+)
+from local_deep_research.security.url_validator import URLValidationError
+
+MODULE = "local_deep_research.notifications.url_builder"
+
+
+class TestBuildNotificationUrlWithSnapshot:
+ def test_with_external_url(self):
+ url = build_notification_url(
+ "/research/123",
+ settings_snapshot={"app.external_url": "https://myapp.com"},
+ validate=False,
+ )
+ assert url == "https://myapp.com/research/123"
+
+ def test_with_host_and_port(self):
+ url = build_notification_url(
+ "/research/456",
+ settings_snapshot={
+ "app.external_url": "",
+ "app.host": "0.0.0.0",
+ "app.port": 8080,
+ },
+ validate=False,
+ )
+ assert "8080" in url
+ assert "/research/456" in url
+
+ def test_fallback_base(self):
+ url = build_notification_url(
+ "/test",
+ fallback_base="http://fallback:9999",
+ validate=False,
+ )
+ assert url == "http://fallback:9999/test"
+
+
+class TestBuildNotificationUrlWithManager:
+ def test_with_settings_manager(self):
+ mock_sm = MagicMock()
+ mock_sm.get_setting.side_effect = lambda key, **kw: {
+ "app.external_url": "https://managed.com",
+ "app.host": "localhost",
+ "app.port": 5000,
+ }.get(key, kw.get("default"))
+
+ url = build_notification_url(
+ "/research/789",
+ settings_manager=mock_sm,
+ validate=False,
+ )
+ assert "managed.com" in url or "research/789" in url
+
+
+class TestBuildNotificationUrlValidation:
+ def test_valid_url_passes(self):
+ url = build_notification_url(
+ "/research/123",
+ settings_snapshot={"app.external_url": "https://valid.example.com"},
+ validate=True,
+ )
+ assert "valid.example.com" in url
+
+ def test_invalid_url_raises(self):
+ with pytest.raises(URLValidationError):
+ build_notification_url(
+ "/test",
+ settings_snapshot={
+ "app.external_url": "not-a-valid-url://???",
+ },
+ validate=True,
+ )
+
+ def test_validation_disabled(self):
+ url = build_notification_url(
+ "/test",
+ validate=False,
+ )
+ assert isinstance(url, str)
+
+
+class TestBuildNotificationUrlExceptions:
+ def test_build_error_wraps_as_url_validation_error(self):
+ with (
+ patch(
+ f"{MODULE}.build_base_url_from_settings",
+ side_effect=RuntimeError("build fail"),
+ ),
+ pytest.raises(URLValidationError),
+ ):
+ build_notification_url("/test")
+
+ def test_url_validation_error_reraises(self):
+ with (
+ patch(
+ f"{MODULE}.build_base_url_from_settings",
+ side_effect=URLValidationError("bad url"),
+ ),
+ pytest.raises(URLValidationError, match="bad url"),
+ ):
+ build_notification_url("/test")
+
+
+class TestBuildNotificationUrlDefaults:
+ def test_default_fallback_base(self):
+ url = build_notification_url("/path", validate=False)
+ assert "localhost:5000" in url
+
+ def test_empty_path(self):
+ url = build_notification_url("", validate=False)
+ assert isinstance(url, str)
diff --git a/tests/web/auth/test_decorators_coverage.py b/tests/web/auth/test_decorators_coverage.py
new file mode 100644
index 0000000000..05eb6a8f0a
--- /dev/null
+++ b/tests/web/auth/test_decorators_coverage.py
@@ -0,0 +1,287 @@
+"""Coverage tests for web/auth/decorators.py — untested branches."""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+from flask import Flask
+
+MODULE = "local_deep_research.web.auth.decorators"
+
+
+def app():
+ flask_app = Flask(__name__)
+ flask_app.secret_key = "test-secret"
+ flask_app.config["TESTING"] = True
+
+ # Register a fake auth.login endpoint for redirect tests
+ @flask_app.route("/auth/login")
+ def login():
+ return "login page"
+
+ # Register protected routes using the real decorator
+ from local_deep_research.web.auth.decorators import login_required
+
+ @flask_app.route("/page")
+ @login_required
+ def page():
+ return "ok"
+
+ @flask_app.route("/api/data")
+ @login_required
+ def api_data():
+ return "ok"
+
+ @flask_app.route("/settings/api/config")
+ @login_required
+ def settings_api():
+ return "ok"
+
+ return flask_app
+
+
+def client(app):
+ return app.test_client()
+
+
+# ---------------------------------------------------------------------------
+# login_required — unauthenticated
+# ---------------------------------------------------------------------------
+
+
+class TestLoginRequiredUnauthenticated:
+ def test_api_returns_401_json(self, client):
+ with patch(f"{MODULE}.db_manager"):
+ resp = client.get("/api/data")
+ assert resp.status_code == 401
+ assert resp.get_json()["error"] == "Authentication required"
+
+ def test_settings_api_returns_401_json(self, client):
+ with patch(f"{MODULE}.db_manager"):
+ resp = client.get("/settings/api/config")
+ assert resp.status_code == 401
+
+ def test_page_calls_safe_redirect(self, client):
+ """Non-API route triggers _safe_redirect_to_login."""
+ with (
+ patch(f"{MODULE}.db_manager"),
+ patch(
+ f"{MODULE}._safe_redirect_to_login",
+ return_value=("redirected", 302),
+ ) as mock_redirect,
+ ):
+ client.get("/page")
+ mock_redirect.assert_called_once()
+
+
+# ---------------------------------------------------------------------------
+# login_required — no db connection
+# ---------------------------------------------------------------------------
+
+
+class TestLoginRequiredNoDbConnection:
+ def test_api_returns_401_on_no_db(self, app, client):
+ with patch(f"{MODULE}.db_manager") as mock_db:
+ mock_db.is_user_connected.return_value = False
+
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+
+ resp = client.get("/api/data")
+
+ assert resp.status_code == 401
+ assert "Database connection" in resp.get_json()["error"]
+
+ def test_page_clears_session_on_no_db(self, app, client):
+ with (
+ patch(f"{MODULE}.db_manager") as mock_db,
+ patch(
+ f"{MODULE}._safe_redirect_to_login",
+ return_value=("redirected", 302),
+ ),
+ ):
+ mock_db.is_user_connected.return_value = False
+
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+
+ client.get("/page")
+
+
+# ---------------------------------------------------------------------------
+# login_required — authenticated with db
+# ---------------------------------------------------------------------------
+
+
+class TestLoginRequiredAuthenticated:
+ def test_page_succeeds(self, client):
+ with patch(f"{MODULE}.db_manager") as mock_db:
+ mock_db.is_user_connected.return_value = True
+
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+
+ resp = client.get("/page")
+
+ assert resp.status_code == 200
+
+
+# ---------------------------------------------------------------------------
+# inject_current_user
+# ---------------------------------------------------------------------------
+
+
+class TestInjectCurrentUser:
+ def test_no_user_sets_none(self, app):
+ from local_deep_research.web.auth.decorators import inject_current_user
+
+ with (
+ app.test_request_context("/"),
+ patch(f"{MODULE}.db_manager"),
+ ):
+ from flask import g
+
+ inject_current_user()
+
+ assert g.current_user is None
+ assert g.db_session is None
+
+ def test_connected_user_sets_session(self, app):
+ from local_deep_research.web.auth.decorators import inject_current_user
+
+ mock_session = MagicMock()
+ with (
+ app.test_request_context("/"),
+ patch(f"{MODULE}.db_manager") as mock_db,
+ ):
+ mock_db.is_user_connected.return_value = True
+ mock_db.get_session.return_value = mock_session
+ from flask import g, session
+
+ session["username"] = "testuser"
+
+ inject_current_user()
+
+ assert g.current_user == "testuser"
+ assert g.db_session is mock_session
+
+ def test_disconnected_user_on_api_route(self, app):
+ from local_deep_research.web.auth.decorators import inject_current_user
+
+ with (
+ app.test_request_context("/api/data"),
+ patch(f"{MODULE}.db_manager") as mock_db,
+ ):
+ mock_db.is_user_connected.return_value = False
+ from flask import g, session
+
+ session["username"] = "testuser"
+
+ inject_current_user()
+
+ # API route: user preserved but db_session is None
+ assert g.current_user == "testuser"
+ assert g.db_session is None
+
+ def test_disconnected_user_on_page_clears_session(self, app):
+ from local_deep_research.web.auth.decorators import inject_current_user
+
+ with (
+ app.test_request_context("/page"),
+ patch(f"{MODULE}.db_manager") as mock_db,
+ ):
+ mock_db.is_user_connected.return_value = False
+ from flask import g, session
+
+ session["username"] = "testuser"
+
+ inject_current_user()
+
+ assert g.current_user is None
+ assert g.db_session is None
+
+ def test_get_session_exception_sets_none(self, app):
+ from local_deep_research.web.auth.decorators import inject_current_user
+
+ with (
+ app.test_request_context("/"),
+ patch(f"{MODULE}.db_manager") as mock_db,
+ ):
+ mock_db.is_user_connected.return_value = True
+ mock_db.get_session.side_effect = RuntimeError("db error")
+ from flask import g, session
+
+ session["username"] = "testuser"
+
+ inject_current_user()
+
+ assert g.current_user == "testuser"
+ assert g.db_session is None
+
+ def test_auth_route_allows_disconnected(self, app):
+ from local_deep_research.web.auth.decorators import inject_current_user
+
+ with (
+ app.test_request_context("/auth/login"),
+ patch(f"{MODULE}.db_manager") as mock_db,
+ ):
+ mock_db.is_user_connected.return_value = False
+ from flask import g, session
+
+ session["username"] = "testuser"
+
+ inject_current_user()
+
+ # Auth route: user preserved
+ assert g.current_user == "testuser"
+
+
+# ---------------------------------------------------------------------------
+# current_user / get_current_db_session
+# ---------------------------------------------------------------------------
+
+
+class TestCurrentUser:
+ def test_returns_username(self, app):
+ from local_deep_research.web.auth.decorators import current_user
+
+ with app.test_request_context("/"):
+ from flask import session
+
+ session["username"] = "alice"
+ assert current_user() == "alice"
+
+ def test_returns_none_when_not_set(self, app):
+ from local_deep_research.web.auth.decorators import current_user
+
+ with app.test_request_context("/"):
+ assert current_user() is None
+
+
+class TestGetCurrentDbSession:
+ def test_returns_session(self, app):
+ from local_deep_research.web.auth.decorators import (
+ get_current_db_session,
+ )
+
+ mock_sess = MagicMock()
+ with (
+ app.test_request_context("/"),
+ patch(f"{MODULE}.db_manager") as mock_db,
+ ):
+ mock_db.get_session.return_value = mock_sess
+ from flask import session
+
+ session["username"] = "alice"
+
+ result = get_current_db_session()
+ assert result is mock_sess
+
+ def test_returns_none_when_no_user(self, app):
+ from local_deep_research.web.auth.decorators import (
+ get_current_db_session,
+ )
+
+ with app.test_request_context("/"):
+ assert get_current_db_session() is None
diff --git a/tests/web/models/test_calculate_duration_extra.py b/tests/web/models/test_calculate_duration_extra.py
new file mode 100644
index 0000000000..795c2ae193
--- /dev/null
+++ b/tests/web/models/test_calculate_duration_extra.py
@@ -0,0 +1,85 @@
+"""Extra coverage tests for calculate_duration edge cases in database.py."""
+
+from local_deep_research.web.models.database import calculate_duration
+
+
+class TestCalculateDurationFormats:
+ def test_iso_format_with_timezone(self):
+ result = calculate_duration(
+ "2025-01-01T00:00:00+00:00",
+ "2025-01-01T01:00:00+00:00",
+ )
+ assert result == 3600
+
+ def test_space_separated_with_microseconds(self):
+ """Space-separated + microseconds → parsed, but naive datetime
+ may fail .astimezone(); verify we get a result or None gracefully."""
+ result = calculate_duration(
+ "2025-01-01 00:00:00.000000",
+ "2025-01-01 00:01:00.000000",
+ )
+ assert result is None or isinstance(result, int)
+
+ def test_space_separated_without_microseconds(self):
+ result = calculate_duration(
+ "2025-01-01 00:00:00",
+ "2025-01-01 00:00:30",
+ )
+ assert result is None or isinstance(result, int)
+
+ def test_space_separated_fallback_replace(self):
+ """Space-separated that fails strptime → replaces space with T."""
+ result = calculate_duration(
+ "2025-01-01 10:00:00+00:00",
+ "2025-01-01 11:00:00+00:00",
+ )
+ assert result == 3600
+
+ def test_none_created_at_returns_none(self):
+ assert calculate_duration(None) is None
+ assert calculate_duration("") is None
+
+ def test_no_completed_at_uses_now(self):
+ result = calculate_duration("2020-01-01T00:00:00+00:00")
+ assert result is not None
+ assert result > 0
+
+ def test_dateutil_fallback_for_weird_format(self):
+ """If standard parsing fails, dateutil.parser is tried."""
+ result = calculate_duration(
+ "Jan 1, 2025 00:00:00",
+ "Jan 1, 2025 01:00:00",
+ )
+ # dateutil may parse this, or it may return None on tz issues
+ assert result is None or isinstance(result, int)
+
+ def test_completely_unparseable_returns_none(self):
+ result = calculate_duration("not-a-date", "also-not-a-date")
+ assert result is None
+
+ def test_unparseable_created_at_returns_none(self):
+ result = calculate_duration("garbage-date", "2025-01-01T00:00:00+00:00")
+ assert result is None
+
+
+class TestCalculateDurationEdgeCases:
+ def test_same_timestamps_returns_zero(self):
+ ts = "2025-06-15T12:00:00+00:00"
+ assert calculate_duration(ts, ts) == 0
+
+ def test_negative_duration(self):
+ """completed_at before created_at → negative seconds."""
+ result = calculate_duration(
+ "2025-01-01T01:00:00+00:00",
+ "2025-01-01T00:00:00+00:00",
+ )
+ assert result == -3600
+
+ def test_mixed_formats(self):
+ """created_at is ISO, completed_at is space-separated."""
+ result = calculate_duration(
+ "2025-01-01T00:00:00+00:00",
+ "2025-01-01 01:00:00",
+ )
+ # Should still calculate correctly
+ assert result is not None