File size: 7,398 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 | import asyncio
import json
import os
from pathlib import Path
from datetime import datetime
import sys
import shutil # Добавлен импорт shutil
sys.path.insert(0, str(Path(__file__).parent.parent)) # Добавляем AI-colab в sys.path
from core.project_context import ProjectContext
from core.project_model_registry import ProjectModelRegistry
async def test_registry_creation_and_use():
print("\n--- Тестирование ProjectModelRegistry ---")
test_project_id = "ai_colab_main" # Используем имя нашего основного проекта
# Убедимся, что директория проекта существует (для ProjectContext)
project_root = Path("D:/Gemini/AI-colab/projects") / test_project_id
project_root.mkdir(parents=True, exist_ok=True)
(project_root / "config").mkdir(parents=True, exist_ok=True)
(project_root / "prompts").mkdir(parents=True, exist_ok=True)
(project_root / "data").mkdir(parents=True, exist_ok=True)
(project_root / "logs").mkdir(parents=True, exist_ok=True)
# Создаем project_info.json
project_info_content = {
"name": "AI-Colab Main Test Project",
"type": "main",
"description": "Main project for AI-Colab system tests",
"version": "1.0",
"project_id": test_project_id,
"status": "created",
"created_at": datetime.now().isoformat()
}
with open(project_root / "project_info.json", "w", encoding="utf-8") as f:
json.dump(project_info_content, f, indent=2, ensure_ascii=False)
# Инициализация ProjectContext, который будет использоваться ProjectModelRegistry
context = ProjectContext.get_instance()
await context.set_current_project(str(project_root)) # Устанавливаем текущий проект
registry = ProjectModelRegistry(test_project_id)
# 1. Проверка начального состояния
print(f"Путь реестра: {registry.registry_path}")
assert not registry.registry_path.exists(), "Реестр не должен существовать на старте"
assert registry.get_model_for_role("chief") is None, "Дефолтный chief не должен быть зарегистрирован"
print("✅ Начальное состояние реестра корректно.")
# 2. Регистрация модели
chief_model_config = {
"model_id": "SmolLM2-360M-Instruct.Q4_K_M.gguf",
"provider": "gptoss",
"is_local": True
}
registry.register_model("chief", chief_model_config)
print("✅ Модель chief зарегистрирована.")
# 3. Проверка зарегистрированной модели
retrieved_model = registry.get_model_for_role("chief")
assert retrieved_model is not None, "Зарегистрированная модель chief не найдена"
assert retrieved_model["model_id"] == chief_model_config["model_id"], "Неверный model_id"
assert "fixed_at" in retrieved_model, "Отсутствует fixed_at"
print("✅ Зарегистрированная модель chief успешно получена и проверена.")
# 4. Проверка сохранения и повторной загрузки
del registry # Удаляем объект для симуляции перезагрузки
reloaded_registry = ProjectModelRegistry(test_project_id)
reloaded_model = reloaded_registry.get_model_for_role("chief")
assert reloaded_model is not None, "Модель не сохранилась после перезагрузки"
assert reloaded_model["model_id"] == chief_model_config["model_id"], "Модель неверна после перезагрузки"
print("✅ Реестр успешно сохраняется и загружается.")
# 5. Регистрация другой модели
ceo_model_config = {
"model_id": "Phi-3-mini-4k-instruct-q4.gguf",
"provider": "gptoss",
"is_local": True
}
reloaded_registry.register_model("ceo", ceo_model_config)
print("✅ Модель ceo зарегистрирована.")
# 6. Проверка обновления Project ID (через изменение ProjectContext)
print("\n--- Тестирование обновления Project ID ---")
new_project_id = "another_test_project"
new_project_root = Path("D:/Gemini/AI-colab/projects") / new_project_id
new_project_root.mkdir(parents=True, exist_ok=True)
(new_project_root / "config").mkdir(parents=True, exist_ok=True)
(new_project_root / "prompts").mkdir(parents=True, exist_ok=True)
(new_project_root / "data").mkdir(parents=True, exist_ok=True)
(new_project_root / "logs").mkdir(parents=True, exist_ok=True)
# Создаем project_info.json для нового тестового проекта
new_project_info_content = {
"name": "Another Test Project",
"type": "test",
"description": "A separate test project",
"version": "1.0",
"project_id": new_project_id,
"status": "created",
"created_at": datetime.now().isoformat()
}
with open(new_project_root / "project_info.json", "w", encoding="utf-8") as f:
json.dump(new_project_info_content, f, indent=2, ensure_ascii=False)
await context.set_current_project(str(new_project_root)) # Меняем ProjectContext
updated_registry = ProjectModelRegistry(new_project_id) # Создаем новый реестр для нового проекта
# Проверим, что реестр для нового проекта пуст (или содержит новые данные, если были)
assert updated_registry.get_model_for_role("chief") is None, "chief не должен быть в новом проекте"
print("✅ Новый реестр для другого проекта корректен (пуст). ")
updated_registry.register_model("flick", {"model_id": "test/flick:free", "provider": "openrouter"})
print("✅ Модель flick зарегистрирована в новом проекте.")
# Проверим, что старый реестр не изменился
final_registry = ProjectModelRegistry(test_project_id) # Загружаем старый реестр
assert final_registry.get_model_for_role("chief") is not None, "chief исчез из старого реестра"
assert final_registry.get_model_for_role("flick") is None, "flick появился в старом реестре"
print("✅ Целостность старого реестра сохранена.")
print("\n--- Все тесты ProjectModelRegistry пройдены успешно! ---")
# Очистка за собой
# if project_root.exists():
# shutil.rmtree(project_root)
# print(f"Удалена тестовая директория: {project_root}")
# if new_project_root.exists():
# shutil.rmtree(new_project_root)
# print(f"Удалена тестовая директория: {new_project_root}")
if __name__ == "__main__":
asyncio.run(test_registry_creation_and_use())
|