Skip to content

Self-hosted AI workspace.

Python

fix(tests): clean agent loop import stubs

nubs44cc84cc6f54
diff --git a/tests/test_agent_loop.py b/tests/test_agent_loop.py
index 372699129..e30a87bf9 100644
--- a/tests/test_agent_loop.py
+++ b/tests/test_agent_loop.py
@@ -4,22 +4,57 @@ and _append_tool_results. Uses mock imports to avoid loading the full app stack.
import sys
from unittest.mock import MagicMock
-# Mock heavy dependencies before importing
-for mod in [
+_MOCKED_IMPORTS = [
'sqlalchemy', 'sqlalchemy.orm', 'sqlalchemy.ext', 'sqlalchemy.ext.declarative',
'sqlalchemy.ext.hybrid', 'sqlalchemy.sql', 'sqlalchemy.sql.expression',
'src.database',
'src.agent_tools',
'core.models', 'core.database',
-]:
- if mod not in sys.modules:
- sys.modules[mod] = MagicMock()
+]
+_INJECTED_IMPORT_STUBS = {}
+_PREEXISTING_AGENT_LOOP = sys.modules.get("src.agent_loop")
+
+
+def _drop_module_if_same(name, expected):
+ if sys.modules.get(name) is expected:
+ sys.modules.pop(name, None)
+ parent_name, _, attr = name.rpartition(".")
+ parent = sys.modules.get(parent_name)
+ if parent is not None and getattr(parent, "__dict__", {}).get(attr) is expected:
+ delattr(parent, attr)
-from src.agent_loop import (
- _detect_admin_intent,
- _compute_final_metrics,
- _append_tool_results,
-)
+
+# Mock heavy dependencies before importing. Only clean up stubs this file
+# created so pre-existing conftest/pytest modules keep their intended state.
+for mod in _MOCKED_IMPORTS:
+ if mod not in sys.modules:
+ stub = MagicMock()
+ sys.modules[mod] = stub
+ _INJECTED_IMPORT_STUBS[mod] = stub
+
+_IMPORTED_AGENT_LOOP = None
+try:
+ from src.agent_loop import (
+ _detect_admin_intent,
+ _compute_final_metrics,
+ _append_tool_results,
+ )
+ _IMPORTED_AGENT_LOOP = sys.modules.get("src.agent_loop")
+finally:
+ if _PREEXISTING_AGENT_LOOP is None and _IMPORTED_AGENT_LOOP is not None:
+ _drop_module_if_same("src.agent_loop", _IMPORTED_AGENT_LOOP)
+ for _mod, _stub in _INJECTED_IMPORT_STUBS.items():
+ _drop_module_if_same(_mod, _stub)
+
+
+def test_import_stubs_do_not_leak_into_later_tests():
+ leaked = [
+ mod for mod, stub in _INJECTED_IMPORT_STUBS.items()
+ if sys.modules.get(mod) is stub
+ ]
+ assert leaked == []
+ if _PREEXISTING_AGENT_LOOP is None:
+ assert sys.modules.get("src.agent_loop") is not _IMPORTED_AGENT_LOOP
# ---------------------------------------------------------------------------