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.

8.4 KB
Raw Blame
"""Tests for server_config.py uncovered branches."""

import json
from unittest.mock import patch

import pytest

from local_deep_research.settings.exceptions import SettingsValueError
from local_deep_research.web.server_config import (
    _DEFAULTS,
    _load_legacy_config,
    has_legacy_customizations,
    load_server_config,
)


class TestHasLegacyCustomizations:
    def test_no_file_returns_false(self, tmp_path):
        assert has_legacy_customizations(tmp_path / "missing.json") is False

    def test_invalid_json_returns_false(self, tmp_path):
        p = tmp_path / "bad.json"
        p.write_text("not json{{{", encoding="utf-8")
        assert has_legacy_customizations(p) is False

    def test_permission_error_returns_false(self, tmp_path):
        """An unreadable optional legacy file must not break startup checks."""
        p = tmp_path / "unreadable.json"
        p.write_text('{"port": 9999}', encoding="utf-8")

        with patch.object(
            type(p),
            "read_text",
            side_effect=PermissionError("legacy config is unreadable"),
        ):
            assert has_legacy_customizations(p) is False

    def test_non_dict_json_returns_false(self, tmp_path):
        p = tmp_path / "list.json"
        p.write_text("[1,2,3]", encoding="utf-8")
        assert has_legacy_customizations(p) is False

    def test_all_defaults_returns_false(self, tmp_path):
        p = tmp_path / "config.json"
        p.write_text(json.dumps(_DEFAULTS), encoding="utf-8")
        assert has_legacy_customizations(p) is False

    def test_non_default_value_returns_true(self, tmp_path):
        p = tmp_path / "config.json"
        data = {"port": 9999}
        p.write_text(json.dumps(data), encoding="utf-8")
        assert has_legacy_customizations(p) is True

    def test_unrecognized_key_returns_true(self, tmp_path):
        p = tmp_path / "config.json"
        data = {"unknown_key": "value"}
        p.write_text(json.dumps(data), encoding="utf-8")
        assert has_legacy_customizations(p) is True

    def test_empty_dict_returns_false(self, tmp_path):
        p = tmp_path / "config.json"
        p.write_text("{}", encoding="utf-8")
        assert has_legacy_customizations(p) is False


class TestLoadLegacyConfig:
    def test_no_file_returns_empty(self, tmp_path):
        with patch(
            "local_deep_research.web.server_config.get_server_config_path",
            return_value=tmp_path / "missing.json",
        ):
            assert _load_legacy_config() == {}

    def test_invalid_json_returns_empty(self, tmp_path):
        p = tmp_path / "bad.json"
        p.write_text("{broken", encoding="utf-8")
        with patch(
            "local_deep_research.web.server_config.get_server_config_path",
            return_value=p,
        ):
            assert _load_legacy_config() == {}

    def test_permission_error_returns_empty_and_warns(self, tmp_path):
        """The migration fallback degrades cleanly when the file cannot read."""
        p = tmp_path / "unreadable.json"
        p.write_text('{"port": 9999}', encoding="utf-8")

        with (
            patch(
                "local_deep_research.web.server_config.get_server_config_path",
                return_value=p,
            ),
            patch.object(
                type(p),
                "read_text",
                side_effect=PermissionError("legacy config is unreadable"),
            ),
            patch("local_deep_research.web.server_config.logger") as logger,
        ):
            assert _load_legacy_config() == {}

        logger.warning.assert_called_once()
        assert (
            "Could not read legacy server_config.json"
            in (logger.warning.call_args.args[0])
        )

    def test_non_dict_returns_empty(self, tmp_path):
        p = tmp_path / "list.json"
        p.write_text('"just a string"', encoding="utf-8")
        with patch(
            "local_deep_research.web.server_config.get_server_config_path",
            return_value=p,
        ):
            assert _load_legacy_config() == {}

    def test_recognized_keys_extracted(self, tmp_path):
        p = tmp_path / "config.json"
        p.write_text(
            json.dumps({"host": "localhost", "port": 8080}), encoding="utf-8"
        )
        with patch(
            "local_deep_research.web.server_config.get_server_config_path",
            return_value=p,
        ):
            result = _load_legacy_config()
            assert result["host"] == "localhost"
            assert result["port"] == 8080

    def test_utf8_bom_prefixed_json_is_loaded(self, tmp_path):
        """Keep compatibility with JSON written by BOM-emitting editors."""
        p = tmp_path / "bom-config.json"
        payload = json.dumps({"host": "0.0.0.0", "port": 8123}).encode()
        p.write_bytes(b"\xef\xbb\xbf" + payload)

        with patch(
            "local_deep_research.web.server_config.get_server_config_path",
            return_value=p,
        ):
            result = _load_legacy_config()

        assert result == {"host": "0.0.0.0", "port": 8123}

    def test_unrecognized_keys_ignored(self, tmp_path):
        p = tmp_path / "config.json"
        p.write_text(
            json.dumps({"host": "localhost", "bogus_key": "val"}),
            encoding="utf-8",
        )
        with patch(
            "local_deep_research.web.server_config.get_server_config_path",
            return_value=p,
        ):
            result = _load_legacy_config()
            assert "host" in result
            assert "bogus_key" not in result


