File size: 7,439 Bytes
0b2210a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 | 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")
|