Added code samples for AI-Agents
This commit is contained in:
2
tests/__init__.py
Normal file
2
tests/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
||||
"""Тесты для AI-агентов."""
|
||||
|
||||
62
tests/test_chat_agent.py
Normal file
62
tests/test_chat_agent.py
Normal file
@@ -0,0 +1,62 @@
|
||||
"""Тесты для чат-агента."""
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock
|
||||
from uuid import uuid4
|
||||
|
||||
from agents.chat_agent import ChatAgent
|
||||
from agents.gigachat_client import GigaChatClient
|
||||
from models.gigachat_types import GigaChatMessage, GigaChatResponse, GigaChatUsage, GigaChatChoice
|
||||
from services.cache_service import CacheService
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_gigachat():
|
||||
"""Фикстура для мокового GigaChat клиента."""
|
||||
return AsyncMock(spec=GigaChatClient)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_cache():
|
||||
"""Фикстура для мокового CacheService."""
|
||||
return AsyncMock(spec=CacheService)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def chat_agent(mock_gigachat, mock_cache):
|
||||
"""Фикстура для ChatAgent."""
|
||||
return ChatAgent(gigachat=mock_gigachat, cache=mock_cache)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_chat_basic(chat_agent, mock_gigachat, mock_cache):
|
||||
"""Тест базового чата."""
|
||||
user_id = uuid4()
|
||||
message = "Привет!"
|
||||
|
||||
mock_response = GigaChatResponse(
|
||||
id="test_id",
|
||||
object="chat.completion",
|
||||
created=1234567890,
|
||||
model="GigaChat-2-Lite",
|
||||
choices=[
|
||||
GigaChatChoice(
|
||||
message=GigaChatMessage(role="assistant", content="Привет! Как дела? 🌍"),
|
||||
index=0,
|
||||
)
|
||||
],
|
||||
usage=GigaChatUsage(prompt_tokens=50, completion_tokens=10, total_tokens=60),
|
||||
)
|
||||
|
||||
mock_gigachat.chat_with_response.return_value = mock_response
|
||||
mock_cache.get_context.return_value = []
|
||||
|
||||
response, tokens = await chat_agent.chat(
|
||||
user_id=user_id,
|
||||
message=message,
|
||||
conversation_id="test_conv",
|
||||
)
|
||||
|
||||
assert response == "Привет! Как дела? 🌍"
|
||||
assert tokens == 60
|
||||
mock_cache.add_message.assert_called()
|
||||
|
||||
92
tests/test_gigachat_client.py
Normal file
92
tests/test_gigachat_client.py
Normal file
@@ -0,0 +1,92 @@
|
||||
"""Тесты для GigaChat клиента."""
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
from agents.gigachat_client import GigaChatClient
|
||||
from models.gigachat_types import GigaChatMessage, GigaChatResponse, GigaChatUsage, GigaChatChoice
|
||||
from services.token_manager import TokenManager
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def token_manager():
|
||||
"""Фикстура для TokenManager."""
|
||||
manager = TokenManager(
|
||||
client_id="test_id",
|
||||
client_secret="test_secret",
|
||||
)
|
||||
manager._access_token = "test_token"
|
||||
manager._expires_at = 9999999999
|
||||
return manager
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def gigachat_client(token_manager):
|
||||
"""Фикстура для GigaChatClient."""
|
||||
return GigaChatClient(token_manager=token_manager)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_chat_success(gigachat_client):
|
||||
"""Тест успешного запроса к GigaChat."""
|
||||
mock_response = GigaChatResponse(
|
||||
id="test_id",
|
||||
object="chat.completion",
|
||||
created=1234567890,
|
||||
model="GigaChat-2",
|
||||
choices=[
|
||||
GigaChatChoice(
|
||||
message=GigaChatMessage(role="assistant", content="Тестовый ответ"),
|
||||
index=0,
|
||||
finish_reason="stop",
|
||||
)
|
||||
],
|
||||
usage=GigaChatUsage(
|
||||
prompt_tokens=10,
|
||||
completion_tokens=5,
|
||||
total_tokens=15,
|
||||
),
|
||||
)
|
||||
|
||||
with patch("aiohttp.ClientSession.post") as mock_post:
|
||||
mock_response_obj = AsyncMock()
|
||||
mock_response_obj.status = 200
|
||||
mock_response_obj.json = AsyncMock(return_value=mock_response.model_dump())
|
||||
mock_post.return_value.__aenter__.return_value = mock_response_obj
|
||||
|
||||
response = await gigachat_client.chat("Привет!")
|
||||
|
||||
assert response == "Тестовый ответ"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_chat_with_context(gigachat_client):
|
||||
"""Тест запроса с контекстом."""
|
||||
context = [
|
||||
GigaChatMessage(role="system", content="Ты помощник"),
|
||||
GigaChatMessage(role="user", content="Привет"),
|
||||
]
|
||||
|
||||
mock_response = GigaChatResponse(
|
||||
id="test_id",
|
||||
object="chat.completion",
|
||||
created=1234567890,
|
||||
model="GigaChat-2",
|
||||
choices=[
|
||||
GigaChatChoice(
|
||||
message=GigaChatMessage(role="assistant", content="Ответ с контекстом"),
|
||||
index=0,
|
||||
)
|
||||
],
|
||||
usage=GigaChatUsage(prompt_tokens=20, completion_tokens=10, total_tokens=30),
|
||||
)
|
||||
|
||||
with patch("aiohttp.ClientSession.post") as mock_post:
|
||||
mock_response_obj = AsyncMock()
|
||||
mock_response_obj.status = 200
|
||||
mock_response_obj.json = AsyncMock(return_value=mock_response.model_dump())
|
||||
mock_post.return_value.__aenter__.return_value = mock_response_obj
|
||||
|
||||
response = await gigachat_client.chat("Как дела?", context=context)
|
||||
|
||||
assert response == "Ответ с контекстом"
|
||||
|
||||
89
tests/test_schedule_generator.py
Normal file
89
tests/test_schedule_generator.py
Normal file
@@ -0,0 +1,89 @@
|
||||
"""Тесты для генератора расписаний."""
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
from agents.gigachat_client import GigaChatClient
|
||||
from agents.schedule_generator import ScheduleGenerator
|
||||
from models.gigachat_types import GigaChatMessage, GigaChatResponse, GigaChatUsage, GigaChatChoice
|
||||
from services.token_manager import TokenManager
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_gigachat():
|
||||
"""Фикстура для мокового GigaChat клиента."""
|
||||
client = AsyncMock(spec=GigaChatClient)
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def schedule_generator(mock_gigachat):
|
||||
"""Фикстура для ScheduleGenerator."""
|
||||
return ScheduleGenerator(gigachat=mock_gigachat)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_generate_schedule(schedule_generator, mock_gigachat):
|
||||
"""Тест генерации расписания."""
|
||||
mock_response_json = """
|
||||
{
|
||||
"title": "Расписание на 2025-12-16",
|
||||
"tasks": [
|
||||
{
|
||||
"title": "Утренняя зарядка",
|
||||
"description": "Сделай зарядку",
|
||||
"duration_minutes": 15,
|
||||
"category": "утренняя_рутина"
|
||||
},
|
||||
{
|
||||
"title": "Завтрак",
|
||||
"description": "Позавтракай",
|
||||
"duration_minutes": 20,
|
||||
"category": "утренняя_рутина"
|
||||
}
|
||||
]
|
||||
}
|
||||
"""
|
||||
|
||||
mock_gigachat.chat.return_value = mock_response_json
|
||||
|
||||
schedule = await schedule_generator.generate(
|
||||
child_age=7,
|
||||
preferences=["рисование", "прогулка"],
|
||||
date="2025-12-16",
|
||||
)
|
||||
|
||||
assert schedule.title == "Расписание на 2025-12-16"
|
||||
assert len(schedule.tasks) == 2
|
||||
assert schedule.tasks[0].title == "Утренняя зарядка"
|
||||
assert schedule.tasks[0].duration_minutes == 15
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_generate_schedule_with_markdown(schedule_generator, mock_gigachat):
|
||||
"""Тест генерации с markdown в ответе."""
|
||||
mock_response_json = """
|
||||
```json
|
||||
{
|
||||
"title": "Тестовое расписание",
|
||||
"tasks": [
|
||||
{
|
||||
"title": "Тест",
|
||||
"duration_minutes": 10,
|
||||
"category": "обучение"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
"""
|
||||
|
||||
mock_gigachat.chat.return_value = mock_response_json
|
||||
|
||||
schedule = await schedule_generator.generate(
|
||||
child_age=5,
|
||||
preferences=[],
|
||||
date="2025-12-17",
|
||||
)
|
||||
|
||||
assert schedule.title == "Тестовое расписание"
|
||||
assert len(schedule.tasks) == 1
|
||||
|
||||
Reference in New Issue
Block a user