class TestLoadServerConfig:
    def test_returns_all_expected_keys(self):
        with patch(
            "local_deep_research.web.server_config._load_legacy_config",
            return_value={},
        ):
            config = load_server_config()
            for key in _DEFAULTS:
                assert key in config

    def test_defaults_when_no_legacy_no_env(self):
        with (
            patch(
                "local_deep_research.web.server_config._load_legacy_config",
                return_value={},
            ),
            patch.dict("os.environ", {}, clear=False),
        ):
            # Remove any LDR_ env vars
            import os

            env_clean = {
                k: v for k, v in os.environ.items() if not k.startswith("LDR_")
            }
            with patch.dict("os.environ", env_clean, clear=True):
                config = load_server_config()
                assert config["port"] in (5000, _DEFAULTS["port"])

    @pytest.mark.parametrize("legacy_value", [None, False, True])
    def test_unrecognized_allow_registrations_env_raises(self, legacy_value):
        """An invalid override must not select a default or legacy value."""
        with (
            patch(
                "local_deep_research.web.server_config._load_legacy_config",
                return_value={"allow_registrations": legacy_value},
            ),
            patch.dict(
                "os.environ",
                {"LDR_APP_ALLOW_REGISTRATIONS": "nein"},
                clear=False,
            ),
        ):
            with pytest.raises(SettingsValueError) as raised:
                load_server_config()

        assert raised.value.key == "app.allow_registrations"
        assert raised.value.source == "environment"

    @pytest.mark.parametrize(
        ("value", "expected"), [("true", True), ("false", False)]
    )
    def test_recognized_allow_registrations_env_passes(self, value, expected):
        with (
            patch(
                "local_deep_research.web.server_config._load_legacy_config",
                return_value={},
            ),
            patch.dict(
                "os.environ",
                {"LDR_APP_ALLOW_REGISTRATIONS": value},
                clear=False,
            ),
        ):
            config = load_server_config()
            assert config["allow_registrations"] is expected

    def test_legacy_unrecognized_allow_registrations_string(self):
        with (
            patch(
                "local_deep_research.web.server_config._load_legacy_config",
                return_value={"allow_registrations": "disabled"},
            ),
            patch.dict("os.environ", {}, clear=False),
        ):
            import os

            env_clean = {
                k: v
                for k, v in os.environ.items()
                if k != "LDR_APP_ALLOW_REGISTRATIONS"
            }
            with patch.dict("os.environ", env_clean, clear=True):
                config = load_server_config()
                assert config["allow_registrations"] is False