From c18117fb8748fff75ceca0b7b7e14c7b6cdc472b Mon Sep 17 00:00:00 2001 From: Victor Giers Date: Tue, 16 Jun 2026 19:14:01 +0200 Subject: [PATCH] Add async tests for chat handler and context fallback handling --- backend/tests/test_agent_chat_tool.py | 45 ++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/backend/tests/test_agent_chat_tool.py b/backend/tests/test_agent_chat_tool.py index b5ef659..3b9f68b 100644 --- a/backend/tests/test_agent_chat_tool.py +++ b/backend/tests/test_agent_chat_tool.py @@ -1,7 +1,9 @@ +import asyncio import unittest from types import SimpleNamespace +from unittest.mock import patch -from backend.agent.tools.chat import _drop_superseded_trailing_user_rows +from backend.agent.tools.chat import _drop_superseded_trailing_user_rows, chat_handler class ChatToolTests(unittest.TestCase): @@ -26,3 +28,44 @@ class ChatToolTests(unittest.TestCase): self.assertIs(_drop_superseded_trailing_user_rows(rows), rows) + +class ChatToolAsyncTests(unittest.IsolatedAsyncioTestCase): + async def test_chat_handler_returns_context_fallback_when_model_fails(self): + async def emit(_event_type, _payload): + return None + + async def failing_stream(*_args, **_kwargs): + raise RuntimeError("model returned 502") + if False: + yield None + + context = SimpleNamespace( + session_id=None, + db_factory=lambda: None, + emit=emit, + cancellation_event=asyncio.Event(), + show_thinking=False, + ) + arguments = { + "model": "broken-model", + "messages": [{"role": "user", "content": "weather?"}], + "context_blocks": [{ + "context_block": "Weather context", + "sources": [{ + "type": "web", + "title": "Schwäbisch Gmünd Weather", + "snippet": "Sunny intervals and light wind.", + "url": "https://weather.example/schwaebisch-gmuend", + }], + }], + "generation_options": {}, + "reasoning": False, + } + + with patch("backend.agent.tools.chat.chat_stream_typed", failing_stream): + result = await chat_handler(arguments, context) + + self.assertIn("selected chat model failed", result["content"]) + self.assertIn("Schwäbisch Gmünd Weather", result["content"]) + self.assertIn("https://weather.example/schwaebisch-gmuend", result["content"]) + self.assertEqual(result["sources"][0]["url"], "https://weather.example/schwaebisch-gmuend")