import pytest import asyncio import os import json from datetime import datetime, timedelta from unittest.mock import AsyncMock, patch, MagicMock from pathlib import Path # Путь к тестируемому модулю import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))) from core.role_binding_manager import RoleBindingManager, ROLES_STATE_PATH, ROLES_HISTORY_PATH, CALLS_HISTORY_PATH, DEPT_STATE_BUSY_BY_CEO, DEPT_STATE_IDLE, BASE_PATH, CONFIG_DIR, MAX_ROUNDS_D from core.model_management import ModelManager from core.project_context import ProjectContext # Фикстура для очистки состояния перед каждым тестом @pytest.fixture(autouse=True) def clean_up_state_files(): CONFIG_DIR.mkdir(parents=True, exist_ok=True) if os.path.exists(ROLES_STATE_PATH): os.remove(ROLES_STATE_PATH) if os.path.exists(ROLES_HISTORY_PATH): os.remove(ROLES_HISTORY_PATH) if os.path.exists(CALLS_HISTORY_PATH): os.remove(CALLS_HISTORY_PATH) RoleBindingManager._instance = None yield if os.path.exists(ROLES_STATE_PATH): os.remove(ROLES_STATE_PATH) if os.path.exists(ROLES_HISTORY_PATH): os.remove(ROLES_HISTORY_PATH) if os.path.exists(CALLS_HISTORY_PATH): os.remove(CALLS_HISTORY_PATH) RoleBindingManager._instance = None @pytest.fixture def mock_project_context(): with patch.object(ProjectContext, 'get_instance') as mock_get: instance = MagicMock() instance.ensure_initialized = AsyncMock() instance.get_current_project_path.return_value = None # Тесты по умолчанию без проекта mock_get.return_value = instance yield instance @pytest.mark.asyncio async def test_initialization_and_default_state(mock_project_context): manager = RoleBindingManager() await asyncio.sleep(0.1) assert os.path.exists(ROLES_STATE_PATH) state = manager.get_state() assert state["version"] == 1 assert "departments" in state assert state["departments"]["C"]["state"] == DEPT_STATE_IDLE assert "chief" in state["roles"] @pytest.mark.asyncio async def test_switch_binding(mock_project_context): manager = RoleBindingManager() await asyncio.sleep(0.1) with patch.object(ModelManager, 'invalidate_model', return_value=None) as mock_invalidate: success = manager.switch_binding("chief", "new-model-id", "test reason") assert success updated_state = manager.get_state("chief") assert updated_state["model_id"] == "new-model-id" mock_invalidate.assert_called_once_with("chief") @pytest.mark.asyncio async def test_department_locking(mock_project_context): manager = RoleBindingManager() await asyncio.sleep(0.1) success = manager.lock_department("C", DEPT_STATE_BUSY_BY_CEO, "test_ceo") assert success state_c = manager.get_state()["departments"]["C"] assert state_c["state"] == DEPT_STATE_BUSY_BY_CEO success = manager.lock_department("C", "busy_by_system", "test_system") assert not success success = manager.unlock_department("C") assert success assert manager.get_state()["departments"]["C"]["state"] == DEPT_STATE_IDLE @pytest.mark.asyncio async def test_consult_department_success(mock_project_context): manager = RoleBindingManager() await asyncio.sleep(0.1) mock_model_instance = AsyncMock() mock_model_instance.generate.side_effect = [ """```json\n{"diagnosis": ["minor issue"], "risk_level": "low", "recommended_fix": "restart"}\n```""", """```json\n{"diagnosis": ["major issue"], "risk_level": "high", "recommended_fix": "reinstall"}\n```""" ] with patch.object(ModelManager, 'get_model', new=AsyncMock(return_value=mock_model_instance)): with patch('asyncio.sleep', new=AsyncMock()): request_data = {"message": "[TASK] Check health", "health": "ok"} result = await manager.consult_department("C", request_data, caller="ceo") assert result is not None assert result["diagnosis"] == ["major issue"] assert manager.get_state()["departments"]["C"]["state"] == DEPT_STATE_IDLE with open(CALLS_HISTORY_PATH, 'r', encoding='utf-8') as f: calls_history = [json.loads(line) for line in f] assert any(call["department"] == "C" and call["success"] is True for call in calls_history) @pytest.mark.asyncio async def test_consult_department_fallback_invalid_json(mock_project_context): manager = RoleBindingManager() await asyncio.sleep(0.1) mock_model_instance = AsyncMock() mock_model_instance.generate.side_effect = ["invalid json", "invalid json"] with patch.object(ModelManager, 'get_model', new=AsyncMock(return_value=mock_model_instance)): with patch('asyncio.sleep', new=AsyncMock()): request_data = {"message": "[TASK] health check", "health": "ok"} result = await manager.consult_department("C", request_data, caller="system") assert result is not None # При невалидном JSON в формальном режиме возвращается текст последнего раунда assert "invalid json" in result @pytest.mark.asyncio async def test_consult_department_fallback_api_error(mock_project_context): manager = RoleBindingManager() await asyncio.sleep(0.1) mock_model_instance = AsyncMock() mock_model_instance.generate.side_effect = [Exception("API error")] * 3 with patch.object(ModelManager, 'get_model', new=AsyncMock(return_value=mock_model_instance)): with patch('asyncio.sleep', new=AsyncMock()): request_data = {"message": "[TASK] strategy", "health": "critical"} result = await manager.consult_department("D", request_data, caller="ceo") assert result is not None assert result["proposal"] == "Внешний мозг недоступен." assert "API error" in result["weak_points"][0] @pytest.mark.asyncio async def test_run_department_work_mode(mock_project_context): manager = RoleBindingManager() await asyncio.sleep(0.1) mock_model_instance = AsyncMock() mock_model_instance.generate.side_effect = ["Step 1 result", "Step 2 final result"] with patch.object(ModelManager, 'get_model', new=AsyncMock(return_value=mock_model_instance)): request_data = {"message": "Build something", "task": "Build something"} result = await manager.run_department("A", request_data, caller="chief") assert "Step 2 final result" in result assert mock_model_instance.generate.call_count == 2 with open(CALLS_HISTORY_PATH, 'r', encoding='utf-8') as f: calls_history = [json.loads(line) for line in f] assert any(call["department"] == "A" and call["success"] is True for call in calls_history) @pytest.mark.asyncio async def test_consult_department_department_busy(mock_project_context): manager = RoleBindingManager() await asyncio.sleep(0.1) manager.lock_department("C", "busy_by_ceo", "another_ceo") result = await manager.consult_department("C", {"msg": "test"}, caller="ceo") assert "Department busy" in result["diagnosis"][0] manager.unlock_department("C")