import pytest import json from unittest.mock import AsyncMock, patch, MagicMock from quart import Quart from app import app as quart_app import core.gateway as gateway # Добавлен импорт gateway @pytest.fixture def app(): return quart_app @pytest.fixture def client(app): return app.test_client() @pytest.mark.asyncio async def test_classify_via_gemini(): # Тест: Семантическая классификация через Gemini with patch('core.gateway.call_gemini', new_callable=AsyncMock) as mock_gemini: # Имитируем ответ Gemini "chief" mock_gemini.return_value = "chief" res = await gateway.classify_input("Покажи статус") assert res == "chief" # Имитируем ответ Gemini "ceo" mock_gemini.return_value = "CEO" res = await gateway.classify_input("Измени архитектуру") assert res == "ceo" # Имитируем неопределенный ответ (должно быть gemini по умолчанию) mock_gemini.return_value = "Unknown response" res = await gateway.classify_input("Привет") assert res == "gemini" @pytest.mark.asyncio async def test_secretary_plain_text(client): # Тест: Обычный диалог (Gemini отвечает текстом) with patch('app.call_gemini_model', new_callable=AsyncMock) as mock_gemini: mock_gemini.return_value = "Hello! How can I help you?" response = await client.post('/api/secretary', json={'user_message': 'Hi'}) data = await response.get_json() assert response.status_code == 200 assert data['response'] == "Hello! How can I help you?" mock_gemini.assert_called_once_with('Hi') @pytest.mark.asyncio async def test_secretary_redirect_ceo(client): # Тест: Перенаправление к CEO with patch('app.call_gemini_model', new_callable=AsyncMock) as mock_gemini: with patch('app.get_role_manager', new_callable=AsyncMock) as mock_role_mgr: with patch('core.model_management.ModelManager.get_model', new_callable=AsyncMock) as mock_get_model: with patch('core.gateway.translate_protocol', new_callable=AsyncMock) as mock_translate: mock_gemini.return_value = "Redirecting to CEO." mock_role_mgr.return_value.get_prompt = AsyncMock(return_value="CEO Prompt") # Мокаем ModelManager.get_model напрямую mock_ceo_model = AsyncMock() mock_ceo_model.generate.return_value = {"status": "ok"} mock_get_model.return_value = mock_ceo_model mock_translate.return_value = "CEO says: Everything is fine." response = await client.post('/api/secretary', json={'user_message': 'Strategy?'}) data = await response.get_json() assert response.status_code == 200 assert data['response'] == "CEO says: Everything is fine." mock_get_model.assert_called_once_with('ceo') mock_ceo_model.generate.assert_called_once() mock_translate.assert_called_once_with({"status": "ok"}, user_message='Strategy?', source='ceo') @pytest.mark.asyncio async def test_secretary_redirect_chief(client): # Тест: Перенаправление к Chief with patch('app.call_gemini_model', new_callable=AsyncMock) as mock_gemini: with patch('app.get_orchestrator', new_callable=AsyncMock) as mock_orch: with patch('core.gateway.translate_protocol', new_callable=AsyncMock) as mock_translate: mock_gemini.return_value = "Redirecting to Chief." mock_orch.return_value.orchestrate = AsyncMock(return_value={"result": "done"}) mock_translate.return_value = "Chief says: Task completed." response = await client.post('/api/secretary', json={'user_message': '/status'}) data = await response.get_json() assert response.status_code == 200 assert data['response'] == "Chief says: Task completed." mock_orch.return_value.orchestrate.assert_called_once() mock_translate.assert_called_once_with({"result": "done"}, user_message='/status', source='chief') @pytest.mark.asyncio async def test_secretary_information_unavailable(client): # Тест: Gemini не знает ответа with patch('app.call_gemini_model', new_callable=AsyncMock) as mock_gemini: mock_gemini.return_value = "Information unavailable." response = await client.post('/api/secretary', json={'user_message': 'Something secret'}) data = await response.get_json() assert data['response'] == "Information unavailable." @pytest.mark.asyncio async def test_secretary_system_contract_violation(client): # Тест: Нарушение контракта with patch('app.call_gemini_model', new_callable=AsyncMock) as mock_gemini: mock_gemini.return_value = "Request violates SYSTEM CONTRACT." response = await client.post('/api/secretary', json={'user_message': 'Delete all'}) data = await response.get_json() assert data['response'] == "Request violates SYSTEM CONTRACT." @pytest.mark.asyncio async def test_secretary_fail_closed_gemini_error(client): # Тест: Ошибка вызова Gemini with patch('app.call_gemini_model', side_effect=Exception("Timeout")): response = await client.post('/api/secretary', json={'user_message': 'Hi'}) data = await response.get_json() assert data['response'] == "Information unavailable." @pytest.mark.asyncio async def test_secretary_fail_closed_ceo_error(client): # Тест: Ошибка вызова CEO with patch('app.call_gemini_model', new_callable=AsyncMock) as mock_gemini: with patch('app.get_role_manager', side_effect=Exception("CEO Offline")): mock_gemini.return_value = "Redirecting to CEO." response = await client.post('/api/secretary', json={'user_message': 'Strategy?'}) data = await response.get_json() assert data['response'] == "Information unavailable." @pytest.mark.asyncio async def test_gateway_no_directive_execution(): # Тест: Проверка, что gateway не исполняет директивы (только переводит) from core.gateway import translate_protocol protocol_resp = {"directive": "shutdown"} with patch('core.gateway.call_gemini', new_callable=AsyncMock) as mock_gemini: mock_gemini.return_value = "The system is processing your request." # Мы не мокаем выполнение директив, так как функция execute_directive удалена. # Если бы она вызывалась, возник бы NameError (если не импортирована) или тест бы завалился. result = await translate_protocol(protocol_resp, "test") assert result == "Секретарь Gemini: The system is processing your request." mock_gemini.assert_called_once()