Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

test: stop letting one test decide what the next one resolves

Bingxi Zhao (Frank)cc316f03dd96
diff --git a/pyproject.toml b/pyproject.toml
index 966ce5a80..bc92b4c60 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -475,6 +475,7 @@ markers = [
"asyncio: mark async tests that require pytest-asyncio",
"integration: requires explicitly configured external services",
"redis_integration: requires DEEPTUTOR_TEST_REDIS_URL",
+ "real_llm_resolver: exercises LLM config resolution itself, so it keeps the real resolver",
]
asyncio_default_fixture_loop_scope = "function"
addopts = [
diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.py
index 606a1ef86..97f3462df 100644
--- a/tests/api/test_knowledge_router.py
+++ b/tests/api/test_knowledge_router.py
@@ -685,11 +685,12 @@ def test_create_kb_does_not_require_llm_precheck(monkeypatch, tmp_path: Path) ->
manager = _FakeKBManager(tmp_path / "knowledge_bases")
monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)
monkeypatch.setattr(knowledge_router_module, "KnowledgeBaseInitializer", _FakeInitializer)
+ # Patch the source module, not the router's namespace: the router does not
+ # import this symbol at all, so a `raising=False` patch on it would create
+ # an attribute nobody reads and the guard would pass no matter what.
monkeypatch.setattr(
- knowledge_router_module,
- "get_llm_config",
+ "deeptutor.services.llm.config.get_llm_config",
lambda: (_ for _ in ()).throw(RuntimeError("should not be called")),
- raising=False,
)
async def _noop_init_task(*_args, **_kwargs):
diff --git a/tests/capabilities/test_ima_capability.py b/tests/capabilities/test_ima_capability.py
index 9c8d00f77..c9e7341a3 100644
--- a/tests/capabilities/test_ima_capability.py
+++ b/tests/capabilities/test_ima_capability.py
@@ -137,7 +137,6 @@ def stub_client(monkeypatch: pytest.MonkeyPatch):
class TestBinding:
def test_only_ima_knowledge_bases_bind(self, monkeypatch: pytest.MonkeyPatch) -> None:
metadata = {"ima知识库": _metadata("ima"), "Papers": {"name": "Papers"}}
- monkeypatch.setattr(ima_binding, "resolve_kb_metadata", metadata.get, raising=False)
monkeypatch.setattr(
"deeptutor.multi_user.knowledge_access.resolve_kb_metadata",
metadata.get,
diff --git a/tests/capabilities/test_mastery_loop_pipeline.py b/tests/capabilities/test_mastery_loop_pipeline.py
index fe2ceb5be..9b0f4830b 100644
--- a/tests/capabilities/test_mastery_loop_pipeline.py
+++ b/tests/capabilities/test_mastery_loop_pipeline.py
@@ -104,6 +104,11 @@ def test_tool_surface_matches_chat_plus_the_mastery_tools(
return []
monkeypatch.setattr("deeptutor.agents.loop.pipeline.compose_enabled_tools", _record)
+ # The baseline has to be a plain chat turn. Setup's first-run offer joins a
+ # turn on its own once the install has a blocking gap and the intro has not
+ # been shown, both read from real settings — so on an unconfigured machine
+ # the "chat" side of this comparison silently grew setup's tools.
+ monkeypatch.setattr("deeptutor.capabilities.setup.binding._intro_pending", lambda _c: False)
chat_context = UnifiedContext(metadata={})
AgenticChatPipeline(language="en")._compose_enabled_tools(chat_context)
diff --git a/tests/conftest.py b/tests/conftest.py
index 7e205bf46..30799ff15 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -4,6 +4,7 @@ Root conftest — shared fixtures for the entire test suite.
from __future__ import annotations
+import os
from pathlib import Path
from unittest.mock import MagicMock
@@ -218,3 +219,85 @@ def fake_llm_config() -> MagicMock:
cfg.api_key = "sk-test"
cfg.api_base = "https://api.openai.com/v1"
return cfg
+
+
[email protected](autouse=True)
+def _isolate_llm_config(request, monkeypatch):
+ """Give every test the same resolved LLM config, and no cache to inherit.
+
+ ``get_llm_config`` memoises into a module-level ``_LLM_CONFIG_CACHE``, so
+ whichever test resolved first decided what every later test saw. Anything
+ constructed at import-or-init time off that config — ``QuestionPipeline``
+ is one — therefore passed only when some earlier test had already filled
+ the cache: run the suite in a different order and it raised
+ ``LLMConfigError`` instead. It also meant a developer with a model
+ configured and CI without one were running different tests.
+
+ Resolve to a fixed fake and clear the cache on both sides. Tests that
+ exercise resolution itself patch ``resolve_llm_runtime_config`` again,
+ which wins over this one.
+ """
+ from deeptutor.services.config.provider_runtime import ResolvedLLMConfig
+ from deeptutor.services.llm import config as llm_config_module
+
+ if "real_llm_resolver" in request.keywords:
+ # Resolution is what this test is checking. Still clear the cache on
+ # both sides so it neither inherits nor leaves one.
+ llm_config_module._LLM_CONFIG_CACHE = None
+ yield
+ llm_config_module._LLM_CONFIG_CACHE = None
+ return
+
+ def _resolve(*_args, **_kwargs) -> ResolvedLLMConfig:
+ return ResolvedLLMConfig(
+ model="gpt-4o-mini",
+ provider_name="openai",
+ provider_mode="direct",
+ binding="openai",
+ api_key="sk-test",
+ base_url="https://api.openai.com/v1",
+ effective_url="https://api.openai.com/v1",
+ context_window=128000,
+ )
+
+ monkeypatch.setattr(llm_config_module, "resolve_llm_runtime_config", _resolve)
+ monkeypatch.setattr(llm_config_module, "_LLM_CONFIG_CACHE", None)
+ yield
+ llm_config_module._LLM_CONFIG_CACHE = None
+
+
[email protected](autouse=True)
+def _isolate_application_container():
+ """No test inherits the process-wide container another test built.
+
+ ``get_application_container`` lazily builds once and keeps the result in a
+ module global, so the first test to reach it chose the coordinator backend
+ for every test after it. A run where that first test had redis settings in
+ scope left every later ``start()`` raising "Turn coordination backend is
+ unavailable" — including tests asserting on an entirely different error.
+ """
+ from deeptutor.app import container as container_module
+
+ container_module._default_container = None
+ yield
+ container_module._default_container = None
+
+
[email protected](autouse=True)
+def _restore_process_env():
+ """Undo environment a test left behind outside monkeypatch's reach.
+
+ ``monkeypatch.setenv`` is restored for you; a production code path that
+ assigns ``os.environ`` directly is not. ``runtime.launcher`` exports
+ ``DEEPTUTOR_HOME`` that way to hand the runtime home to its children, so
+ every launcher test left the variable pointing at its own ``tmp_path``.
+ The directory is deleted at teardown but the variable is not, and each of
+ the eight tests that shell out to ``sys.executable`` then ran against a
+ home that no longer exists — creating default settings, and logging that
+ it did onto the stdout the parent was trying to parse.
+ """
+ before = dict(os.environ)
+ yield
+ if os.environ != before:
+ os.environ.clear()
+ os.environ.update(before)
diff --git a/tests/services/session/test_capability_routing.py b/tests/services/session/test_capability_routing.py
index 3887e9a0f..ba3824aa1 100644
--- a/tests/services/session/test_capability_routing.py
+++ b/tests/services/session/test_capability_routing.py
@@ -100,9 +100,11 @@ async def _run_quiz_turn(tmp_path, captured: dict, config: dict | None = None):
@pytest.mark.asyncio
-async def test_quiz_requests_stay_in_chat_by_default(tmp_path) -> None:
+async def test_quiz_requests_stay_in_chat_by_default(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
captured: dict = {"global_enabled": False}
- _configure_runtime(pytest.MonkeyPatch(), captured)
+ _configure_runtime(monkeypatch, captured)
turn, session = await _run_quiz_turn(tmp_path, captured)
@@ -114,9 +116,11 @@ async def test_quiz_requests_stay_in_chat_by_default(tmp_path) -> None:
@pytest.mark.asyncio
-async def test_enabled_explicit_quiz_routes_for_one_turn(tmp_path) -> None:
+async def test_enabled_explicit_quiz_routes_for_one_turn(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
captured: dict = {"global_enabled": True}
- _configure_runtime(pytest.MonkeyPatch(), captured)
+ _configure_runtime(monkeypatch, captured)
turn, session = await _run_quiz_turn(tmp_path, captured)
@@ -129,9 +133,11 @@ async def test_enabled_explicit_quiz_routes_for_one_turn(tmp_path) -> None:
@pytest.mark.asyncio
-async def test_auto_route_false_overrides_global_setting(tmp_path) -> None:
+async def test_auto_route_false_overrides_global_setting(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
captured: dict = {"global_enabled": True}
- _configure_runtime(pytest.MonkeyPatch(), captured)
+ _configure_runtime(monkeypatch, captured)
turn, session = await _run_quiz_turn(tmp_path, captured, {"auto_route": False})
@@ -141,9 +147,11 @@ async def test_auto_route_false_overrides_global_setting(tmp_path) -> None:
@pytest.mark.asyncio
-async def test_per_turn_flag_opts_in_when_global_default_is_off(tmp_path) -> None:
+async def test_per_turn_flag_opts_in_when_global_default_is_off(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
captured: dict = {"global_enabled": False}
- _configure_runtime(pytest.MonkeyPatch(), captured)
+ _configure_runtime(monkeypatch, captured)
turn, session = await _run_quiz_turn(tmp_path, captured, {"auto_route": True})
diff --git a/tests/services/test_task_model_call_sites.py b/tests/services/test_task_model_call_sites.py
index 64f57f47f..b0de9768e 100644
--- a/tests/services/test_task_model_call_sites.py
+++ b/tests/services/test_task_model_call_sites.py
@@ -18,6 +18,8 @@ from deeptutor.services.config import model_catalog as model_catalog_module
from deeptutor.services.config.model_catalog import ModelCatalogService
from deeptutor.services.llm.config import clear_llm_config_cache, get_llm_config
+pytestmark = pytest.mark.real_llm_resolver
+
class _FakePathService:
def __init__(self, root: Path) -> None: