deer-flow/backend/tests/test_checkpointer.py
greatmengqi 84dccef230 refactor(config): Phase 2 — eliminate AppConfig.current() ambient lookup
Finish Phase 2 of the config refactor: production code no longer calls
AppConfig.current() anywhere. AppConfig now flows as an explicit parameter
down every consumer lane.

Call-site migrations
--------------------
- Memory subsystem (queue/updater/storage): MemoryConfig captured at
  enqueue time so the Timer closure survives the ContextVar boundary.
- Sandbox layer: tools.py, security.py, sandbox_provider.py, local_sandbox_provider,
  aio_sandbox_provider all take app_config explicitly. Module-level
  caching in tools.py's path helpers is removed — pure parameter flow.
- Skills layer: manager.py + loader.py + lead_agent.prompt cache refresh
  all thread app_config; cache worker closes over it.
- Community tools (tavily, jina, firecrawl, exa, ddg, image_search,
  infoquest, aio_sandbox): read runtime.context.app_config.
- Subagents registry: get_subagent_config / list_subagents /
  get_available_subagent_names require app_config.
- Runtime worker: requires RunContext.app_config; no fallback.
- Gateway routers (uploads, skills): add Depends(get_config).
- Channels feishu: uses AppConfig.from_file() (pure) at its sync boundary.
- LangGraph Server bootstrap (make_lead_agent): falls back to
  AppConfig.from_file() — pure load, not ambient lookup.

Context resolution
------------------
- resolve_context(runtime) now raises on non-DeerFlowContext runtime.context.
  Every entry point attaches typed context; dict/None shapes are rejected
  loudly instead of being papered over with an ambient AppConfig lookup.

AppConfig lifecycle
-------------------
- AppConfig.current() kept as a deprecated slot that raises RuntimeError,
  purely so legacy tests that still run `patch.object(AppConfig, "current")`
  don't trip AttributeError at teardown. Production never calls it.
- conftest autouse fixture no longer monkey-patches `current` — it only
  stubs `from_file()` so tests don't need a real config.yaml.

Design refs
-----------
- docs/plans/2026-04-12-config-refactor-plan.md (Phase 2: P2-6..P2-10)
- docs/plans/2026-04-12-config-refactor-design.md §8

All 2338 non-e2e tests pass. Zero AppConfig.current() call sites remain
in backend/packages or backend/app (docstrings in deps.py excepted).
2026-04-17 11:14:13 +08:00

255 lines
10 KiB
Python

