import sys import asyncio import httpx import unittest from unittest.mock import MagicMock, AsyncMock, patch # Configure loop for Windows if sys.platform == 'win32': asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) sys.path.append(".") class TestNexusResilience(unittest.IsolatedAsyncioTestCase): async def test_llm_retry_on_524(self): """Test that the get_llm factory produces a model that retries on 524.""" from core.llm import get_llm with patch("langchain_ollama.ChatOllama.ainvoke", new_callable=AsyncMock) as mock_invoke: # Setup: Fail twice with 524, then succeed resp_524 = MagicMock(spec=httpx.Response) resp_524.status_code = 524 err_524 = httpx.HTTPStatusError("Cloudflare Timeout", request=MagicMock(), response=resp_524) mock_invoke.side_effect = [err_524, err_524, MagicMock(content="Finally Success")] llm = get_llm(use_fast_model=True) # We need to manually trigger the retry block if the factory doesn't return the wrapper # But the factory DOES return ResilientChatOllama result = await llm.ainvoke("hi") self.assertEqual(result.content, "Finally Success") self.assertEqual(mock_invoke.call_count, 3) print("\n[OK] LLM Factory correctly retried on 524 errors.") async def test_router_timeout_increase(self): """Test that nexus_router uses the increased 120s timeout.""" from agents.nexus_master import nexus_router, NexusState from uuid import uuid4 state = { "messages": [MagicMock(content="test")], "workspace_id": uuid4(), "user_id": uuid4(), "thread_id": uuid4(), "is_agent": True, "user_role": "admin" } with patch("agents.nexus_master.get_bound_llm") as mock_get_llm: mock_llm = MagicMock() # If router times out, it logs an error and uses fallback. # We want to show it DOES NOT time out during a long call (e.g. 5s) mock_llm.ainvoke = AsyncMock(side_effect=lambda *args, **kwargs: (asyncio.sleep(2), MagicMock(content="Success"))[1]) mock_get_llm.return_value = mock_llm # This test doesn't prove it's 120s, but verifies the logic is reachable. # Real verification is searching the source for the '120.0' string. result = await nexus_router(state) self.assertIn("messages", result) print("[OK] Router reached successfully with new timeout configuration.") if __name__ == "__main__": unittest.main()