Download scripts/test_registry_a1.py from lhc-lab/AI-Colab: direct link, hf CLI and curl.
- Browser
- Download file 7.4 kB
-
https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/scripts/test_registry_a1.py
- Command line
-
hf download hf://datasets/lhc-lab/AI-Colab/scripts/test_registry_a1.py
-
curl -L -o test_registry_a1.py https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/scripts/test_registry_a1.py
7.4 kB
| 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()) | |