"""Unit tests for checkpointer config and singleton factory."""
import sys
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from deerflow.config.app_config import AppConfig
from deerflow.config.checkpointer_config import CheckpointerConfig
from deerflow.config.sandbox_config import SandboxConfig
from deerflow.runtime.checkpointer import get_checkpointer, reset_checkpointer
def _make_config(checkpointer: CheckpointerConfig | None = None) -> AppConfig:
return AppConfig(sandbox=SandboxConfig(use="test"), checkpointer=checkpointer)
@pytest.fixture(autouse=True)
def reset_state():
"""Reset singleton state before each test."""
reset_checkpointer()
yield
reset_checkpointer()
# ---------------------------------------------------------------------------
# Config tests
# ---------------------------------------------------------------------------
class TestCheckpointerConfig:
def test_memory_config(self):
config = CheckpointerConfig(type="memory")
assert config.type == "memory"
assert config.connection_string is None
def test_sqlite_config(self):
config = CheckpointerConfig(type="sqlite", connection_string="/tmp/test.db")
assert config.type == "sqlite"
assert config.connection_string == "/tmp/test.db"
def test_postgres_config(self):
config = CheckpointerConfig(type="postgres", connection_string="postgresql://localhost/db")
assert config.type == "postgres"
assert config.connection_string == "postgresql://localhost/db"
def test_default_connection_string_is_none(self):
config = CheckpointerConfig(type="memory")
assert config.connection_string is None
def test_invalid_type_raises(self):
with pytest.raises(Exception):
CheckpointerConfig(type="unknown")
# ---------------------------------------------------------------------------
# Factory tests
# ---------------------------------------------------------------------------
class TestGetCheckpointer:
def test_returns_in_memory_saver_when_not_configured(self):
"""get_checkpointer should return InMemorySaver when not configured."""
from langgraph.checkpoint.memory import InMemorySaver
with patch.object(AppConfig, "current", return_value=_make_config()):
cp = get_checkpointer(AppConfig.current())
assert cp is not None
assert isinstance(cp, InMemorySaver)
def test_raises_when_config_file_missing(self):
"""A missing config.yaml is a deployment error, not a cue to degrade to InMemorySaver.
Silent degradation would drop persistent-run state on process restart.
`get_checkpointer` only falls back to InMemorySaver for the explicit
`checkpointer: null` opt-in (test above), not for I/O failure.
"""
with patch.object(AppConfig, "current", side_effect=FileNotFoundError):
with pytest.raises(FileNotFoundError):
get_checkpointer(AppConfig.current())
def test_memory_returns_in_memory_saver(self):
from langgraph.checkpoint.memory import InMemorySaver
cfg = _make_config(CheckpointerConfig(type="memory"))
with patch.object(AppConfig, "current", return_value=cfg):
cp = get_checkpointer(AppConfig.current())
assert isinstance(cp, InMemorySaver)
def test_memory_singleton(self):
cfg = _make_config(CheckpointerConfig(type="memory"))
with patch.object(AppConfig, "current", return_value=cfg):
cp1 = get_checkpointer(AppConfig.current())
cp2 = get_checkpointer(AppConfig.current())
assert cp1 is cp2
def test_reset_clears_singleton(self):
cfg = _make_config(CheckpointerConfig(type="memory"))
with patch.object(AppConfig, "current", return_value=cfg):
cp1 = get_checkpointer(AppConfig.current())
reset_checkpointer()
cp2 = get_checkpointer(AppConfig.current())
assert cp1 is not cp2
def test_sqlite_raises_when_package_missing(self):
cfg = _make_config(CheckpointerConfig(type="sqlite", connection_string="/tmp/test.db"))
with (
patch.object(AppConfig, "current", return_value=cfg),
patch.dict(sys.modules, {"langgraph.checkpoint.sqlite": None}),
):
reset_checkpointer()
with pytest.raises(ImportError, match="langgraph-checkpoint-sqlite"):
get_checkpointer(AppConfig.current())
def test_postgres_raises_when_package_missing(self):
cfg = _make_config(CheckpointerConfig(type="postgres", connection_string="postgresql://localhost/db"))
with (
patch.object(AppConfig, "current", return_value=cfg),
patch.dict(sys.modules, {"langgraph.checkpoint.postgres": None}),
):
reset_checkpointer()
with pytest.raises(ImportError, match="langgraph-checkpoint-postgres"):
get_checkpointer(AppConfig.current())
def test_postgres_raises_when_connection_string_missing(self):
cfg = _make_config(CheckpointerConfig(type="postgres"))
mock_saver = MagicMock()
mock_module = MagicMock()
mock_module.PostgresSaver = mock_saver
with (
patch.object(AppConfig, "current", return_value=cfg),
patch.dict(sys.modules, {"langgraph.checkpoint.postgres": mock_module}),
):
reset_checkpointer()
with pytest.raises(ValueError, match="connection_string is required"):
get_checkpointer(AppConfig.current())
def test_sqlite_creates_saver(self):
"""SQLite checkpointer is created when package is available."""
cfg = _make_config(CheckpointerConfig(type="sqlite", connection_string="/tmp/test.db"))
mock_saver_instance = MagicMock()
mock_cm = MagicMock()
mock_cm.__enter__ = MagicMock(return_value=mock_saver_instance)
mock_cm.__exit__ = MagicMock(return_value=False)
mock_saver_cls = MagicMock()
mock_saver_cls.from_conn_string = MagicMock(return_value=mock_cm)
mock_module = MagicMock()
mock_module.SqliteSaver = mock_saver_cls
with (
patch.object(AppConfig, "current", return_value=cfg),
patch.dict(sys.modules, {"langgraph.checkpoint.sqlite": mock_module}),
):
reset_checkpointer()
cp = get_checkpointer(AppConfig.current())
assert cp is mock_saver_instance
mock_saver_cls.from_conn_string.assert_called_once()
mock_saver_instance.setup.assert_called_once()
def test_postgres_creates_saver(self):
"""Postgres checkpointer is created when packages are available."""
cfg = _make_config(CheckpointerConfig(type="postgres", connection_string="postgresql://localhost/db"))
mock_saver_instance = MagicMock()
mock_cm = MagicMock()
mock_cm.__enter__ = MagicMock(return_value=mock_saver_instance)
mock_cm.__exit__ = MagicMock(return_value=False)
mock_saver_cls = MagicMock()
mock_saver_cls.from_conn_string = MagicMock(return_value=mock_cm)
mock_pg_module = MagicMock()
mock_pg_module.PostgresSaver = mock_saver_cls
with (
patch.object(AppConfig, "current", return_value=cfg),
patch.dict(sys.modules, {"langgraph.checkpoint.postgres": mock_pg_module}),
):
reset_checkpointer()
cp = get_checkpointer(AppConfig.current())
assert cp is mock_saver_instance
mock_saver_cls.from_conn_string.assert_called_once_with("postgresql://localhost/db")
mock_saver_instance.setup.assert_called_once()
class TestAsyncCheckpointer:
@pytest.mark.anyio
async def test_sqlite_creates_parent_dir_via_to_thread(self):
"""Async SQLite setup should move mkdir off the event loop."""
from deerflow.runtime.checkpointer.async_provider import make_checkpointer
mock_config = MagicMock()
mock_config.checkpointer = CheckpointerConfig(type="sqlite", connection_string="relative/test.db")
mock_saver = AsyncMock()
mock_cm = AsyncMock()
mock_cm.__aenter__.return_value = mock_saver
mock_cm.__aexit__.return_value = False
mock_saver_cls = MagicMock()
mock_saver_cls.from_conn_string.return_value = mock_cm
mock_module = MagicMock()
mock_module.AsyncSqliteSaver = mock_saver_cls
with (
patch.object(AppConfig, "current", return_value=mock_config),
patch.dict(sys.modules, {"langgraph.checkpoint.sqlite.aio": mock_module}),
patch("deerflow.runtime.checkpointer.async_provider.asyncio.to_thread", new_callable=AsyncMock) as mock_to_thread,
patch(
"deerflow.runtime.checkpointer.async_provider.resolve_sqlite_conn_str",
return_value="/tmp/resolved/test.db",
),
):
async with make_checkpointer(AppConfig.current()) as saver:
assert saver is mock_saver
mock_to_thread.assert_awaited_once()
called_fn, called_path = mock_to_thread.await_args.args
assert called_fn.__name__ == "ensure_sqlite_parent_dir"
assert called_path == "/tmp/resolved/test.db"
mock_saver_cls.from_conn_string.assert_called_once_with("/tmp/resolved/test.db")
mock_saver.setup.assert_awaited_once()
# ---------------------------------------------------------------------------
# app_config.py integration
# ---------------------------------------------------------------------------
class TestAppConfigLoadsCheckpointer:
def test_load_checkpointer_section(self):
"""AppConfig with checkpointer section has the correct config."""
cfg = _make_config(CheckpointerConfig(type="memory"))
assert cfg.checkpointer is not None
assert cfg.checkpointer.type == "memory"
# ---------------------------------------------------------------------------
# DeerFlowClient falls back to config checkpointer
# ---------------------------------------------------------------------------
class TestClientCheckpointerFallback:
def test_client_uses_config_checkpointer_when_none_provided(self):
"""DeerFlowClient._ensure_agent falls back to get_checkpointer(AppConfig.current()) when checkpointer=None."""
# This is a structural test — verifying the fallback path exists.
cfg = _make_config(CheckpointerConfig(type="memory"))
assert cfg.checkpointer is not None