~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
"""Tests for the calculate_warnings orchestrator (__init__.py).
These test the integration logic: DB session lifecycle, setting dispatch
to sub-checks, and error handling.
Ported from the Flask-era harness (main's test_orchestrator.py), which
patched a module-level ``session`` dict to fake a Flask request context.
Under FastAPI there is no request-scoped session object: calculate_warnings
takes ``username`` as an explicit parameter (populated by routers from
``Depends(require_auth)`` — see web/routers/settings.py:818 and :2154), so
these tests call it directly with a ``username=`` kwarg instead of patching
a fake session.
"""
import errno
import os
import stat
from pathlib import Path
from unittest.mock import Mock, patch
import pytest
def _make_settings_manager(overrides=None):
"""Build a mock SettingsManager with sensible defaults covering every
setting calculate_warnings() reads (hardware/context + egress + backup).
"""
defaults = {
"llm.provider": "ollama",
"llm.local_context_window_size": 4096,
"llm.model": "llama3",
"app.warnings.dismiss_high_context": False,
"app.warnings.dismiss_model_mismatch": False,
"app.warnings.dismiss_context_below_history": False,
"app.warnings.dismiss_context_truncation_history": False,
"app.warnings.dismiss_legacy_config": False,
"app.warnings.dismiss_no_backups": False,
"app.warnings.dismiss_backup_disabled": False,
"app.warnings.dismiss_backup_info": False,
"backup.enabled": True,
"policy.egress_scope": "adaptive",
"llm.require_local_endpoint": False,
"embeddings.provider": "",
"embeddings.openai.base_url": "",
"embeddings.require_local": False,
"search.tool": "searxng",
"policy.trusted_inference_providers": [],
"policy.trusted_search_engines": [],
"app.warnings.dismiss_adaptive_scope_info": False,
"app.warnings.dismiss_egress_policy": False,
"app.warnings.dismiss_cloud_llm": False,
"app.warnings.dismiss_cloud_embeddings": False,
}
if overrides:
defaults.update(overrides)
mgr = Mock()
mgr.get_setting.side_effect = lambda key, default=None: defaults.get(
key, default
)
# Not a dict by default => the effective-scope resolution in
# calculate_warnings (context_from_snapshot) is skipped and it falls
# back to the raw settings-manager values above (isinstance check at
# web/warning_checks/__init__.py:174).
mgr.get_settings_snapshot.return_value = None
return mgr
def _patch_orchestrator(settings_manager, db_session=None):
"""Return a nested context manager that patches get_user_db_session and
get_settings_manager for the warnings orchestrator — the FastAPI
equivalent of main's Flask-session-patching helper.
"""
if db_session is None:
db_session = Mock()
class _Ctx:
def __enter__(self_ctx):
self_ctx.p1 = patch(
"local_deep_research.web.warning_checks.get_user_db_session"
)
self_ctx.p2 = patch(
"local_deep_research.web.warning_checks.get_settings_manager",
return_value=settings_manager,
)
mock_ctx = self_ctx.p1.start()
mock_ctx.return_value.__enter__ = Mock(return_value=db_session)
mock_ctx.return_value.__exit__ = Mock(return_value=False)
self_ctx.p2.start()
return self_ctx
def __exit__(self_ctx, *args):
self_ctx.p2.stop()
self_ctx.p1.stop()
return _Ctx()
class TestCalculateWarningsNoDbSession:
"""Tests for the early-return guards before any check runs."""
def test_returns_empty_list_when_no_username(self):
from local_deep_research.web.warning_checks import calculate_warnings
# No username => must short-circuit BEFORE ever opening a DB
# session (there's nothing to open it with under FastAPI).
with patch(
"local_deep_research.web.warning_checks.get_user_db_session"
) as mock_ctx:
result = calculate_warnings(username=None)
assert result == []
mock_ctx.assert_not_called()
def test_returns_empty_list_when_db_session_is_none(self):
from local_deep_research.web.warning_checks import calculate_warnings
with patch(
"local_deep_research.web.warning_checks.get_user_db_session"
) as mock_ctx:
mock_ctx.return_value.__enter__ = Mock(return_value=None)
mock_ctx.return_value.__exit__ = Mock(return_value=False)
result = calculate_warnings(username="test")
assert result == []
class TestCalculateWarningsErrorHandling:
"""Tests for exception handling — every failure mode returns []
rather than propagating, since this feeds a settings-page banner."""
def test_returns_empty_list_on_exception(self):
from local_deep_research.web.warning_checks import calculate_warnings
with patch(
"local_deep_research.web.warning_checks.get_user_db_session",
side_effect=RuntimeError("DB exploded"),
):
result = calculate_warnings(username="test")
assert result == []
def test_returns_empty_list_on_settings_manager_error(self):
from local_deep_research.web.warning_checks import calculate_warnings
with patch(
"local_deep_research.web.warning_checks.get_user_db_session"
) as mock_ctx:
mock_ctx.return_value.__enter__ = Mock(return_value=Mock())
mock_ctx.return_value.__exit__ = Mock(return_value=False)
with patch(
"local_deep_research.web.warning_checks.get_settings_manager",
side_effect=ValueError("bad settings"),
):
result = calculate_warnings(username="test")
assert result == []
class TestCalculateWarningsProviderNormalization:
"""Provider string is lowercased before checks."""
def test_uppercase_provider_is_normalized(self):
from local_deep_research.web.warning_checks import calculate_warnings
mgr = _make_settings_manager(
{
"llm.provider": "OLLAMA",
"llm.local_context_window_size": 16384,
}
)
with _patch_orchestrator(mgr):
warnings = calculate_warnings(username="test")
assert any(w["type"] == "high_context" for w in warnings)
class TestCalculateWarningsContextCheckGating:
"""Context history checks are gated on is_local AND not dismissed."""
def test_context_checks_skipped_for_non_local_provider(self):
"""A non-local (cloud) provider should never trigger the DB-backed
context-history checks, even when history would normally warn."""
from local_deep_research.web.warning_checks import calculate_warnings
mock_db_session = Mock()
mgr = _make_settings_manager(
{
"llm.provider": "openai",
"llm.local_context_window_size": 2048,
"app.warnings.dismiss_context_below_history": False,
"app.warnings.dismiss_context_truncation_history": False,
}
)
with _patch_orchestrator(mgr, db_session=mock_db_session):
warnings = calculate_warnings(username="test")
# DB should not have been queried for context history at all.
mock_db_session.query.assert_not_called()
assert not any(w["type"] == "context_below_history" for w in warnings)
assert not any(
w["type"] == "context_truncation_history" for w in warnings
)
def test_context_checks_skipped_when_dismissed(self):
"""Both dismissed context warnings should skip the DB queries."""
from local_deep_research.web.warning_checks import calculate_warnings
mock_db_session = Mock()
mgr = _make_settings_manager(
{
"llm.provider": "ollama",
"llm.local_context_window_size": 2048,
"app.warnings.dismiss_context_below_history": True,
"app.warnings.dismiss_context_truncation_history": True,
}
)
with _patch_orchestrator(mgr, db_session=mock_db_session):
warnings = calculate_warnings(username="test")
mock_db_session.query.assert_not_called()
assert not any(w["type"] == "context_below_history" for w in warnings)
class TestCalculateWarningsDismissalIndependence:
"""Each warning's dismiss flag is independent of the others."""
def test_below_history_can_be_dismissed_independently(self):
from local_deep_research.web.warning_checks import calculate_warnings
mgr = _make_settings_manager(
{
"app.warnings.dismiss_context_below_history": True,
"app.warnings.dismiss_context_truncation_history": False,
}
)
with _patch_orchestrator(mgr):
with patch(
"local_deep_research.web.warning_checks.check_context_below_history"
) as below_check:
with patch(
"local_deep_research.web.warning_checks.check_context_truncation_history"
) as truncation_check:
calculate_warnings(username="test")
below_check.assert_not_called()
truncation_check.assert_called_once()
def test_truncation_history_can_be_dismissed_independently(self):
from local_deep_research.web.warning_checks import calculate_warnings
mgr = _make_settings_manager(
{
"app.warnings.dismiss_context_below_history": False,
"app.warnings.dismiss_context_truncation_history": True,
}
)
with _patch_orchestrator(mgr):
with patch(
"local_deep_research.web.warning_checks.check_context_below_history"
) as below_check:
with patch(
"local_deep_research.web.warning_checks.check_context_truncation_history"
) as truncation_check:
calculate_warnings(username="test")
below_check.assert_called_once()
truncation_check.assert_not_called()
def test_high_context_can_be_dismissed_independently_of_model_mismatch(
self,
):
"""Dismissing high_context alone must not silence model_mismatch,
even though both are driven by the same provider/context/model
settings."""
from local_deep_research.web.warning_checks import calculate_warnings
mgr = _make_settings_manager(
{
"llm.provider": "ollama",
"llm.local_context_window_size": 16384,
"llm.model": "llama3.1:70b",
"app.warnings.dismiss_high_context": True,
"app.warnings.dismiss_model_mismatch": False,
}
)
with _patch_orchestrator(mgr):
warnings = calculate_warnings(username="test")
types = {w["type"] for w in warnings}
assert "high_context" not in types
assert "model_mismatch" in types
class TestCalculateWarningsMultipleWarnings:
"""Several warnings can fire simultaneously without interfering."""
def test_high_context_and_model_mismatch_together(self):
from local_deep_research.web.warning_checks import calculate_warnings
mgr = _make_settings_manager(
{
"llm.provider": "ollama",
"llm.local_context_window_size": 16384,
"llm.model": "llama3.1:70b",
}
)
with _patch_orchestrator(mgr):
warnings = calculate_warnings(username="test")
types = {w["type"] for w in warnings}
assert "high_context" in types
assert "model_mismatch" in types
def test_high_context_and_context_history_together(self):
from local_deep_research.web.warning_checks import calculate_warnings
mock_db_session = Mock()
context_query = Mock()
context_query.filter.return_value.order_by.return_value.limit.return_value.all.return_value = (
[(32768,)] * 10
)
truncation_query = Mock()
truncation_query.filter.return_value.filter.return_value.scalar.return_value = 5
mock_db_session.query.side_effect = [context_query, truncation_query]
mgr = _make_settings_manager(
{
"llm.provider": "ollama",
"llm.local_context_window_size": 16384,
}
)
with _patch_orchestrator(mgr, db_session=mock_db_session):
warnings = calculate_warnings(username="test")
types = {w["type"] for w in warnings}
assert "high_context" in types
assert "context_below_history" in types
assert "context_truncation_history" in types
def test_several_warnings_co_occur(self, tmp_path):
"""Hardware, context-history, backup and egress-advisory warnings
can all fire on the same call, each independently."""
from local_deep_research.web.warning_checks import calculate_warnings
mock_db_session = Mock()
context_query = Mock()
context_query.filter.return_value.order_by.return_value.limit.return_value.all.return_value = (
[(32768,)] * 10
)
truncation_query = Mock()
truncation_query.filter.return_value.filter.return_value.scalar.return_value = 2
mock_db_session.query.side_effect = [context_query, truncation_query]
mgr = _make_settings_manager(
{
"llm.provider": "ollama",
"llm.local_context_window_size": 16384,
"llm.model": "llama3.1:70b",
}
)
# tmp_path is an empty real directory: listing it finds no
# ldr_backup_*.db files -> backup_count == 0 -> "no_backups" fires
# (backup.enabled defaults to True in _make_settings_manager).
with _patch_orchestrator(mgr, db_session=mock_db_session):
with (
patch(
"local_deep_research.web.server_config.get_server_config_path",
return_value=Mock(exists=Mock(return_value=False)),
),
patch(
"local_deep_research.config.paths.get_user_backup_directory",
return_value=tmp_path,
),
):
warnings = calculate_warnings(username="test")
types = {w["type"] for w in warnings}
assert types == {
"high_context",
"model_mismatch",
"context_below_history",
"context_truncation_history",
"no_backups",
# policy.egress_scope defaults to "adaptive" (unacknowledged):
# the public-egress banner fires (adaptive can resolve to a
# public-allowing scope) alongside the informational banner
# stating what adaptive resolves to (no real snapshot dict is
# configured, so effective_scope falls back to the raw
# "adaptive" value — see web/warning_checks/__init__.py:174).
"public_egress_enabled",
"egress_effective_scope",
}
class TestCalculateWarningsSingleSession:
"""Verify all settings are read from a single DB session (the point of
the orchestrator refactor cited in __init__.py's module docstring)."""
def test_get_user_db_session_called_once(self):
"""The orchestrator should open exactly one DB session per call."""
from local_deep_research.web.warning_checks import calculate_warnings
mgr = _make_settings_manager()
with patch(
"local_deep_research.web.warning_checks.get_user_db_session"
) as mock_ctx:
mock_ctx.return_value.__enter__ = Mock(return_value=Mock())
mock_ctx.return_value.__exit__ = Mock(return_value=False)
with patch(
"local_deep_research.web.warning_checks.get_settings_manager",
return_value=mgr,
):
calculate_warnings(username="test")
assert mock_ctx.call_count == 1
def test_get_user_db_session_called_with_username(self):
"""The username passed to calculate_warnings flows through to
get_user_db_session unchanged."""
from local_deep_research.web.warning_checks import calculate_warnings
mgr = _make_settings_manager()
with patch(
"local_deep_research.web.warning_checks.get_user_db_session"
) as mock_get_db:
mock_get_db.return_value.__enter__ = Mock(return_value=Mock())
mock_get_db.return_value.__exit__ = Mock(return_value=False)
with patch(
"local_deep_research.web.warning_checks.get_settings_manager",
return_value=mgr,
):
calculate_warnings(username="alice")
mock_get_db.assert_called_once_with("alice")
def test_get_settings_manager_called_with_session_and_username(self):
"""Both the acquired db_session and username are forwarded to
get_settings_manager."""
from local_deep_research.web.warning_checks import calculate_warnings
mgr = _make_settings_manager()
mock_db = Mock()
with patch(
"local_deep_research.web.warning_checks.get_user_db_session"
) as mock_get_db:
mock_get_db.return_value.__enter__ = Mock(return_value=mock_db)
mock_get_db.return_value.__exit__ = Mock(return_value=False)
with patch(
"local_deep_research.web.warning_checks.get_settings_manager",
return_value=mgr,
) as mock_get_sm:
calculate_warnings(username="bob")
mock_get_sm.assert_called_once_with(mock_db, "bob")
class TestCalculateWarningsFailureIsolation:
"""Verify _safe_check isolates one check's crash from the rest."""
def test_first_check_crash_does_not_kill_second(self):
"""If check_high_context raises, check_model_mismatch still runs."""
from local_deep_research.web.warning_checks import calculate_warnings
mgr = _make_settings_manager(
{
"llm.provider": "ollama",
"llm.local_context_window_size": 16384,
"llm.model": "llama3.1:70b",
}
)
with _patch_orchestrator(mgr):
with patch(
"local_deep_research.web.warning_checks.check_high_context",
side_effect=RuntimeError("boom"),
):
warnings = calculate_warnings(username="test")
types = {w["type"] for w in warnings}
assert "high_context" not in types
assert "model_mismatch" in types
def test_context_check_crash_does_not_kill_other_context_check(self):
"""If check_context_below_history raises, check_context_truncation_history still runs."""
from local_deep_research.web.warning_checks import calculate_warnings
mock_db_session = Mock()
truncation_query = Mock()
truncation_query.filter.return_value.filter.return_value.scalar.return_value = 3
mock_db_session.query.return_value = truncation_query
mgr = _make_settings_manager(
{
"llm.provider": "ollama",
"llm.local_context_window_size": 4096,
}
)
with _patch_orchestrator(mgr, db_session=mock_db_session):
with patch(
"local_deep_research.web.warning_checks.check_context_below_history",
side_effect=RuntimeError("db query failed"),
):
warnings = calculate_warnings(username="test")
types = {w["type"] for w in warnings}
assert "context_below_history" not in types
assert "context_truncation_history" in types
class TestCalculateWarningsNoneProvider:
"""Document behavior when provider setting is None."""
def test_none_provider_does_not_crash(self):
"""If get_setting returns None for provider, outer try/except catches the AttributeError."""
from local_deep_research.web.warning_checks import calculate_warnings
mgr = Mock()
mgr.get_setting.side_effect = lambda key, default=None: {
"llm.provider": None,
"llm.local_context_window_size": 4096,
"llm.model": "llama3",
"app.warnings.dismiss_high_context": False,
"app.warnings.dismiss_model_mismatch": False,
"app.warnings.dismiss_context_below_history": False,
"app.warnings.dismiss_context_truncation_history": False,
}.get(key, default)
with _patch_orchestrator(mgr):
result = calculate_warnings(username="test")
# Should not crash — outer except catches AttributeError from None.lower()
assert isinstance(result, list)
class TestCalculateWarningsBackupGlobHardening:
"""The backup listing in calculate_warnings() must skip symlinks, so a
planted symlink cannot inflate the backup count/size used for warnings,
and must not mistake a directory it cannot read for an empty one.
"""
def test_symlink_is_not_counted_as_a_backup(self, tmp_path):
from local_deep_research.web.warning_checks import calculate_warnings
backup_dir = tmp_path / "backups"
backup_dir.mkdir()
# The ONLY entry matching the glob is a symlink to an existing file
# outside the backup dir. With the hardening it is skipped, leaving
# zero real backups; without it, stat() would follow the link and
# count it.
outside = tmp_path / "outside_secret.db"
outside.write_bytes(b"x" * 4096)
(backup_dir / "ldr_backup_29991231_235959.db").symlink_to(outside)
settings_manager = _make_settings_manager() # backup.enabled=True
with _patch_orchestrator(settings_manager):
with patch(
"local_deep_research.config.paths.get_user_backup_directory",
return_value=backup_dir,
):
warnings = calculate_warnings(username="test")
types = {w["type"] for w in warnings}
# Symlink excluded -> backup_count == 0 -> the "no backups" warning
# fires and no "backup_info" (which would carry the link target size).
assert "no_backups" in types
assert "backup_info" not in types
@pytest.mark.nonroot
def test_unlistable_directory_is_not_reported_as_having_no_backups(
self, tmp_path, loguru_caplog
):
"""Path.glob returns nothing for a directory it cannot read, so a
real permission denial is needed (root and Windows do not enforce
one). Neither banner may be claimed when the count is unknown, and
the skip leaves a warning for operators."""
from local_deep_research.web.warning_checks import calculate_warnings
if os.name != "posix" or os.geteuid() == 0:
pytest.skip("permission bits are not enforced for root or Windows")
backup_dir = tmp_path / "backups"
backup_dir.mkdir()
(backup_dir / "ldr_backup_20260101_000000.db").write_bytes(b"x")
backup_dir.chmod(0o300)
try:
with loguru_caplog.at_level("DEBUG"):
with _patch_orchestrator(_make_settings_manager()):
with patch(
"local_deep_research.config.paths.get_user_backup_directory",
return_value=backup_dir,
):
warnings = calculate_warnings(username="test")
finally:
backup_dir.chmod(0o700)
types = {w["type"] for w in warnings}
assert "no_backups" not in types
assert "backup_info" not in types
skipped = [
record.getMessage()
for record in loguru_caplog.records
if record.levelname == "DEBUG"
and "Backup banners skipped" in record.getMessage()
]
assert len(skipped) == 1
assert "PermissionError" in skipped[0]
assert str(tmp_path) not in skipped[0]
class TestCalculateWarningsUnprotectedBannerUsesEffectiveScope:
"""The loud "protection disabled" banner must be driven by the RESOLVED
effective scope, not the raw stored value. A stale ``unprotected`` row
left over from before the operator gate existed must NOT light the banner
once the gate is off (context_from_snapshot coerces it to adaptive) — and
the banner must still fire when the operator has enabled the gate.
Pins the effective_scope wiring in calculate_warnings(): reverting it to
feed the raw egress_scope would fail the gate-off case here.
"""
def _manager_with_stale_unprotected(self):
mgr = _make_settings_manager(
{
"policy.egress_scope": "unprotected",
"search.tool": "wikipedia",
}
)
# context_from_snapshot resolves the effective posture from this.
mgr.get_settings_snapshot.return_value = {
"policy.egress_scope": "unprotected",
"search.tool": "wikipedia",
}
return mgr
def test_no_banner_for_stale_unprotected_when_gate_off(self, monkeypatch):
from local_deep_research.web.warning_checks import calculate_warnings
monkeypatch.delenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", raising=False)
with _patch_orchestrator(self._manager_with_stale_unprotected()):
warnings = calculate_warnings(username="test")
assert "egress_unprotected" not in {w["type"] for w in warnings}
def test_banner_fires_when_gate_enabled(self, monkeypatch):
from local_deep_research.web.warning_checks import calculate_warnings
monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")
with _patch_orchestrator(self._manager_with_stale_unprotected()):
warnings = calculate_warnings(username="test")
assert "egress_unprotected" in {w["type"] for w in warnings}
def test_adaptive_warnings_resolve_padded_private_primary():
from local_deep_research.web.warning_checks import calculate_warnings
manager = _make_settings_manager(
{"search.tool": " library ", "llm.provider": "openai"}
)
manager.get_settings_snapshot.return_value = {
"policy.egress_scope": "adaptive",
"search.tool": " library ",
}
with _patch_orchestrator(manager):
warnings = calculate_warnings(username="alice")
types = {warning["type"] for warning in warnings}
assert "public_egress_enabled" not in types
assert "cloud_llm_enabled" not in types
class TestSearxngPrivateUrlWarning:
"""Orchestrator wiring for the SearXNG private-URL banner."""
APPROVAL_ENVS = (
"LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS",
"LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST",
"LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL",
)
def _run(self, overrides, monkeypatch):
for var in self.APPROVAL_ENVS:
monkeypatch.delenv(var, raising=False)
from local_deep_research.web.warning_checks import calculate_warnings
mgr = _make_settings_manager(overrides)
with _patch_orchestrator(mgr):
return calculate_warnings(username="test")
def test_banner_emitted_for_unapproved_searxng(self, monkeypatch):
warnings = self._run(
{
"search.tool": "searxng",
"search.engine.web.searxng.default_params.instance_url": (
"http://localhost:8080"
),
},
monkeypatch,
)
assert "searxng_private_url_blocked" in {w["type"] for w in warnings}
def test_banner_respects_dismiss_flag(self, monkeypatch):
warnings = self._run(
{
"search.tool": "searxng",
"search.engine.web.searxng.default_params.instance_url": (
"http://localhost:8080"
),
"app.warnings.dismiss_searxng_private_url": True,
},
monkeypatch,
)
assert "searxng_private_url_blocked" not in {
w["type"] for w in warnings
}
def test_banner_fires_when_enabled_for_auto_search_not_primary(
self, monkeypatch
):
"""Real default settings ship use_in_auto_search=True for SearXNG, so
the engine is used by the langgraph strategy even when another
engine is primary — the banner must still fire (it would silently
self-disable in those runs too)."""
warnings = self._run(
{
"search.tool": "wikipedia",
"search.engine.web.searxng.use_in_auto_search": True,
"search.engine.web.searxng.default_params.instance_url": (
"http://localhost:8080"
),
},
monkeypatch,
)
assert "searxng_private_url_blocked" in {w["type"] for w in warnings}
def test_no_banner_when_not_primary_and_all_flags_off(self, monkeypatch):
"""Only when SearXNG is neither primary nor enabled by any
activation flag is the banner silent."""
warnings = self._run(
{
"search.tool": "wikipedia",
"search.engine.web.searxng.use_in_auto_search": False,
"search.engine.web.searxng.agent_enabled": False,
"search.engine.web.searxng.default_params.instance_url": (
"http://localhost:8080"
),
},
monkeypatch,
)
assert "searxng_private_url_blocked" not in {
w["type"] for w in warnings
}
def test_elasticsearch_cloud_id_reaches_banner(self, monkeypatch):
"""The ES cloud_id branch: a set cloud_id fires the public-URL
banner even when every listed host is private."""
for var in self.APPROVAL_ENVS:
monkeypatch.delenv(var, raising=False)
from local_deep_research.web.warning_checks import calculate_warnings
mgr = _make_settings_manager(
{
"search.engine.web.elasticsearch.use_in_auto_search": True,
"search.engine.web.elasticsearch.default_params.hosts": [
"http://localhost:9200"
],
"search.engine.web.elasticsearch.default_params.cloud_id": (
"my-deployment:abc123"
),
}
)
with _patch_orchestrator(mgr):
warnings = calculate_warnings(username="test")
es = [w for w in warnings if w["type"] == "elasticsearch_public_url"]
assert es and "Elastic Cloud" in es[0]["message"]
def test_no_banner_when_operator_approved(self, monkeypatch):
for var in self.APPROVAL_ENVS:
monkeypatch.delenv(var, raising=False)
monkeypatch.setenv(
"LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST", "http://localhost:8080"
)
from local_deep_research.web.warning_checks import calculate_warnings
mgr = _make_settings_manager(
{
"search.tool": "searxng",
"search.engine.web.searxng.default_params.instance_url": (
"http://localhost:8080"
),
}
)
with _patch_orchestrator(mgr):
warnings = calculate_warnings(username="test")
assert "searxng_private_url_blocked" not in {
w["type"] for w in warnings
}
class TestLocalEnginePublicUrlWarnings:
"""Orchestrator wiring for the Paperless / Elasticsearch banners."""
def test_paperless_banner_when_enabled_with_public_url(self):
from local_deep_research.web.warning_checks import calculate_warnings
mgr = _make_settings_manager(
{
"search.engine.web.paperless.enabled": True,
"search.engine.web.paperless.default_params.api_url": (
"https://paperless.example.com"
),
}
)
with _patch_orchestrator(mgr):
warnings = calculate_warnings(username="test")
assert "paperless_public_url" in {w["type"] for w in warnings}
def test_paperless_silent_when_disabled(self):
from local_deep_research.web.warning_checks import calculate_warnings
mgr = _make_settings_manager(
{
"search.engine.web.paperless.enabled": False,
"search.engine.web.paperless.default_params.api_url": (
"https://paperless.example.com"
),
}
)
with _patch_orchestrator(mgr):
warnings = calculate_warnings(username="test")
assert "paperless_public_url" not in {w["type"] for w in warnings}
def test_elasticsearch_banner_for_public_host(self):
from local_deep_research.web.warning_checks import calculate_warnings
mgr = _make_settings_manager(
{
"search.engine.web.elasticsearch.use_in_auto_search": True,
"search.engine.web.elasticsearch.default_params.hosts": [
"https://es.example.com:9200"
],
}
)
with _patch_orchestrator(mgr):
warnings = calculate_warnings(username="test")
assert "elasticsearch_public_url" in {w["type"] for w in warnings}
def test_elasticsearch_silent_for_default_localhost(self):
from local_deep_research.web.warning_checks import calculate_warnings
mgr = _make_settings_manager(
{
"search.engine.web.elasticsearch.use_in_auto_search": True,
"search.engine.web.elasticsearch.default_params.hosts": [
"http://localhost:9200"
],
}
)
with _patch_orchestrator(mgr):
warnings = calculate_warnings(username="test")
assert "elasticsearch_public_url" not in {w["type"] for w in warnings}
class TestCalculateWarningsLegacyServerConfig:
"""Orchestrator coverage for the legacy_server_config check.
Restored from main during the FastAPI merge: the check is still wired in
``calculate_warnings`` (``_safe_check(check_legacy_server_config, ...)``),
so dropping its tests would have left live code uncovered. Calls pass an
explicit username because the FastAPI orchestrator returns [] without one
-- a bare call would make every negative assertion below pass vacuously.
"""
def test_legacy_server_config_warning_when_file_exists(self):
"""server_config.json on disk with non-default values -> warning."""
from local_deep_research.web.warning_checks import calculate_warnings
mgr = _make_settings_manager()
mock_path = Mock()
mock_path.exists.return_value = True
mock_path.read_text.return_value = '{"port": 9999}'
with _patch_orchestrator(mgr):
with patch(
"local_deep_research.web.server_config.get_server_config_path",
return_value=mock_path,
):
warnings = calculate_warnings(username="test")
assert "legacy_server_config" in {w["type"] for w in warnings}
def test_no_legacy_server_config_warning_when_file_absent(self):
"""No file -> no warning."""
from local_deep_research.web.warning_checks import calculate_warnings
mgr = _make_settings_manager()
with _patch_orchestrator(mgr):
with patch(
"local_deep_research.web.server_config.get_server_config_path",
return_value=Mock(exists=Mock(return_value=False)),
):
warnings = calculate_warnings(username="test")
assert "legacy_server_config" not in {w["type"] for w in warnings}
def test_no_legacy_server_config_warning_when_dismissed(self):
"""Dismissed -> no warning even when the file exists."""
from local_deep_research.web.warning_checks import calculate_warnings
mgr = _make_settings_manager(
{"app.warnings.dismiss_legacy_config": True}
)
with _patch_orchestrator(mgr):
with patch(
"local_deep_research.web.server_config.get_server_config_path",
return_value=Mock(exists=Mock(return_value=True)),
):
warnings = calculate_warnings(username="test")
assert "legacy_server_config" not in {w["type"] for w in warnings}
class TestCalculateWarningsReadsItsSettings:
"""Restored from main: pins that the orchestrator actually reads each
setting it branches on. A check that stops reading its dismiss key would
silently ignore the user's dismissal."""
def test_all_required_settings_read(self):
from local_deep_research.web.warning_checks import calculate_warnings
mgr = _make_settings_manager()
with _patch_orchestrator(mgr):
calculate_warnings(username="test")
called_keys = [call.args[0] for call in mgr.get_setting.call_args_list]
for key in (
"llm.provider",
"llm.local_context_window_size",
"llm.model",
"app.warnings.dismiss_high_context",
"app.warnings.dismiss_model_mismatch",
"app.warnings.dismiss_context_below_history",
"app.warnings.dismiss_context_truncation_history",
"app.warnings.dismiss_legacy_config",
):
assert key in called_keys, f"{key} is never read"
class TestReportBackupUnavailableBanner:
"""Report file backups that are on but refused get a visible banner."""
@staticmethod
def _warnings(tmp_path, monkeypatch, enabled):
from local_deep_research.web.warning_checks import calculate_warnings
monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
mgr = _make_settings_manager({"report.enable_file_backup": enabled})
with _patch_orchestrator(mgr):
with patch(
"local_deep_research.config.paths.get_user_backup_directory",
return_value=tmp_path,
):
return calculate_warnings(username="test")
@staticmethod
def _banners(warnings):
return [w for w in warnings if w["type"] == "report_backup_unavailable"]
@pytest.mark.skipif(os.name != "posix", reason="POSIX ownership and modes")
@pytest.mark.parametrize(
"breakage, cause",
[
("mode_not_kept", "does not keep owner-only permissions"),
("foreign_owner", "another OS account owns"),
("chmod_error", "could not make its research_outputs folder"),
],
)
def test_refused_backup_directory_shows_cause_and_remedy(
self, tmp_path, monkeypatch, breakage, cause
):
root = tmp_path / "research_outputs"
root.mkdir()
root.chmod(0o755)
if breakage == "mode_not_kept":
# A drvfs or CIFS mount: chmod succeeds and changes nothing.
monkeypatch.setattr(
Path, "chmod", lambda self, mode, **kwargs: None
)
elif breakage == "foreign_owner":
other_uid = root.stat().st_uid + 1
monkeypatch.setattr(os, "geteuid", lambda: other_uid)
else:
def read_only(self, mode, **kwargs):
raise OSError(errno.EROFS, "Read-only file system")
monkeypatch.setattr(Path, "chmod", read_only)
banners = self._banners(
self._warnings(tmp_path, monkeypatch, enabled=True)
)
assert len(banners) == 1, "refused report backups raised no banner"
banner = banners[0]
assert cause in banner["message"]
assert "Docker named volume" in banner["message"]
assert "turn off report file backup" in banner["message"]
assert banner["dismissKey"] is None
assert (
banner["actionUrl"] == "/settings#setting-report-enable_file_backup"
)
@pytest.mark.skipif(os.name != "posix", reason="POSIX mode bits")
def test_no_banner_for_a_directory_that_can_be_made_private(
self, tmp_path, monkeypatch
):
root = tmp_path / "research_outputs"
root.mkdir()
root.chmod(0o755)
warnings = self._warnings(tmp_path, monkeypatch, enabled=True)
assert self._banners(warnings) == []
@pytest.mark.skipif(os.name != "posix", reason="POSIX mode bits")
def test_backups_off_means_no_banner_and_no_directory_change(
self, tmp_path, monkeypatch
):
root = tmp_path / "research_outputs"
root.mkdir()
root.chmod(0o755)
warnings = self._warnings(tmp_path, monkeypatch, enabled=False)
assert self._banners(warnings) == []
assert stat.S_IMODE(root.stat().st_mode) == 0o755