import pytest import json import re from unittest.mock import AsyncMock, patch, MagicMock from app import app as quart_app @pytest.fixture def app(): return quart_app @pytest.fixture def client(app): return app.test_client() @pytest.mark.asyncio async def test_gateway_chief_direct_response(client): """Тест: Прямой ответ от Chief (без редиректа).""" with patch('core.llm_integrations.chief_orchestrator.ChiefOrchestrator.orchestrate', new_callable=AsyncMock) as mock_orch: mock_orch.return_value = "Task assigned to Dept A" response = await client.post('/api/secretary', json={ 'model': 'chief', 'message': 'Create new task' }) data = await response.get_json() assert response.status_code == 200 assert data['response'] == "Task assigned to Dept A" mock_orch.assert_called_once() @pytest.mark.asyncio async def test_gateway_chief_redirect(client): """Тест: Редирект от Chief к Secretary.""" # Эмулируем ответ Chief с маркером редиректа chief_redirect_msg = '{"redirect":"secretary","reason_code":"out_of_scope"}' secretary_explanation = "Chief is only for task management. I can help you with general talk." with patch('core.llm_integrations.chief_orchestrator.ChiefOrchestrator.orchestrate', new_callable=AsyncMock) as mock_orch: with patch('core.gateway.call_gemini', new_callable=AsyncMock) as mock_gemini: mock_orch.return_value = chief_redirect_msg mock_gemini.return_value = secretary_explanation response = await client.post('/api/secretary', json={ 'model': 'chief', 'message': 'How to cook borsch?' }) data = await response.get_json() assert response.status_code == 200 assert data['response'] == secretary_explanation mock_orch.assert_called_once() # Проверяем, что промпт для Секретаря содержит причину args, _ = mock_gemini.call_args assert "out_of_scope" in args[0] assert "How to cook borsch?" in args[0] @pytest.mark.asyncio async def test_gateway_ceo_redirect(client): """Тест: Редирект от CEO к Secretary.""" ceo_redirect_msg = ' {"redirect":"secretary","reason_code":"not_actionable"}' # С пробелами secretary_explanation = "CEO expects architectural proposals. How can I help you frame one?" with patch('core.model_management.ModelManager.get_model', new_callable=AsyncMock) as mock_get_model: with patch('core.gateway.call_gemini', new_callable=AsyncMock) as mock_gemini: mock_ceo = AsyncMock() mock_ceo.generate.return_value = ceo_redirect_msg mock_get_model.return_value = mock_ceo mock_gemini.return_value = secretary_explanation response = await client.post('/api/secretary', json={ 'model': 'ceo', 'message': 'Hello' }) data = await response.get_json() assert response.status_code == 200 assert data['response'] == secretary_explanation # Проверяем извлечение reason_code (not_actionable) args, _ = mock_gemini.call_args assert "not_actionable" in args[0] @pytest.mark.asyncio async def test_gateway_invalid_json_but_prefix(client): """Тест: Некорректный JSON, но есть префикс редиректа.""" # Невалидный JSON после префикса broken_redirect_msg = '{"redirect":"secretary", "reason_code": broken!!!}' secretary_explanation = "I noticed a redirect but couldn't parse the reason. How can I help?" with patch('core.llm_integrations.chief_orchestrator.ChiefOrchestrator.orchestrate', new_callable=AsyncMock) as mock_orch: with patch('core.gateway.call_gemini', new_callable=AsyncMock) as mock_gemini: mock_orch.return_value = broken_redirect_msg mock_gemini.return_value = secretary_explanation response = await client.post('/api/secretary', json={ 'model': 'chief', 'message': 'Broken test' }) data = await response.get_json() assert response.status_code == 200 assert data['response'] == secretary_explanation # reason_code должен быть unspecified args, _ = mock_gemini.call_args assert "unspecified" in args[0] @pytest.mark.asyncio async def test_gateway_role_error(client): """Тест: Техническая ошибка роли (не вызывает Secretary).""" with patch('core.llm_integrations.chief_orchestrator.ChiefOrchestrator.orchestrate', side_effect=Exception("Model Timeout")): response = await client.post('/api/secretary', json={ 'model': 'chief', 'message': 'Trigger error' }) data = await response.get_json() assert response.status_code == 500 assert data['response'] == "Technical error occurred." @pytest.mark.asyncio async def test_gateway_employee_response(client): """Тест: Ответ от сотрудника (например, flick) с корректным именем и промптом.""" with patch('core.model_management.ModelManager.get_model', new_callable=AsyncMock) as mock_get_model: with patch('core.role_binding_manager.RoleBindingManager.get_prompt', new_callable=AsyncMock) as mock_get_prompt: mock_flick = AsyncMock() mock_flick.generate.return_value = "I am Flick, the analyzer." mock_get_model.return_value = mock_flick mock_get_prompt.return_value = "You are Flick." response = await client.post('/api/secretary', json={ 'model': 'flick', 'message': 'Who are you?' }) data = await response.get_json() assert response.status_code == 200 assert data['response'] == "I am Flick, the analyzer." assert data['modelInfo']['roleName'] == "Флик" # Проверяем, что системный промпт был передан mock_flick.generate.assert_called_once_with('Who are you?', system_prompt="You are Flick.") @pytest.mark.asyncio async def test_gateway_direct_gemini(client): """Тест: Прямой вызов Gemini (model='gemini').""" with patch('core.gateway.call_gemini', new_callable=AsyncMock) as mock_gemini: mock_gemini.return_value = "I am Secretary Gemini." response = await client.post('/api/secretary', json={ 'model': 'gemini', 'message': 'Who are you?' }) data = await response.get_json() assert response.status_code == 200 assert data['response'] == "I am Secretary Gemini." mock_gemini.assert_called_once_with('Who are you?')