From 90fcb7f903f35f6857118ca3139c036f406bb89e Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Sun, 18 Oct 2026 18:23:05 +0800 Subject: [PATCH] test(agent): close session input fixtures and share shutdown diagnostics --- tests/agent/session_helpers.py | 14 +++++++++++ tests/agent/test_session_inbox_controls.py | 15 ++---------- tests/agent/test_session_inputs.py | 27 +++++++++++----------- 3 files changed, 29 insertions(+), 27 deletions(-) diff --git a/tests/agent/session_helpers.py b/tests/agent/session_helpers.py index 9b8d03841..b109e64d4 100644 --- a/tests/agent/session_helpers.py +++ b/tests/agent/session_helpers.py @@ -1,6 +1,7 @@ """Session-worker completion helpers for integration tests.""" import asyncio +import faulthandler import time from nanobot.agent.loop import AgentLoop @@ -38,6 +39,19 @@ async def run_session(loop: AgentLoop, msg: InboundMessage) -> None: await asyncio.gather(*loop._active_tasks[loop._effective_session_key(msg)]) +async def stop_loop(loop: AgentLoop, worker: asyncio.Task[None], *, timeout: float) -> None: + """Stop an integration loop, retaining native shutdown stacks on timeout.""" + loop.stop() + try: + await asyncio.wait_for(worker, timeout=timeout) + except TimeoutError: + close_task = loop.sessions.state._close_task + if close_task is not None: + close_task.print_stack() + faulthandler.dump_traceback() + raise + + def mock_session_manager(*_args, **_kwargs): """Model the asynchronous state boundary in scheduler-only unit tests.""" from unittest.mock import AsyncMock, MagicMock diff --git a/tests/agent/test_session_inbox_controls.py b/tests/agent/test_session_inbox_controls.py index a5dfbb002..c92562333 100644 --- a/tests/agent/test_session_inbox_controls.py +++ b/tests/agent/test_session_inbox_controls.py @@ -1,13 +1,12 @@ """Independent turns and internal controls retain their session inbox semantics.""" import asyncio -import faulthandler import threading from unittest.mock import AsyncMock, MagicMock import pytest -from agent.session_helpers import run_session +from agent.session_helpers import run_session, stop_loop from nanobot.agent.automation_turns import AutomationTurnError from nanobot.agent.loop import AgentLoop from nanobot.agent.tools.context import current_request_context @@ -705,14 +704,4 @@ async def test_queued_continuation_keeps_its_origin_after_another_chat_runs(loop replies.append((reply.chat_id, reply.metadata.get("message_id"))) assert replies == [("chat-a", "message-a")] finally: - loop.stop() - try: - await asyncio.wait_for(worker, timeout=3) - except TimeoutError: - # Native Windows CI has timed out after the routing assertions. - # Preserve the deadline and expose the shielded storage drain. - close_task = loop.sessions.state._close_task - if close_task is not None: - close_task.print_stack() - faulthandler.dump_traceback() - raise + await stop_loop(loop, worker, timeout=3) diff --git a/tests/agent/test_session_inputs.py b/tests/agent/test_session_inputs.py index 0b3006211..a9b6bf578 100644 --- a/tests/agent/test_session_inputs.py +++ b/tests/agent/test_session_inputs.py @@ -5,6 +5,7 @@ from unittest.mock import AsyncMock, MagicMock import pytest +from agent.session_helpers import stop_loop from nanobot.agent.loop import AgentLoop from nanobot.bus.events import InboundMessage from nanobot.bus.queue import MessageBus @@ -13,19 +14,25 @@ from nanobot.runtime_context import public_history_message from nanobot.session.session_messages import SESSION_MESSAGE_METADATA_KEY -def _loop(tmp_path: Path) -> AgentLoop: +@pytest.fixture +async def loop(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path / "state") provider = MagicMock(aclose=AsyncMock()) provider.get_default_model.return_value = "test-model" provider.generation = SimpleNamespace(max_tokens=4096) provider.chat_stream_with_retry = AsyncMock( return_value=LLMResponse(content="Reviewed", tool_calls=[], usage=None) ) - return AgentLoop( + agent = AgentLoop( bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model", ) + try: + yield agent + finally: + await agent.aclose() def _message(content: str = "Please review") -> InboundMessage: @@ -50,11 +57,8 @@ def _message(content: str = "Please review") -> InboundMessage: @pytest.mark.asyncio async def test_session_message_runs_as_user_input_and_replies_on_target_route( - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, + loop: AgentLoop, ) -> None: - monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path / "state") - loop = _loop(tmp_path) loop.sessions.save(loop.sessions.get_or_create("telegram:target")) msg = _message() @@ -82,11 +86,8 @@ async def test_session_message_runs_as_user_input_and_replies_on_target_route( @pytest.mark.asyncio async def test_session_message_text_is_not_dispatched_as_a_slash_command( - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, + loop: AgentLoop, ) -> None: - monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path / "state") - loop = _loop(tmp_path) loop.sessions.save(loop.sessions.get_or_create("telegram:target")) task = asyncio.create_task(loop.run()) try: @@ -96,12 +97,10 @@ async def test_session_message_text_is_not_dispatched_as_a_slash_command( assert response.content == "Reviewed" loop.provider.chat_stream_with_retry.assert_awaited_once() finally: - loop.stop() - await asyncio.wait_for(task, timeout=2) + await stop_loop(loop, task, timeout=2) -async def test_path_followup_reaches_running_turn(tmp_path: Path) -> None: - loop = _loop(tmp_path) +async def test_path_followup_reaches_running_turn(loop: AgentLoop) -> None: first_call = asyncio.Event() release = asyncio.Event() calls = []