initial commit heh
This commit is contained in:
78 files changed
+11181
No files matched your search
@@ -0,0 +1,41 @@
|
||||
"""Unit tests for agent factory."""
|
||||
|
||||
from homeagent.agent.factory import create_agent
|
||||
from homeagent.agent.gemini import GeminiAgent
|
||||
from homeagent.agent.openai_agent import OpenAIAgent
|
||||
from homeagent.config import Settings
|
||||
|
||||
|
||||
def test_factory_creates_gemini_by_default(tmp_path):
|
||||
settings = Settings(LLM_PROVIDER="gemini", DATA_DIR=tmp_path)
|
||||
agent = create_agent(settings=settings)
|
||||
assert isinstance(agent, GeminiAgent)
|
||||
|
||||
|
||||
def test_factory_creates_deepseek(tmp_path):
|
||||
settings = Settings(
|
||||
LLM_PROVIDER="deepseek",
|
||||
DEEPSEEK_API_KEY="sk-fake",
|
||||
DEEPSEEK_MODEL="deepseek-chat",
|
||||
DATA_DIR=tmp_path,
|
||||
)
|
||||
agent = create_agent(settings=settings)
|
||||
assert isinstance(agent, OpenAIAgent)
|
||||
assert agent.provider == "deepseek"
|
||||
assert agent.base_url == "https://api.deepseek.com"
|
||||
assert agent.model == "deepseek-chat"
|
||||
|
||||
|
||||
def test_factory_creates_openai_compatible(tmp_path):
|
||||
settings = Settings(
|
||||
LLM_PROVIDER="openai",
|
||||
OPENAI_API_KEY="sk-fake",
|
||||
OPENAI_BASE_URL="https://openrouter.ai/api/v1",
|
||||
OPENAI_MODEL="deepseek/deepseek-chat",
|
||||
DATA_DIR=tmp_path,
|
||||
)
|
||||
agent = create_agent(settings=settings)
|
||||
assert isinstance(agent, OpenAIAgent)
|
||||
assert agent.provider == "openai"
|
||||
assert agent.base_url == "https://openrouter.ai/api/v1"
|
||||
assert agent.model == "deepseek/deepseek-chat"
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Unit tests for Google Calendar multi-calendar support."""
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
import pytest
|
||||
from extensions.google_calendar.tools import (
|
||||
calendar_date_schedule,
|
||||
calendar_list_calendars,
|
||||
calendar_list_events,
|
||||
calendar_today_schedule,
|
||||
calendar_tomorrow_schedule,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_calendar_unconfigured():
|
||||
with patch("extensions.google_calendar.tools.get_calendar_client") as mock_get_client:
|
||||
mock_client = MagicMock()
|
||||
mock_client.is_configured.return_value = False
|
||||
mock_get_client.return_value = mock_client
|
||||
|
||||
res = await calendar_list_events()
|
||||
assert "Google Календарь не настроен" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_calendar_list_calendars():
|
||||
with patch("extensions.google_calendar.tools.get_calendar_client") as mock_get_client:
|
||||
mock_client = MagicMock()
|
||||
mock_client.is_configured.return_value = True
|
||||
mock_client.list_calendars = AsyncMock(
|
||||
return_value=[
|
||||
{"id": "primary", "summary": "Основной (Личный)", "primary": True},
|
||||
{"id": "work@company.com", "summary": "Работа", "primary": False},
|
||||
{"id": "team@group.calendar.google.com", "summary": "Команда Dev", "primary": False},
|
||||
]
|
||||
)
|
||||
mock_get_client.return_value = mock_client
|
||||
|
||||
res = await calendar_list_calendars()
|
||||
assert "Доступные Google Календари (3):" in res
|
||||
assert "**Основной (Личный)** ⭐ (Основной)" in res
|
||||
assert "**Работа**" in res
|
||||
assert "**Команда Dev**" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_calendar_multi_calendar_events_tagged():
|
||||
with patch("extensions.google_calendar.tools.get_calendar_client") as mock_get_client:
|
||||
mock_client = MagicMock()
|
||||
mock_client.is_configured.return_value = True
|
||||
mock_client.list_events = AsyncMock(
|
||||
return_value=[
|
||||
{
|
||||
"id": "ev1",
|
||||
"summary": "Утренний кофе",
|
||||
"start": {"dateTime": "2026-11-08T09:00:00+03:00"},
|
||||
"end": {"dateTime": "2026-11-08T09:30:00+03:00"},
|
||||
"_calendar_name": "Личный",
|
||||
"_calendar_id": "primary",
|
||||
},
|
||||
{
|
||||
"id": "ev2",
|
||||
"summary": "Стендап проекта",
|
||||
"start": {"dateTime": "2026-11-08T10:00:00+03:00"},
|
||||
"end": {"dateTime": "2026-11-08T10:30:00+03:00"},
|
||||
"_calendar_name": "Работа",
|
||||
"_calendar_id": "work@company.com",
|
||||
},
|
||||
]
|
||||
)
|
||||
mock_get_client.return_value = mock_client
|
||||
|
||||
res = await calendar_today_schedule(include_tomorrow=True)
|
||||
assert "[Личный]" in res
|
||||
assert "Утренний кофе" in res
|
||||
assert "[Работа]" in res
|
||||
assert "Стендап проекта" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_calendar_tomorrow_schedule():
|
||||
with patch("extensions.google_calendar.tools.get_calendar_client") as mock_get_client:
|
||||
mock_client = MagicMock()
|
||||
mock_client.is_configured.return_value = True
|
||||
mock_client.list_events = AsyncMock(
|
||||
return_value=[
|
||||
{
|
||||
"id": "ev_tomorrow",
|
||||
"summary": "Проектная практика",
|
||||
"start": {"dateTime": "2026-11-08T16:30:00+03:00"},
|
||||
"end": {"dateTime": "2026-11-08T17:30:00+03:00"},
|
||||
"_calendar_name": "Учебный",
|
||||
"_calendar_id": "study@group.calendar.google.com",
|
||||
}
|
||||
]
|
||||
)
|
||||
mock_get_client.return_value = mock_client
|
||||
|
||||
res = await calendar_tomorrow_schedule()
|
||||
assert "Расписание на завтра" in res
|
||||
assert "Проектная практика" in res
|
||||
assert "[Учебный]" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_calendar_date_schedule():
|
||||
with patch("extensions.google_calendar.tools.get_calendar_client") as mock_get_client:
|
||||
mock_client = MagicMock()
|
||||
mock_client.is_configured.return_value = True
|
||||
mock_client.list_events = AsyncMock(
|
||||
return_value=[
|
||||
{
|
||||
"id": "ev_date",
|
||||
"summary": "Коллоквиум по алгосам",
|
||||
"start": {"dateTime": "2026-11-13T10:00:00+03:00"},
|
||||
"end": {"dateTime": "2026-11-13T13:00:00+03:00"},
|
||||
"_calendar_name": "Пары",
|
||||
"_calendar_id": "pairs@group.calendar.google.com",
|
||||
}
|
||||
]
|
||||
)
|
||||
mock_get_client.return_value = mock_client
|
||||
|
||||
res = await calendar_date_schedule("2026-11-13")
|
||||
assert "13.11.2026" in res
|
||||
assert "Коллоквиум по алгосам" in res
|
||||
assert "[Пары]" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_client_service_account_sync_and_resolution():
|
||||
from extensions.google_calendar.client import GoogleCalendarClient
|
||||
|
||||
client = GoogleCalendarClient()
|
||||
mock_service = MagicMock()
|
||||
client._service = mock_service
|
||||
|
||||
# Configure user settings
|
||||
client.default_calendar_id = "user@gmail.com"
|
||||
client.settings.GOOGLE_ADDITIONAL_CALENDAR_IDS = ["study@group.calendar.google.com"]
|
||||
|
||||
# Mock service account credentials
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.service_account_email = "sa@project.iam.gserviceaccount.com"
|
||||
client._get_credentials = MagicMock(return_value=mock_creds)
|
||||
|
||||
# calendarList.list returns the sa itself and study calendar
|
||||
mock_service.calendarList().list().execute.return_value = {
|
||||
"items": [
|
||||
{"id": "sa@project.iam.gserviceaccount.com", "summary": "sa", "primary": True},
|
||||
{"id": "study@group.calendar.google.com", "summary": "Учеба", "primary": False},
|
||||
]
|
||||
}
|
||||
# calendars.get returns metadata for user@gmail.com
|
||||
mock_service.calendars().get(calendarId="user@gmail.com").execute.return_value = {
|
||||
"id": "user@gmail.com",
|
||||
"summary": "Личный календарь",
|
||||
}
|
||||
|
||||
calendars = await client.list_calendars()
|
||||
|
||||
# The service account calendar should be filtered out
|
||||
ids = [c["id"] for c in calendars]
|
||||
assert "sa@project.iam.gserviceaccount.com" not in ids
|
||||
assert "user@gmail.com" in ids
|
||||
assert "study@group.calendar.google.com" in ids
|
||||
|
||||
# user@gmail.com should be primary
|
||||
user_cal = next(c for c in calendars if c["id"] == "user@gmail.com")
|
||||
assert user_cal["primary"] is True
|
||||
|
||||
# resolve_calendar_id should resolve 'primary' to 'user@gmail.com'
|
||||
resolved = await client.resolve_calendar_id("primary")
|
||||
assert resolved == "user@gmail.com"
|
||||
resolved_alias = await client.resolve_calendar_id("основной")
|
||||
assert resolved_alias == "user@gmail.com"
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Unit tests for conversation history and topic isolation."""
|
||||
|
||||
from google.genai import types
|
||||
from homeagent.agent.conversation import ConversationManager
|
||||
|
||||
|
||||
def test_topic_isolation_and_persistence(tmp_path):
|
||||
mgr = ConversationManager(data_dir=tmp_path, max_turns=5)
|
||||
|
||||
chat_id = 100
|
||||
topic_1 = 10
|
||||
topic_2 = 20
|
||||
|
||||
# Add turn to topic 1
|
||||
content_t1 = types.Content(
|
||||
role="user",
|
||||
parts=[types.Part.from_text(text="Question in Topic 1")],
|
||||
)
|
||||
mgr.append_content(chat_id, topic_1, content_t1)
|
||||
|
||||
# Add turn to topic 2
|
||||
content_t2 = types.Content(
|
||||
role="user",
|
||||
parts=[types.Part.from_text(text="Question in Topic 2")],
|
||||
)
|
||||
mgr.append_content(chat_id, topic_2, content_t2)
|
||||
|
||||
# Verify topic 1 only has topic 1 history
|
||||
h1 = mgr.get_history(chat_id, topic_1)
|
||||
assert len(h1) == 1
|
||||
assert h1[0].parts[0].text == "Question in Topic 1"
|
||||
|
||||
# Verify topic 2 only has topic 2 history
|
||||
h2 = mgr.get_history(chat_id, topic_2)
|
||||
assert len(h2) == 1
|
||||
assert h2[0].parts[0].text == "Question in Topic 2"
|
||||
|
||||
# Create new instance (simulating restart) to test disk persistence
|
||||
mgr_restarted = ConversationManager(data_dir=tmp_path, max_turns=5)
|
||||
loaded_h1 = mgr_restarted.get_history(chat_id, topic_1)
|
||||
assert len(loaded_h1) == 1
|
||||
assert loaded_h1[0].parts[0].text == "Question in Topic 1"
|
||||
|
||||
# Clear topic 1
|
||||
mgr_restarted.clear(chat_id, topic_1)
|
||||
assert len(mgr_restarted.get_history(chat_id, topic_1)) == 0
|
||||
# Topic 2 remains intact
|
||||
assert len(mgr_restarted.get_history(chat_id, topic_2)) == 1
|
||||
@@ -0,0 +1,221 @@
|
||||
"""Unit tests for Gitea extension tools."""
|
||||
|
||||
import base64
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
import pytest
|
||||
|
||||
from extensions.gitea.tools import (
|
||||
gitea_add_issue_comment,
|
||||
gitea_create_branch,
|
||||
gitea_create_issue,
|
||||
gitea_create_pull_request,
|
||||
gitea_get_file_or_dir,
|
||||
gitea_get_repo,
|
||||
gitea_list_branches,
|
||||
gitea_list_issues,
|
||||
gitea_list_pull_requests,
|
||||
gitea_list_repos,
|
||||
gitea_save_file,
|
||||
gitea_search_repos,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_client():
|
||||
client = MagicMock()
|
||||
client.is_configured.return_value = True
|
||||
client.web_url = "https://git.timka.su"
|
||||
return client
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_gitea_unconfigured():
|
||||
with patch("extensions.gitea.tools.get_gitea_client") as mock_get_client:
|
||||
client = MagicMock()
|
||||
client.is_configured.return_value = False
|
||||
client.web_url = "https://git.timka.su"
|
||||
mock_get_client.return_value = client
|
||||
|
||||
res = await gitea_list_repos()
|
||||
assert "Gitea не настроена" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_gitea_list_repos(mock_client):
|
||||
with patch("extensions.gitea.tools.get_gitea_client", return_value=mock_client):
|
||||
mock_client.list_user_repos = AsyncMock(
|
||||
return_value=[
|
||||
{
|
||||
"full_name": "timka/homeagent",
|
||||
"html_url": "https://git.timka.su/timka/homeagent",
|
||||
"description": "Telegram AI Assistant",
|
||||
"default_branch": "main",
|
||||
"private": True,
|
||||
"stars_count": 5,
|
||||
"open_issues_count": 2,
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
res = await gitea_list_repos()
|
||||
assert "timka/homeagent" in res
|
||||
assert "Telegram AI Assistant" in res
|
||||
assert "🔒 Приватный" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_gitea_get_repo_details(mock_client):
|
||||
with patch("extensions.gitea.tools.get_gitea_client", return_value=mock_client):
|
||||
mock_client.get_repo = AsyncMock(
|
||||
return_value={
|
||||
"full_name": "timka/homeagent",
|
||||
"html_url": "https://git.timka.su/timka/homeagent",
|
||||
"clone_url": "https://git.timka.su/timka/homeagent.git",
|
||||
"ssh_url": "git@git.timka.su:timka/homeagent.git",
|
||||
"description": "Personal bot",
|
||||
"default_branch": "main",
|
||||
"private": False,
|
||||
"stars_count": 10,
|
||||
"forks_count": 1,
|
||||
"open_issues_count": 3,
|
||||
"open_pr_counter": 1,
|
||||
}
|
||||
)
|
||||
|
||||
res = await gitea_get_repo("timka", "homeagent")
|
||||
assert "timka/homeagent" in res
|
||||
assert "HTTPS: `https://git.timka.su/timka/homeagent.git`" in res
|
||||
assert "Stars: 10" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_gitea_get_directory_contents(mock_client):
|
||||
with patch("extensions.gitea.tools.get_gitea_client", return_value=mock_client):
|
||||
mock_client.get_contents = AsyncMock(
|
||||
return_value=[
|
||||
{"name": "src", "type": "dir", "size": 0},
|
||||
{"name": "README.md", "type": "file", "size": 1024},
|
||||
]
|
||||
)
|
||||
|
||||
res = await gitea_get_file_or_dir("timka", "homeagent", "")
|
||||
assert "📁 **src/**" in res
|
||||
assert "📄 `README.md` (1024 B)" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_gitea_get_file_contents(mock_client):
|
||||
raw_code = "print('Hello from Gitea!')"
|
||||
b64_content = base64.b64encode(raw_code.encode("utf-8")).decode("utf-8")
|
||||
|
||||
with patch("extensions.gitea.tools.get_gitea_client", return_value=mock_client):
|
||||
mock_client.get_contents = AsyncMock(
|
||||
return_value={
|
||||
"name": "main.py",
|
||||
"type": "file",
|
||||
"size": len(raw_code),
|
||||
"encoding": "base64",
|
||||
"content": b64_content,
|
||||
}
|
||||
)
|
||||
|
||||
res = await gitea_get_file_or_dir("timka", "homeagent", "main.py")
|
||||
assert "Hello from Gitea!" in res
|
||||
assert "main.py" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_gitea_save_file_vibecoding(mock_client):
|
||||
with patch("extensions.gitea.tools.get_gitea_client", return_value=mock_client):
|
||||
mock_client.create_or_update_file = AsyncMock(
|
||||
return_value={
|
||||
"content": {"name": "app.py", "path": "app.py"},
|
||||
"commit": {"sha": "abcdef1234567890"},
|
||||
}
|
||||
)
|
||||
|
||||
res = await gitea_save_file(
|
||||
owner="timka",
|
||||
repo="homeagent",
|
||||
filepath="app.py",
|
||||
content="# New App\nimport sys",
|
||||
commit_message="feat: initial app setup",
|
||||
branch="dev",
|
||||
)
|
||||
assert "app.py" in res
|
||||
assert "abcdef12" in res
|
||||
assert "ветку `dev`" in res
|
||||
assert "feat: initial app setup" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_gitea_branches(mock_client):
|
||||
with patch("extensions.gitea.tools.get_gitea_client", return_value=mock_client):
|
||||
mock_client.list_branches = AsyncMock(
|
||||
return_value=[
|
||||
{"name": "main", "commit": {"id": "1122334455", "message": "Initial commit"}},
|
||||
{"name": "feat/ai", "commit": {"id": "aabbccddeeff", "message": "Add AI agent"}},
|
||||
]
|
||||
)
|
||||
mock_client.create_branch = AsyncMock(
|
||||
return_value={"name": "feat/cool-feature"}
|
||||
)
|
||||
|
||||
branches_res = await gitea_list_branches("timka", "homeagent")
|
||||
assert "🌿 `main`" in branches_res
|
||||
assert "🌿 `feat/ai`" in branches_res
|
||||
|
||||
create_res = await gitea_create_branch("timka", "homeagent", "feat/cool-feature", "main")
|
||||
assert "feat/cool-feature" in create_res
|
||||
assert "от `main`" in create_res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_gitea_issues_and_prs(mock_client):
|
||||
with patch("extensions.gitea.tools.get_gitea_client", return_value=mock_client):
|
||||
mock_client.list_issues = AsyncMock(
|
||||
return_value=[
|
||||
{
|
||||
"number": 1,
|
||||
"title": "Bug in parser",
|
||||
"html_url": "https://git.timka.su/timka/homeagent/issues/1",
|
||||
"user": {"login": "timka"},
|
||||
"comments": 2,
|
||||
"pull_request": None,
|
||||
}
|
||||
]
|
||||
)
|
||||
mock_client.create_issue = AsyncMock(
|
||||
return_value={
|
||||
"number": 2,
|
||||
"title": "Add calendar sync",
|
||||
"html_url": "https://git.timka.su/timka/homeagent/issues/2",
|
||||
}
|
||||
)
|
||||
mock_client.add_issue_comment = AsyncMock(
|
||||
return_value={
|
||||
"id": 10,
|
||||
"html_url": "https://git.timka.su/timka/homeagent/issues/2#comment-10",
|
||||
}
|
||||
)
|
||||
mock_client.create_pull_request = AsyncMock(
|
||||
return_value={
|
||||
"number": 3,
|
||||
"title": "Implement Gitea toolset",
|
||||
"html_url": "https://git.timka.su/timka/homeagent/pulls/3",
|
||||
}
|
||||
)
|
||||
|
||||
issues = await gitea_list_issues("timka", "homeagent")
|
||||
assert "Bug in parser" in issues
|
||||
|
||||
created_issue = await gitea_create_issue("timka", "homeagent", "Add calendar sync", "Details")
|
||||
assert "Add calendar sync" in created_issue
|
||||
assert "[#2]" in created_issue
|
||||
|
||||
comment_res = await gitea_add_issue_comment("timka", "homeagent", 2, "LGTM!")
|
||||
assert "успешно добавлен" in comment_res
|
||||
|
||||
pr_res = await gitea_create_pull_request("timka", "homeagent", "Implement Gitea toolset", "feat/gitea", "main")
|
||||
assert "Implement Gitea toolset" in pr_res
|
||||
assert "[#3]" in pr_res
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Unit tests for Global Shared Memory."""
|
||||
|
||||
from homeagent.memory.global_memory import GlobalMemory
|
||||
|
||||
|
||||
def test_global_memory_crud_and_search(tmp_path):
|
||||
storage_file = tmp_path / "global_memory.json"
|
||||
mem = GlobalMemory(storage_file)
|
||||
|
||||
# 1. Add facts
|
||||
item1 = mem.add_fact("Пользователь предпочитает короткие ответы", category="user")
|
||||
item2 = mem.add_fact("Основной проект в Jira: PROJ", category="jira")
|
||||
|
||||
assert len(mem.list_facts()) == 2
|
||||
|
||||
# 2. Search
|
||||
results = mem.search("Jira")
|
||||
assert len(results) == 1
|
||||
assert results[0].id == item2.id
|
||||
|
||||
# 3. Category filter
|
||||
user_facts = mem.list_facts(category="user")
|
||||
assert len(user_facts) == 1
|
||||
assert user_facts[0].id == item1.id
|
||||
|
||||
# 4. Persistence check
|
||||
mem2 = GlobalMemory(storage_file)
|
||||
assert len(mem2.list_facts()) == 2
|
||||
|
||||
# 5. Summary formatting
|
||||
summary = mem2.get_memory_summary()
|
||||
assert "[ГЛОБАЛЬНАЯ ПАМЯТЬ" in summary
|
||||
assert "PROJ" in summary
|
||||
|
||||
# 6. Delete
|
||||
assert mem2.remove_fact(item1.id)
|
||||
assert len(mem2.list_facts()) == 1
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Unit tests for bot Rich Messages sending and error fallback."""
|
||||
|
||||
from datetime import datetime
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
from aiogram.types import Chat, Message, User
|
||||
from homeagent.bot.handlers import _send_reply
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_reply_rich_message_success():
|
||||
bot = MagicMock()
|
||||
bot.send_rich_message = AsyncMock()
|
||||
|
||||
user = User(id=1, is_bot=False, first_name="Test")
|
||||
chat = Chat(id=-100123, type="supergroup")
|
||||
msg = Message(
|
||||
message_id=42,
|
||||
date=datetime.now(),
|
||||
chat=chat,
|
||||
from_user=user,
|
||||
message_thread_id=11,
|
||||
is_topic_message=True,
|
||||
)
|
||||
msg._bot = bot
|
||||
|
||||
await _send_reply(msg, "Hello in topic with **Rich Message**!")
|
||||
|
||||
bot.send_rich_message.assert_awaited_once()
|
||||
kwargs = bot.send_rich_message.await_args.kwargs
|
||||
assert kwargs["chat_id"] == -100123
|
||||
assert kwargs["message_thread_id"] == 11
|
||||
rich_msg = kwargs["rich_message"]
|
||||
assert rich_msg.markdown == "Hello in topic with **Rich Message**!"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_reply_rich_message_fallback_to_html():
|
||||
bot = MagicMock()
|
||||
# First call with markdown fails, second call with html succeeds
|
||||
bot.send_rich_message = AsyncMock(side_effect=[Exception("Invalid Markdown"), None])
|
||||
|
||||
user = User(id=1, is_bot=False, first_name="Test")
|
||||
chat = Chat(id=-100123, type="supergroup")
|
||||
msg = Message(
|
||||
message_id=42,
|
||||
date=datetime.now(),
|
||||
chat=chat,
|
||||
from_user=user,
|
||||
message_thread_id=11,
|
||||
is_topic_message=True,
|
||||
)
|
||||
msg._bot = bot
|
||||
|
||||
await _send_reply(msg, "Text with _bad markdown")
|
||||
|
||||
assert bot.send_rich_message.await_count == 2
|
||||
second_kwargs = bot.send_rich_message.await_args_list[1].kwargs
|
||||
assert second_kwargs["rich_message"].html == "Text with _bad markdown"
|
||||
assert second_kwargs["message_thread_id"] == 11
|
||||
@@ -0,0 +1,263 @@
|
||||
"""Unit tests for Jira tools."""
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
import pytest
|
||||
from extensions.jira.client import JiraClient
|
||||
from extensions.jira.tools import (
|
||||
jira_get_editable_fields,
|
||||
jira_get_issue,
|
||||
jira_search,
|
||||
jira_search_users,
|
||||
jira_update_issue,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_jira_unconfigured():
|
||||
with patch("extensions.jira.tools.get_jira_client") as mock_get_client:
|
||||
mock_client = MagicMock()
|
||||
mock_client.is_configured.return_value = False
|
||||
mock_get_client.return_value = mock_client
|
||||
|
||||
res = await jira_search("assignee = currentUser()")
|
||||
assert "Jira не настроена" in res
|
||||
|
||||
res_update = await jira_update_issue("DEV-1", summary="New")
|
||||
assert "Jira не настроена" in res_update
|
||||
|
||||
res_fields = await jira_get_editable_fields("DEV-1")
|
||||
assert "Jira не настроена" in res_fields
|
||||
|
||||
res_users = await jira_search_users("Ivan")
|
||||
assert "Jira не настроена" in res_users
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_jira_search_mocked():
|
||||
with patch("extensions.jira.tools.get_jira_client") as mock_get_client:
|
||||
mock_client = MagicMock()
|
||||
mock_client.is_configured.return_value = True
|
||||
mock_client.search_issues = AsyncMock(
|
||||
return_value=[
|
||||
{
|
||||
"key": "DEV-42",
|
||||
"fields": {
|
||||
"summary": "Fix login bug",
|
||||
"status": {"name": "In Progress"},
|
||||
"priority": {"name": "High"},
|
||||
"assignee": {"displayName": "John Doe"},
|
||||
},
|
||||
}
|
||||
]
|
||||
)
|
||||
mock_get_client.return_value = mock_client
|
||||
|
||||
res = await jira_search("assignee = currentUser()")
|
||||
assert "DEV-42" in res
|
||||
assert "Fix login bug" in res
|
||||
assert "In Progress" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_jira_get_editable_fields():
|
||||
with patch("extensions.jira.tools.get_jira_client") as mock_get_client:
|
||||
mock_client = MagicMock()
|
||||
mock_client.is_configured.return_value = True
|
||||
mock_client.get_edit_meta = AsyncMock(
|
||||
return_value={
|
||||
"fields": {
|
||||
"summary": {
|
||||
"name": "Summary",
|
||||
"required": True,
|
||||
"schema": {"type": "string"},
|
||||
},
|
||||
"priority": {
|
||||
"name": "Priority",
|
||||
"required": False,
|
||||
"schema": {"type": "priority"},
|
||||
"allowedValues": [{"name": "Highest"}, {"name": "Low"}],
|
||||
},
|
||||
"customfield_10016": {
|
||||
"name": "Story Points",
|
||||
"required": False,
|
||||
"schema": {"type": "number"},
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
mock_get_client.return_value = mock_client
|
||||
|
||||
res = await jira_get_editable_fields("DEV-42")
|
||||
assert "DEV-42" in res
|
||||
assert "summary" in res
|
||||
assert "[Обязательное]" in res
|
||||
assert "Priority" in res
|
||||
assert "Highest, Low" in res
|
||||
assert "customfield_10016" in res
|
||||
assert "Story Points" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_jira_search_users():
|
||||
with patch("extensions.jira.tools.get_jira_client") as mock_get_client:
|
||||
mock_client = MagicMock()
|
||||
mock_client.is_configured.return_value = True
|
||||
mock_client.search_users = AsyncMock(
|
||||
return_value=[
|
||||
{
|
||||
"displayName": "Alex Developer",
|
||||
"accountId": "acc-12345",
|
||||
"emailAddress": "alex@example.com",
|
||||
"active": True,
|
||||
}
|
||||
]
|
||||
)
|
||||
mock_get_client.return_value = mock_client
|
||||
|
||||
res = await jira_search_users("Alex")
|
||||
assert "Alex Developer" in res
|
||||
assert "acc-12345" in res
|
||||
assert "alex@example.com" in res
|
||||
assert "Активен" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_jira_update_issue_standard_and_custom_fields():
|
||||
with patch("extensions.jira.tools.get_jira_client") as mock_get_client:
|
||||
mock_client = MagicMock()
|
||||
mock_client.is_configured.return_value = True
|
||||
mock_client.browse_url.return_value = "https://jira.example.com/browse/DEV-42"
|
||||
mock_client.update_issue = AsyncMock(return_value={"status": "success"})
|
||||
mock_client.resolve_user = AsyncMock(
|
||||
return_value={"accountId": "acc-999", "displayName": "Bob Builder"}
|
||||
)
|
||||
mock_client.get_edit_meta = AsyncMock(
|
||||
return_value={
|
||||
"fields": {
|
||||
"customfield_10016": {"name": "Story Points", "schema": {"type": "number"}},
|
||||
}
|
||||
}
|
||||
)
|
||||
mock_client.get_transitions = AsyncMock(
|
||||
return_value=[{"id": "31", "name": "In Progress"}]
|
||||
)
|
||||
mock_client.transition_issue = AsyncMock()
|
||||
mock_get_client.return_value = mock_client
|
||||
|
||||
res = await jira_update_issue(
|
||||
issue_key="dev-42",
|
||||
summary="Refactor auth",
|
||||
description="New description content",
|
||||
status="In Progress",
|
||||
assignee="Bob",
|
||||
priority="Highest",
|
||||
duedate="2026-12-31",
|
||||
labels=["backend", "security"],
|
||||
components=["Auth Module"],
|
||||
issue_type="Bug",
|
||||
custom_fields={"Story Points": 8, "customfield_10020": 42},
|
||||
)
|
||||
|
||||
assert "DEV-42" in res
|
||||
assert "успешно обновлена" in res
|
||||
assert "Refactor auth" in res
|
||||
assert "Статус -> 'In Progress'" in res
|
||||
assert "Bob Builder" in res
|
||||
assert "Highest" in res
|
||||
assert "2026-12-31" in res
|
||||
assert "Story Points" in res
|
||||
|
||||
# Verify update_issue payload passed to client
|
||||
mock_client.update_issue.assert_awaited_once()
|
||||
call_key, call_payload = mock_client.update_issue.call_args[0]
|
||||
assert call_key == "DEV-42"
|
||||
assert call_payload["summary"] == "Refactor auth"
|
||||
assert call_payload["priority"] == {"name": "Highest"}
|
||||
assert call_payload["duedate"] == "2026-12-31"
|
||||
assert call_payload["labels"] == ["backend", "security"]
|
||||
assert call_payload["components"] == [{"name": "Auth Module"}]
|
||||
assert call_payload["issuetype"] == {"name": "Bug"}
|
||||
assert call_payload["assignee"] == {"accountId": "acc-999"}
|
||||
assert call_payload["customfield_10016"] == 8
|
||||
assert call_payload["customfield_10020"] == 42
|
||||
assert "version" in call_payload["description"]
|
||||
|
||||
# Verify transition was called
|
||||
mock_client.transition_issue.assert_awaited_once_with("DEV-42", "31")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_jira_update_issue_unassign_and_clear_due():
|
||||
with patch("extensions.jira.tools.get_jira_client") as mock_get_client:
|
||||
mock_client = MagicMock()
|
||||
mock_client.is_configured.return_value = True
|
||||
mock_client.browse_url.return_value = "https://jira.example.com/browse/DEV-42"
|
||||
mock_client.update_issue = AsyncMock(return_value={"status": "success"})
|
||||
mock_get_client.return_value = mock_client
|
||||
|
||||
res = await jira_update_issue(
|
||||
issue_key="DEV-42",
|
||||
assignee="unassigned",
|
||||
duedate="clear",
|
||||
)
|
||||
|
||||
assert "DEV-42" in res
|
||||
assert "Исполнитель -> Снят (Unassigned)" in res
|
||||
assert "Дедлайн -> Снят" in res
|
||||
|
||||
mock_client.update_issue.assert_awaited_once()
|
||||
call_key, call_payload = mock_client.update_issue.call_args[0]
|
||||
assert call_payload["assignee"] is None
|
||||
assert call_payload["duedate"] is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_jira_update_issue_no_fields():
|
||||
with patch("extensions.jira.tools.get_jira_client") as mock_get_client:
|
||||
mock_client = MagicMock()
|
||||
mock_client.is_configured.return_value = True
|
||||
mock_get_client.return_value = mock_client
|
||||
|
||||
res = await jira_update_issue(issue_key="DEV-42")
|
||||
assert "Не указаны поля" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_jira_client_update_and_meta():
|
||||
client = JiraClient(base_url="https://jira.example.com", email="test@example.com", api_token="secret")
|
||||
client._request = AsyncMock(return_value={"status": "success", "status_code": 204})
|
||||
|
||||
# Test update_issue v3
|
||||
await client.update_issue("DEV-10", {"summary": "Updated"})
|
||||
client._request.assert_awaited_with(
|
||||
"PUT",
|
||||
"rest/api/3/issue/DEV-10",
|
||||
json_data={"fields": {"summary": "Updated"}},
|
||||
)
|
||||
|
||||
# Test get_edit_meta
|
||||
client._request.return_value = {"fields": {"summary": {}}}
|
||||
meta = await client.get_edit_meta("DEV-10")
|
||||
assert "summary" in meta["fields"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_jira_client_resolve_user():
|
||||
client = JiraClient(base_url="https://jira.example.com", email="test@example.com", api_token="secret")
|
||||
client.search_users = AsyncMock(
|
||||
return_value=[
|
||||
{"displayName": "Alice Smith", "emailAddress": "alice@company.com", "accountId": "acc-alice"},
|
||||
{"displayName": "Bob Builder", "emailAddress": "bob@company.com", "accountId": "acc-bob"},
|
||||
]
|
||||
)
|
||||
|
||||
# Test exact email match
|
||||
u1 = await client.resolve_user("bob@company.com")
|
||||
assert u1 is not None
|
||||
assert u1["accountId"] == "acc-bob"
|
||||
|
||||
# Test unassigned
|
||||
u_none = await client.resolve_user("unassigned")
|
||||
assert u_none is None
|
||||
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
"""Unit tests for OpenAIAgent supporting DeepSeek and OpenAI-compatible models."""
|
||||
|
||||
import json
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
|
||||
from homeagent.agent.conversation import ConversationManager
|
||||
from homeagent.agent.openai_agent import OpenAIAgent
|
||||
from homeagent.config import Settings
|
||||
from homeagent.tools.base import tool
|
||||
from homeagent.tools.registry import ToolRegistry
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_deepseek_unconfigured(tmp_path):
|
||||
settings = Settings(
|
||||
LLM_PROVIDER="deepseek",
|
||||
DEEPSEEK_API_KEY="",
|
||||
DATA_DIR=tmp_path,
|
||||
)
|
||||
conv_mgr = ConversationManager(tmp_path)
|
||||
agent = OpenAIAgent(settings=settings, conversation_manager=conv_mgr)
|
||||
|
||||
res = await agent.chat(chat_id=101, thread_id=1, user_message="Hello")
|
||||
assert "DeepSeek API Key не настроен" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_openai_unconfigured(tmp_path):
|
||||
settings = Settings(
|
||||
LLM_PROVIDER="openai",
|
||||
OPENAI_API_KEY="",
|
||||
DATA_DIR=tmp_path,
|
||||
)
|
||||
conv_mgr = ConversationManager(tmp_path)
|
||||
agent = OpenAIAgent(settings=settings, conversation_manager=conv_mgr)
|
||||
|
||||
res = await agent.chat(chat_id=101, thread_id=1, user_message="Hello")
|
||||
assert "OpenAI / OpenAI-compatible API Key не настроен" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_deepseek_simple_chat(tmp_path):
|
||||
settings = Settings(
|
||||
LLM_PROVIDER="deepseek",
|
||||
DEEPSEEK_API_KEY="sk-mock-deepseek",
|
||||
DEEPSEEK_MODEL="deepseek-chat",
|
||||
DATA_DIR=tmp_path,
|
||||
)
|
||||
conv_mgr = ConversationManager(tmp_path)
|
||||
agent = OpenAIAgent(settings=settings, conversation_manager=conv_mgr)
|
||||
|
||||
# Mock OpenAI client
|
||||
mock_client = MagicMock()
|
||||
mock_choice = MagicMock()
|
||||
mock_choice.message.content = "Привет! Я DeepSeek."
|
||||
mock_choice.message.tool_calls = None
|
||||
|
||||
mock_resp = MagicMock()
|
||||
mock_resp.choices = [mock_choice]
|
||||
|
||||
mock_client.chat.completions.create = AsyncMock(return_value=mock_resp)
|
||||
agent._client = mock_client
|
||||
|
||||
reply = await agent.chat(chat_id=123, thread_id=456, user_message="Привет!")
|
||||
assert reply == "Привет! Я DeepSeek."
|
||||
|
||||
# Check conversation history saved
|
||||
history = conv_mgr.get_openai_messages(chat_id=123, thread_id=456)
|
||||
assert len(history) == 2
|
||||
assert history[0]["role"] == "user"
|
||||
assert history[0]["content"] == "Привет!"
|
||||
assert history[1]["role"] == "assistant"
|
||||
assert history[1]["content"] == "Привет! Я DeepSeek."
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_openai_tool_calling_loop(tmp_path):
|
||||
settings = Settings(
|
||||
LLM_PROVIDER="openai",
|
||||
OPENAI_API_KEY="sk-mock-openai",
|
||||
OPENAI_MODEL="gpt-4o",
|
||||
DATA_DIR=tmp_path,
|
||||
)
|
||||
conv_mgr = ConversationManager(tmp_path)
|
||||
registry = ToolRegistry()
|
||||
|
||||
@tool(name="weather_check", description="Check city weather")
|
||||
def weather_check(city: str) -> str:
|
||||
return f"{city}: +22C, ясно"
|
||||
|
||||
registry.register(weather_check)
|
||||
|
||||
agent = OpenAIAgent(settings=settings, registry=registry, conversation_manager=conv_mgr)
|
||||
|
||||
# Turn 1: Model returns tool_call
|
||||
mock_tool_call = MagicMock()
|
||||
mock_tool_call.id = "call_abc123"
|
||||
mock_tool_call.function.name = "weather_check"
|
||||
mock_tool_call.function.arguments = json.dumps({"city": "Москва"})
|
||||
|
||||
choice_1 = MagicMock()
|
||||
choice_1.message.content = "Сейчас проверю погоду..."
|
||||
choice_1.message.tool_calls = [mock_tool_call]
|
||||
resp_1 = MagicMock()
|
||||
resp_1.choices = [choice_1]
|
||||
|
||||
# Turn 2: Model returns final text after getting tool result
|
||||
choice_2 = MagicMock()
|
||||
choice_2.message.content = "В Москве сейчас +22C, ясно!"
|
||||
choice_2.message.tool_calls = None
|
||||
resp_2 = MagicMock()
|
||||
resp_2.choices = [choice_2]
|
||||
|
||||
mock_client = MagicMock()
|
||||
mock_client.chat.completions.create = AsyncMock(side_effect=[resp_1, resp_2])
|
||||
agent._client = mock_client
|
||||
|
||||
reply = await agent.chat(chat_id=999, thread_id=1, user_message="Какая погода в Москве?")
|
||||
assert reply == "В Москве сейчас +22C, ясно!"
|
||||
assert mock_client.chat.completions.create.call_count == 2
|
||||
|
||||
|
||||
def test_legacy_session_sanitization(tmp_path):
|
||||
"""Test that a legacy session with function_call and function_response is properly aligned for OpenAI/DeepSeek."""
|
||||
conv_mgr = ConversationManager(tmp_path)
|
||||
session_file = tmp_path / "sessions" / "session_123_main.json"
|
||||
session_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
legacy_data = [
|
||||
{"role": "user", "parts": [{"text": "какие события на сегодня"}]},
|
||||
{"role": "model", "parts": [{"function_call": {"name": "calendar_today_schedule", "args": {}}}]},
|
||||
{"role": "user", "parts": [{"function_response": {"name": "calendar_today_schedule", "response": {"result": "Встреч нет"}}}]},
|
||||
{"role": "model", "parts": [{"text": "На сегодня встреч нет."}]},
|
||||
]
|
||||
with open(session_file, "w", encoding="utf-8") as f:
|
||||
json.dump(legacy_data, f)
|
||||
|
||||
messages = conv_mgr.get_openai_messages(chat_id=123, thread_id=None)
|
||||
assert len(messages) == 4
|
||||
assert messages[0]["role"] == "user"
|
||||
assert messages[1]["role"] == "assistant"
|
||||
assert messages[1]["tool_calls"] is not None
|
||||
assert len(messages[1]["tool_calls"]) == 1
|
||||
|
||||
tool_call_id = messages[1]["tool_calls"][0]["id"]
|
||||
assert messages[2]["role"] == "tool"
|
||||
# The tool response tool_call_id MUST MATCH the assistant tool_calls id
|
||||
assert messages[2]["tool_call_id"] == tool_call_id
|
||||
assert messages[3]["role"] == "assistant"
|
||||
assert messages[3]["content"] == "На сегодня встреч нет."
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Unit tests for OpenAI tool schema generation in ToolRegistry."""
|
||||
|
||||
from homeagent.tools.base import tool
|
||||
from homeagent.tools.registry import ToolRegistry
|
||||
|
||||
|
||||
def test_openai_tools_conversion():
|
||||
registry = ToolRegistry()
|
||||
|
||||
@tool(name="calc_add", description="Add two numbers")
|
||||
def calc_add(a: int, b: int = 0) -> str:
|
||||
"""Add two integers.
|
||||
|
||||
Args:
|
||||
a: First number
|
||||
b: Second number
|
||||
"""
|
||||
return str(a + b)
|
||||
|
||||
registry.register(calc_add)
|
||||
|
||||
tools = registry.get_openai_tools()
|
||||
assert len(tools) == 1
|
||||
t = tools[0]
|
||||
assert t["type"] == "function"
|
||||
assert t["function"]["name"] == "calc_add"
|
||||
assert t["function"]["description"] == "Add two numbers"
|
||||
|
||||
params = t["function"]["parameters"]
|
||||
assert params["type"] == "object"
|
||||
assert "a" in params["properties"]
|
||||
assert params["properties"]["a"]["type"] == "integer"
|
||||
assert "b" in params["properties"]
|
||||
assert params["required"] == ["a"]
|
||||
|
||||
|
||||
def test_openai_tools_exclude_subagents():
|
||||
registry = ToolRegistry()
|
||||
|
||||
@tool(name="spawn_subagent", description="Subagent tool")
|
||||
def dummy_spawn(task: str) -> str:
|
||||
return task
|
||||
|
||||
@tool(name="regular_tool", description="Regular tool")
|
||||
def dummy_regular() -> str:
|
||||
return "ok"
|
||||
|
||||
registry.register(dummy_spawn)
|
||||
registry.register(dummy_regular)
|
||||
|
||||
all_tools = registry.get_openai_tools(exclude_subagents=False)
|
||||
assert any(t["function"]["name"] == "spawn_subagent" for t in all_tools)
|
||||
|
||||
subagent_tools = registry.get_openai_tools(exclude_subagents=True)
|
||||
assert not any(t["function"]["name"] == "spawn_subagent" for t in subagent_tools)
|
||||
assert any(t["function"]["name"] == "regular_tool" for t in subagent_tools)
|
||||
@@ -0,0 +1,160 @@
|
||||
"""Unit tests for ProgressReporter and tool progress formatting."""
|
||||
|
||||
import asyncio
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
|
||||
from homeagent.bot.progress import ProgressReporter, format_tool_progress
|
||||
|
||||
|
||||
def test_format_tool_progress_known_tools():
|
||||
# Web search
|
||||
assert "Ищу в интернете" in format_tool_progress("web_search", {"query": "weather in Moscow"})
|
||||
# Fetch page
|
||||
assert "Читаю веб-страницу" in format_tool_progress("web_fetch_page", {"url": "https://example.com/test"})
|
||||
# Sandbox tools
|
||||
assert "песочниц" in format_tool_progress("code_execute", {"language": "python", "code": "print(1)"})
|
||||
assert "песочниц" in format_tool_progress("sandbox_run_command", {"command": "ls -la"})
|
||||
assert "песочниц" in format_tool_progress("sandbox_file_write", {"filename": "main.py"})
|
||||
assert "песочниц" in format_tool_progress("sandbox_file_read", {"filename": "main.py"})
|
||||
assert "Очищаю" in format_tool_progress("sandbox_reset", {})
|
||||
|
||||
# Calendar
|
||||
assert "расписание на сегодня" in format_tool_progress("calendar_today_schedule", {})
|
||||
assert "расписание на завтра" in format_tool_progress("calendar_tomorrow_schedule", {})
|
||||
assert "2026-11-08" in format_tool_progress("calendar_date_schedule", {"date_str": "2026-11-08"})
|
||||
|
||||
# Jira
|
||||
assert "Jira" in format_tool_progress("jira_my_issues", {})
|
||||
assert "KAN-42" in format_tool_progress("jira_get_issue", {"issue_key": "KAN-42"})
|
||||
|
||||
# Gitea
|
||||
assert "Gitea" in format_tool_progress("gitea_list_repos", {})
|
||||
assert "vibecoding" in format_tool_progress("gitea_save_file_vibecoding", {"filepath": "app.py"}) or "Gitea" in format_tool_progress("gitea_save_file_vibecoding", {"filepath": "app.py"})
|
||||
|
||||
# Subagents
|
||||
assert "подагента" in format_tool_progress("spawn_subagent", {"role": "исследователь"})
|
||||
assert "параллельных подагентов" in format_tool_progress("spawn_parallel_subagents", {"tasks": [1, 2]})
|
||||
|
||||
# Fallback
|
||||
assert "custom_tool" in format_tool_progress("custom_tool", {"arg": "val"})
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_progress_reporter_lifecycle():
|
||||
mock_bot = MagicMock()
|
||||
mock_sent_msg = AsyncMock()
|
||||
mock_sent_msg.edit_text = AsyncMock()
|
||||
mock_sent_msg.delete = AsyncMock()
|
||||
|
||||
mock_bot.send_message = AsyncMock(return_value=mock_sent_msg)
|
||||
|
||||
reporter = ProgressReporter(bot=mock_bot, chat_id=12345, thread_id=99)
|
||||
reporter._min_interval = 0.01 # accelerate for tests
|
||||
|
||||
# 1. Start
|
||||
await reporter.start("⏳ Думаю...")
|
||||
assert reporter.message is mock_sent_msg
|
||||
mock_bot.send_message.assert_called_once_with(
|
||||
chat_id=12345,
|
||||
text="⏳ Думаю...",
|
||||
message_thread_id=99,
|
||||
)
|
||||
|
||||
# 2. Update
|
||||
await reporter.update("🔍 Ищу в интернете...")
|
||||
mock_sent_msg.edit_text.assert_called_once_with(text="🔍 Ищу в интернете...")
|
||||
|
||||
# Update with duplicate text should not trigger another edit
|
||||
mock_sent_msg.edit_text.reset_mock()
|
||||
await reporter.update("🔍 Ищу в интернете...")
|
||||
mock_sent_msg.edit_text.assert_not_called()
|
||||
|
||||
# 3. Finish
|
||||
await reporter.finish()
|
||||
mock_sent_msg.delete.assert_called_once()
|
||||
assert reporter.message is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_progress_reporter_send_error_suppression():
|
||||
mock_bot = MagicMock()
|
||||
mock_bot.send_message = AsyncMock(side_effect=RuntimeError("Network error"))
|
||||
|
||||
reporter = ProgressReporter(bot=mock_bot, chat_id=12345)
|
||||
await reporter.start("Test")
|
||||
assert reporter.message is None
|
||||
|
||||
# Calling update or finish with no message should not raise
|
||||
await reporter.update("New status")
|
||||
await reporter.finish()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_progress_reporter_delete_error_suppression():
|
||||
mock_bot = MagicMock()
|
||||
mock_sent_msg = AsyncMock()
|
||||
mock_sent_msg.delete = AsyncMock(side_effect=RuntimeError("Message not found"))
|
||||
mock_bot.send_message = AsyncMock(return_value=mock_sent_msg)
|
||||
|
||||
reporter = ProgressReporter(bot=mock_bot, chat_id=12345)
|
||||
await reporter.start()
|
||||
# Should not raise exception
|
||||
await reporter.finish()
|
||||
assert reporter.message is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_agent_calls_on_progress(tmp_path):
|
||||
from homeagent.agent.conversation import ConversationManager
|
||||
from homeagent.agent.openai_agent import OpenAIAgent
|
||||
from homeagent.config import Settings
|
||||
from homeagent.tools.base import tool
|
||||
from homeagent.tools.registry import ToolRegistry
|
||||
|
||||
settings = Settings(
|
||||
LLM_PROVIDER="deepseek",
|
||||
DEEPSEEK_API_KEY="sk-test",
|
||||
DATA_DIR=tmp_path,
|
||||
)
|
||||
conv_mgr = ConversationManager(tmp_path)
|
||||
registry = ToolRegistry()
|
||||
|
||||
@tool(name="mock_calc", description="calc")
|
||||
def mock_calc(x: int) -> int:
|
||||
return x * 2
|
||||
|
||||
registry.register(mock_calc)
|
||||
agent = OpenAIAgent(settings=settings, conversation_manager=conv_mgr, registry=registry)
|
||||
|
||||
# Mock client with 1 tool call then final message
|
||||
mock_client = MagicMock()
|
||||
call1 = MagicMock()
|
||||
call1.id = "call_1"
|
||||
call1.function.name = "mock_calc"
|
||||
call1.function.arguments = '{"x": 21}'
|
||||
|
||||
msg1 = MagicMock()
|
||||
msg1.content = None
|
||||
msg1.tool_calls = [call1]
|
||||
resp1 = MagicMock(choices=[MagicMock(message=msg1)])
|
||||
|
||||
msg2 = MagicMock()
|
||||
msg2.content = "Результат вычисления: 42"
|
||||
msg2.tool_calls = None
|
||||
resp2 = MagicMock(choices=[MagicMock(message=msg2)])
|
||||
|
||||
mock_client.chat.completions.create = AsyncMock(side_effect=[resp1, resp2])
|
||||
agent._client = mock_client
|
||||
|
||||
progress_updates = []
|
||||
|
||||
async def progress_cb(text: str) -> None:
|
||||
progress_updates.append(text)
|
||||
|
||||
ans = await agent.chat(chat_id=1, thread_id=None, user_message="Сколько будет 21*2?", on_progress=progress_cb)
|
||||
|
||||
assert "42" in ans
|
||||
assert len(progress_updates) >= 2
|
||||
assert any("Формирую ответ" in u for u in progress_updates)
|
||||
assert any("mock_calc" in u for u in progress_updates)
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Unit tests for the Safe Code Execution Sandbox extension."""
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
import pytest
|
||||
|
||||
from extensions.sandbox.base import ExecutionResult
|
||||
from extensions.sandbox.manager import SandboxManager
|
||||
from extensions.sandbox.tools import (
|
||||
code_execute,
|
||||
sandbox_file_read,
|
||||
sandbox_file_write,
|
||||
sandbox_reset,
|
||||
sandbox_run_command,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_code_execute_python_arithmetic():
|
||||
code = "total = sum(range(1, 101))\nprint(f'Sum: {total}')"
|
||||
res = await code_execute(code=code, language="python")
|
||||
assert "Sum: 5050" in res
|
||||
assert "Sandbox:" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_code_execute_syntax_error():
|
||||
bad_code = "def invalid_syntax(:\n pass"
|
||||
res = await code_execute(code=bad_code, language="python")
|
||||
assert "SyntaxError" in res or "Ошибка" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_code_execute_timeout():
|
||||
# Loop that takes longer than 1 second
|
||||
infinite_code = "import time\ntime.sleep(5)"
|
||||
res = await code_execute(code=infinite_code, language="python", timeout=1)
|
||||
assert "Превышен лимит времени выполнения" in res or "таймаут" in res.lower()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sandbox_isolation_cannot_access_host():
|
||||
"""Verify that host home directory and secrets (.env) are completely invisible in sandbox."""
|
||||
check_code = """
|
||||
import os
|
||||
print("HOME_EXISTS:", os.path.exists("/home"))
|
||||
print("ENV_EXISTS:", os.path.exists("/home/timka/code/homeagent/.env"))
|
||||
"""
|
||||
res = await code_execute(code=check_code, language="python")
|
||||
assert "HOME_EXISTS: False" in res
|
||||
assert "ENV_EXISTS: False" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sandbox_file_write_and_read():
|
||||
await sandbox_reset()
|
||||
write_res = await sandbox_file_write("sample.txt", "Привет из изолированной песочницы!")
|
||||
assert "успешно создан" in write_res
|
||||
|
||||
read_res = await sandbox_file_read("sample.txt")
|
||||
assert "Привет из изолированной песочницы!" in read_res
|
||||
|
||||
# Also test that Python script can read the written file
|
||||
py_code = """
|
||||
with open("sample.txt", "r", encoding="utf-8") as f:
|
||||
print("Content:", f.read())
|
||||
"""
|
||||
run_res = await code_execute(code=py_code, language="python")
|
||||
assert "Content: Привет из изолированной песочницы!" in run_res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sandbox_path_traversal_blocked():
|
||||
write_res = await sandbox_file_write("../../evil.sh", "echo evil")
|
||||
assert "Access denied" in write_res or "Ошибка" in write_res
|
||||
|
||||
read_res = await sandbox_file_read("../../.env")
|
||||
assert "Access denied" in read_res or "Ошибка" in read_res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sandbox_run_command():
|
||||
res = await sandbox_run_command("echo 'hello sandbox' | tr 'a-z' 'A-Z'")
|
||||
assert "HELLO SANDBOX" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sandbox_disabled():
|
||||
with patch("extensions.sandbox.tools.get_settings") as mock_settings:
|
||||
cfg = MagicMock()
|
||||
cfg.SANDBOX_ENABLED = False
|
||||
mock_settings.return_value = cfg
|
||||
|
||||
res = await code_execute("print(1)")
|
||||
assert "отключена в настройках" in res
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Unit tests for skills parser, renderer, and manager."""
|
||||
|
||||
from homeagent.skills.loader import Skill, parse_skill_file
|
||||
from homeagent.skills.manager import SkillManager
|
||||
|
||||
|
||||
def test_parse_skill_file(tmp_path):
|
||||
skill_file = tmp_path / "test_skill.md"
|
||||
content = """---
|
||||
name: test_action
|
||||
title: Тестовое Действие
|
||||
description: Описание тестового скилла
|
||||
triggers: ["/test", "тестовый триггер"]
|
||||
---
|
||||
Инструкция для модели на {date}.
|
||||
Вызови инструмент test_tool.
|
||||
"""
|
||||
skill_file.write_text(content, encoding="utf-8")
|
||||
|
||||
skill = parse_skill_file(skill_file)
|
||||
assert skill is not None
|
||||
assert skill.name == "test_action"
|
||||
assert skill.title == "Тестовое Действие"
|
||||
assert skill.description == "Описание тестового скилла"
|
||||
assert "/test" in skill.triggers
|
||||
assert "тестовый триггер" in skill.triggers
|
||||
|
||||
rendered = skill.render(extra_instructions="Только для проекта DEV")
|
||||
assert "Инструкция для модели на 20" in rendered # contains year
|
||||
assert "Только для проекта DEV" in rendered
|
||||
|
||||
|
||||
def test_skill_manager_triggers(tmp_path):
|
||||
skill_file = tmp_path / "morning.md"
|
||||
content = """---
|
||||
name: morning
|
||||
title: Утро
|
||||
triggers: ["/morning", "доброе утро"]
|
||||
---
|
||||
Сделай утренний план.
|
||||
"""
|
||||
skill_file.write_text(content, encoding="utf-8")
|
||||
|
||||
manager = SkillManager(tmp_path)
|
||||
assert len(manager.list_skills()) == 1
|
||||
|
||||
# Exact trigger match
|
||||
matched = manager.match_trigger("доброе утро")
|
||||
assert matched is not None
|
||||
assert matched[0].name == "morning"
|
||||
assert matched[1] == ""
|
||||
|
||||
# Command /skill <name> match
|
||||
matched_cmd = manager.match_trigger("/skill morning с фокусом на Jira")
|
||||
assert matched_cmd is not None
|
||||
assert matched_cmd[0].name == "morning"
|
||||
assert matched_cmd[1] == "с фокусом на Jira"
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Unit tests for SubagentRunner and parallel execution."""
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
from homeagent.agent.subagent import SubagentRunner
|
||||
from homeagent.config import Settings
|
||||
from homeagent.tools.registry import ToolRegistry
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_subagent_run_task_mocked():
|
||||
settings = Settings(
|
||||
LLM_PROVIDER="gemini",
|
||||
GEMINI_API_KEY="mock_key",
|
||||
GEMINI_SUBAGENT_MODEL="gemini-2.5-flash",
|
||||
)
|
||||
registry = ToolRegistry()
|
||||
|
||||
runner = SubagentRunner(settings=settings, registry=registry)
|
||||
|
||||
# Mock Gemini client
|
||||
mock_client = MagicMock()
|
||||
mock_resp = MagicMock()
|
||||
mock_resp.function_calls = None
|
||||
mock_resp.text = "Subtask completed successfully!"
|
||||
|
||||
mock_client.aio.models.generate_content = AsyncMock(return_value=mock_resp)
|
||||
runner._client = mock_client
|
||||
|
||||
result = await runner.run_task(task="Find urgent bugs in Jira", role="Jira Specialist")
|
||||
assert result == "Subtask completed successfully!"
|
||||
mock_client.aio.models.generate_content.assert_awaited_once()
|
||||
|
||||
# Verify model used was subagent model
|
||||
called_kwargs = mock_client.aio.models.generate_content.await_args.kwargs
|
||||
assert called_kwargs["model"] == "gemini-2.5-flash"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_subagent_run_parallel_mocked():
|
||||
settings = Settings(
|
||||
LLM_PROVIDER="gemini",
|
||||
GEMINI_API_KEY="mock_key",
|
||||
GEMINI_SUBAGENT_MODEL="gemini-2.5-flash",
|
||||
)
|
||||
registry = ToolRegistry()
|
||||
|
||||
runner = SubagentRunner(settings=settings, registry=registry)
|
||||
|
||||
# Mock runner.run_task directly for parallel test
|
||||
runner.run_task = AsyncMock(side_effect=["Calendar done: 2 events", "Jira done: 5 issues"])
|
||||
|
||||
tasks = [
|
||||
{"task": "Check calendar today", "role": "Calendar Specialist"},
|
||||
{"task": "Check Jira issues", "role": "Jira Specialist"},
|
||||
]
|
||||
|
||||
result = await runner.run_parallel(tasks)
|
||||
assert runner.run_task.await_count == 2
|
||||
assert "Calendar done: 2 events" in result
|
||||
assert "Jira done: 5 issues" in result
|
||||
assert "Результаты работы параллельных подагентов (2)" in result
|
||||
|
||||
|
||||
def test_subagent_tools_exclude_recursion():
|
||||
registry = ToolRegistry()
|
||||
runner = SubagentRunner(registry=registry)
|
||||
|
||||
tools_cfg = runner._get_subagent_tools_config()
|
||||
if tools_cfg:
|
||||
decl_names = [d.name for d in tools_cfg[0].function_declarations]
|
||||
assert "spawn_subagent" not in decl_names
|
||||
assert "spawn_parallel_subagents" not in decl_names
|
||||
# Regular tools should be present
|
||||
assert "remember_fact" in decl_names
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Unit tests for SubagentRunner with OpenAI/DeepSeek providers."""
|
||||
|
||||
import json
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
|
||||
from homeagent.agent.subagent import SubagentRunner
|
||||
from homeagent.config import Settings
|
||||
from homeagent.tools.base import tool
|
||||
from homeagent.tools.registry import ToolRegistry
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_subagent_run_task_openai_mocked():
|
||||
settings = Settings(
|
||||
LLM_PROVIDER="deepseek",
|
||||
DEEPSEEK_API_KEY="mock_key",
|
||||
DEEPSEEK_SUBAGENT_MODEL="deepseek-chat",
|
||||
)
|
||||
registry = ToolRegistry()
|
||||
|
||||
@tool(name="find_ticket", description="Find ticket in Jira")
|
||||
def find_ticket(key: str) -> str:
|
||||
return f"Ticket {key}: In Progress"
|
||||
|
||||
registry.register(find_ticket)
|
||||
runner = SubagentRunner(settings=settings, registry=registry)
|
||||
|
||||
# Mock tool call then final response
|
||||
mock_tool_call = MagicMock()
|
||||
mock_tool_call.id = "sub_call_1"
|
||||
mock_tool_call.function.name = "find_ticket"
|
||||
mock_tool_call.function.arguments = json.dumps({"key": "DEV-10"})
|
||||
|
||||
choice_1 = MagicMock()
|
||||
choice_1.message.content = "Looking up ticket..."
|
||||
choice_1.message.tool_calls = [mock_tool_call]
|
||||
resp_1 = MagicMock()
|
||||
resp_1.choices = [choice_1]
|
||||
|
||||
choice_2 = MagicMock()
|
||||
choice_2.message.content = "Subagent report: DEV-10 is In Progress."
|
||||
choice_2.message.tool_calls = None
|
||||
resp_2 = MagicMock()
|
||||
resp_2.choices = [choice_2]
|
||||
|
||||
mock_client = MagicMock()
|
||||
mock_client.chat.completions.create = AsyncMock(side_effect=[resp_1, resp_2])
|
||||
runner._openai_client = mock_client
|
||||
|
||||
result = await runner.run_task(task="Find ticket DEV-10", role="Ticket Finder")
|
||||
assert result == "Subagent report: DEV-10 is In Progress."
|
||||
assert mock_client.chat.completions.create.call_count == 2
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Unit tests for tool definition, schema generation, and registry."""
|
||||
|
||||
import pytest
|
||||
from homeagent.tools.base import _python_type_to_schema, tool
|
||||
from homeagent.tools.registry import ToolRegistry
|
||||
|
||||
|
||||
def test_type_to_schema_mapping():
|
||||
assert _python_type_to_schema(str) == {"type": "string"}
|
||||
assert _python_type_to_schema(int) == {"type": "integer"}
|
||||
assert _python_type_to_schema(float) == {"type": "number"}
|
||||
assert _python_type_to_schema(bool) == {"type": "boolean"}
|
||||
assert _python_type_to_schema(list[str]) == {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
}
|
||||
|
||||
|
||||
def test_tool_decorator_schema_and_execution():
|
||||
@tool(name="calculate_sum", description="Add two numbers")
|
||||
def calculate_sum(a: int, b: int = 10) -> int:
|
||||
"""Add two numbers.
|
||||
|
||||
Args:
|
||||
a: First number
|
||||
b: Second number
|
||||
"""
|
||||
return a + b
|
||||
|
||||
tool_def = getattr(calculate_sum, "__tool_definition__")
|
||||
assert tool_def.name == "calculate_sum"
|
||||
assert tool_def.description == "Add two numbers"
|
||||
assert not tool_def.is_async
|
||||
|
||||
schema = tool_def.parameters_schema
|
||||
assert schema["type"] == "object"
|
||||
assert "a" in schema["properties"]
|
||||
assert "b" in schema["properties"]
|
||||
assert schema["properties"]["a"]["type"] == "integer"
|
||||
assert schema["properties"]["a"]["description"] == "First number"
|
||||
assert schema["required"] == ["a"] # b has default
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_tool_execution():
|
||||
@tool(description="Async greeting")
|
||||
async def greet(name: str) -> str:
|
||||
"""Greet a user.
|
||||
|
||||
Args:
|
||||
name: User name
|
||||
"""
|
||||
return f"Hello, {name}!"
|
||||
|
||||
registry = ToolRegistry()
|
||||
registry.register(greet)
|
||||
|
||||
res = await registry.execute("greet", {"name": "Alice"})
|
||||
assert res == "Hello, Alice!"
|
||||
|
||||
# Gemini function declarations
|
||||
decls = registry.get_function_declarations()
|
||||
assert len(decls) == 1
|
||||
assert decls[0].name == "greet"
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Unit tests for Telegram formatting and message splitting."""
|
||||
|
||||
from homeagent.bot.utils import split_message
|
||||
|
||||
|
||||
def test_split_short_message():
|
||||
text = "Short message"
|
||||
assert split_message(text, max_length=100) == ["Short message"]
|
||||
|
||||
|
||||
def test_split_long_message_preserves_code_blocks():
|
||||
code = "```python\n" + "\n".join([f"x_{i} = {i}" for i in range(50)]) + "\n```"
|
||||
chunks = split_message(code, max_length=150)
|
||||
assert len(chunks) > 1
|
||||
|
||||
# First chunk should have closed code block
|
||||
assert chunks[0].strip().endswith("```")
|
||||
# Second chunk should have reopened code block
|
||||
assert chunks[1].strip().startswith("```python")
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Unit tests for Web Search and Web Fetch tools."""
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
import pytest
|
||||
|
||||
from extensions.web_search.client import WebSearchClient, _HTMLTextExtractor
|
||||
from extensions.web_search.tools import web_fetch_page, web_search
|
||||
|
||||
|
||||
def test_html_text_extractor():
|
||||
html_sample = """
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Test Page</title>
|
||||
<style>body { font-size: 14px; }</style>
|
||||
<script>console.log("ignore me");</script>
|
||||
</head>
|
||||
<body>
|
||||
<nav><a href="/">Home</a></nav>
|
||||
<header>Header content</header>
|
||||
<article>
|
||||
<h1>Заголовок статьи</h1>
|
||||
<p>Первый абзац с важным текстом.</p>
|
||||
<p>Второй абзац с деталями.</p>
|
||||
</article>
|
||||
<footer>Footer note</footer>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
parser = _HTMLTextExtractor()
|
||||
parser.feed(html_sample)
|
||||
extracted = parser.get_text()
|
||||
|
||||
assert "console.log" not in extracted
|
||||
assert "font-size" not in extracted
|
||||
assert "Заголовок статьи" in extracted
|
||||
assert "Первый абзац с важным текстом." in extracted
|
||||
assert "Второй абзац с деталями." in extracted
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_web_search_success():
|
||||
with patch("extensions.web_search.tools.get_search_client") as mock_get_client:
|
||||
mock_client = MagicMock()
|
||||
mock_client.search = AsyncMock(
|
||||
return_value=[
|
||||
{
|
||||
"title": "МФТИ Официальный сайт",
|
||||
"url": "https://mipt.ru",
|
||||
"snippet": "Ведущий технический университет России.",
|
||||
},
|
||||
{
|
||||
"title": "ФПМИ МФТИ",
|
||||
"url": "https://fpmi.mipt.ru",
|
||||
"snippet": "Физтех-школа прикладной математики и информатики.",
|
||||
},
|
||||
]
|
||||
)
|
||||
mock_get_client.return_value = mock_client
|
||||
|
||||
res = await web_search("МФТИ")
|
||||
assert "Результаты поиска по запросу «МФТИ» (2):" in res
|
||||
assert "[МФТИ Официальный сайт](https://mipt.ru)" in res
|
||||
assert "Ведущий технический университет" in res
|
||||
assert "[ФПМИ МФТИ](https://fpmi.mipt.ru)" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_web_search_empty():
|
||||
with patch("extensions.web_search.tools.get_search_client") as mock_get_client:
|
||||
mock_client = MagicMock()
|
||||
mock_client.search = AsyncMock(return_value=[])
|
||||
mock_get_client.return_value = mock_client
|
||||
|
||||
res = await web_search("abracadabraxyz123456789")
|
||||
assert "ничего не найдено" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_web_search_disabled():
|
||||
with patch("extensions.web_search.tools.get_settings") as mock_settings:
|
||||
cfg = MagicMock()
|
||||
cfg.WEB_SEARCH_ENABLED = False
|
||||
mock_settings.return_value = cfg
|
||||
|
||||
res = await web_search("python")
|
||||
assert "отключен в настройках" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_web_fetch_page_success():
|
||||
with patch("extensions.web_search.tools.get_search_client") as mock_get_client:
|
||||
mock_client = MagicMock()
|
||||
mock_client.fetch_page = AsyncMock(return_value="Документация по Python 3.12: основные возможности и синтаксис.")
|
||||
mock_get_client.return_value = mock_client
|
||||
|
||||
res = await web_fetch_page("https://docs.python.org/3/")
|
||||
assert "Содержимое страницы [https://docs.python.org/3/]:" in res
|
||||
assert "Документация по Python 3.12" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_web_fetch_page_invalid_url():
|
||||
res = await web_fetch_page("ftp://invalid-url.com")
|
||||
assert "некорректный URL" in res
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_client_search_duckduckgo_mocked():
|
||||
with patch("ddgs.DDGS") as mock_ddgs_cls:
|
||||
mock_instance = MagicMock()
|
||||
mock_instance.text.return_value = [
|
||||
{"title": "Result 1", "href": "https://example.com/1", "body": "Snippet 1"},
|
||||
{"title": "Result 2", "href": "https://example.com/2", "body": "Snippet 2"},
|
||||
]
|
||||
mock_ddgs_cls.return_value = mock_instance
|
||||
|
||||
client = WebSearchClient()
|
||||
client.settings.WEB_SEARCH_PROVIDER = "duckduckgo"
|
||||
results = await client.search("test query", max_results=2)
|
||||
|
||||
assert len(results) == 2
|
||||
assert results[0]["title"] == "Result 1"
|
||||
assert results[0]["url"] == "https://example.com/1"
|
||||
assert results[0]["snippet"] == "Snippet 1"
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Unit tests for Telegram WhitelistMiddleware."""
|
||||
|
||||
from datetime import datetime
|
||||
from unittest.mock import AsyncMock
|
||||
import pytest
|
||||
from aiogram.types import Chat, Message, User
|
||||
from homeagent.bot.middlewares import WhitelistMiddleware
|
||||
from homeagent.config import Settings
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_whitelist_allows_authorized_user():
|
||||
settings = Settings(ALLOWED_TELEGRAM_USER_IDS=[123456])
|
||||
middleware = WhitelistMiddleware(settings)
|
||||
|
||||
user = User(id=123456, is_bot=False, first_name="Owner")
|
||||
chat = Chat(id=123456, type="private")
|
||||
message = Message(message_id=1, date=datetime.now(), chat=chat, from_user=user)
|
||||
|
||||
handler = AsyncMock(return_value="handled")
|
||||
data = {"event_from_user": user}
|
||||
|
||||
result = await middleware(handler, message, data)
|
||||
assert result == "handled"
|
||||
handler.assert_awaited_once_with(message, data)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_whitelist_blocks_unauthorized_user():
|
||||
settings = Settings(ALLOWED_TELEGRAM_USER_IDS=[123456])
|
||||
middleware = WhitelistMiddleware(settings)
|
||||
|
||||
unauthorized_user = User(id=999999, is_bot=False, first_name="Stranger")
|
||||
chat = Chat(id=999999, type="private")
|
||||
message = Message(message_id=2, date=datetime.now(), chat=chat, from_user=unauthorized_user)
|
||||
|
||||
handler = AsyncMock()
|
||||
data = {"event_from_user": unauthorized_user}
|
||||
|
||||
result = await middleware(handler, message, data)
|
||||
assert result is None
|
||||
handler.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_whitelist_empty_blocks_all():
|
||||
settings = Settings(ALLOWED_TELEGRAM_USER_IDS=[])
|
||||
middleware = WhitelistMiddleware(settings)
|
||||
|
||||
user = User(id=123456, is_bot=False, first_name="Any")
|
||||
chat = Chat(id=123456, type="private")
|
||||
message = Message(message_id=3, date=datetime.now(), chat=chat, from_user=user)
|
||||
|
||||
handler = AsyncMock()
|
||||
data = {"event_from_user": user}
|
||||
|
||||
result = await middleware(handler, message, data)
|
||||
assert result is None
|
||||
handler.assert_not_awaited()
|
||||
Reference in new issue
Block a user