v1.7.0: refactor max_bot to flat structure, add VCF+UserModel+NLP history context, portal pages and proxy fixes

- Refactored max_bot from nested packages to flat module structure
- Q2: Extended BotUser model (patronymic, email, org, address, vcf_raw, contact_hash, phone_verified, email_verified, last_interaction, total_conversations, total_tickets)
- Q2: VCF parser (FN, N, TEL, EMAIL, ORG, ADR), upsert on re-contact, NLP history context (_get_user_history_context -> YandexGPT)
- Q1: Broadcast preview modal with 10s confirmation timer
- Q3: CSS var(--white)->var(--bg-card), var(--text)->var(--text-primary)
- Q4: bot_settings showNotification(), editable max_bot_id
- Q5: Webhook secret passthrough via X-Max-Bot-Api-Secret
- Masking sensitive keys, dialog_cleared handler, migrate via _add_column_if_not_exists()
- Rate limit (asyncio.sleep 0.5 per 10), dead code removed, conv.intent context in contact.py
- Portal pages: bot_consent, bot_kb (edit), bot_settings, bot_test, bot_tickets, portal_settings
- Tests: 21/21 passing, added test_yandex_gpt.py, test_email_sender.py
- Deploy: deploy_full.sh, schema.sql, seed_knowledge_base.sql
This commit is contained in:
2026-05-29 02:30:30 +03:00
parent 493e0b37a1
commit 72b6879f4b
234 changed files with 26768 additions and 6240 deletions
Binary file not shown.
-78
View File
@@ -1,78 +0,0 @@
import os
os.environ["WEBHOOK_SECRET"] = "test-secret"
os.environ["DATABASE_URL"] = "sqlite+aiosqlite://"
os.environ["APP_ENV"] = "test"
import asyncio
from typing import AsyncGenerator
from unittest.mock import AsyncMock, MagicMock
import pytest
import pytest_asyncio
from httpx import ASGITransport, AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from app.config import Settings, get_settings
from app.database import get_db
from app.models.models import Base
get_settings.cache_clear()
from app.main import app # noqa: E402
@pytest.fixture(scope="session")
def event_loop():
loop = asyncio.new_event_loop()
yield loop
loop.close()
@pytest_asyncio.fixture(scope="session")
async def test_engine():
engine = create_async_engine("sqlite+aiosqlite://", echo=False)
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield engine
await engine.dispose()
@pytest_asyncio.fixture
async def test_session(test_engine) -> AsyncGenerator[AsyncSession, None]:
TestSession = async_sessionmaker(test_engine, expire_on_commit=False)
async with TestSession() as session:
yield session
@pytest_asyncio.fixture
async def client(test_session: AsyncSession) -> AsyncGenerator:
async def override_get_db() -> AsyncGenerator[AsyncSession, None]:
yield test_session
app.dependency_overrides[get_db] = override_get_db
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as ac:
yield ac
app.dependency_overrides.clear()
@pytest.fixture
def mock_max_api():
mock = AsyncMock()
mock.send_message = AsyncMock(return_value={"ok": True})
mock.send_message_with_keyboard = AsyncMock(return_value={"ok": True})
mock.send_file = AsyncMock(return_value={"ok": True})
mock.get_file_url = AsyncMock(return_value="https://example.com/file")
mock.send_contact_request = AsyncMock(return_value={"ok": True})
mock.answer_callback = AsyncMock(return_value={"ok": True})
mock.get_me = AsyncMock(return_value={"ok": True, "bot": "test"})
mock.subscribe_webhook = AsyncMock(return_value={"ok": True})
mock.verify_webhook_secret = MagicMock(return_value=True)
mock.verify_contact_hash = MagicMock(return_value=True)
return mock
@pytest.fixture
def bot():
return None
+57
View File
@@ -0,0 +1,57 @@
import pytest
import os
from unittest.mock import patch, MagicMock
from app.email_sender import EmailSender
@pytest.fixture
def sender():
return EmailSender()
def test_send_debug_mode(sender):
with patch("os.name", "nt"):
result = sender.send("test@test.com", "Test", "Body", "from@test.com")
assert result is True
log_path = os.path.join(os.path.dirname(__file__), "..", "logs", "emails.log")
if os.path.isfile(log_path):
with open(log_path, "r", encoding="utf-8") as f:
content = f.read()
assert "test@test.com" in content
assert "Test" in content
os.remove(log_path)
def test_send_linux_mode(sender):
mock_proc = MagicMock()
mock_proc.returncode = 0
with patch("os.name", "posix"), \
patch("subprocess.run", return_value=mock_proc):
result = sender.send("test@test.com", "Test", "Body", "from@test.com")
assert result is True
def test_send_with_default_from(sender):
with patch("app.email_sender.config_reader") as mock_config:
mock_config.get_mail_from.return_value = "no-reply@aegisone.ru"
result = sender.send("test@test.com", "Test", "Body")
assert result is True
def test_send_ticket_escalation(sender):
with patch.object(sender, "send", return_value=True) as mock_send:
result = sender.send_ticket_escalation(
to="support@aegisone.ru",
subject="Test",
user_info="ID: 123",
contact="+79990000000",
inquiry="Need help",
history="Client: Hello",
)
assert result is True
mock_send.assert_called_once()
args = mock_send.call_args[0]
assert "ID: 123" in args[2]
assert "Need help" in args[2]
-168
View File
@@ -1,168 +0,0 @@
from app.fsm import BotState, FSM, STATE_TRANSITIONS
class TestFSM:
def test_initial_state(self):
FSM.clear_all()
assert FSM.get_state(1) == BotState.IDLE
def test_set_and_get_state(self):
FSM.clear_all()
FSM.set_state(1, BotState.NAME_REQUEST)
assert FSM.get_state(1) == BotState.NAME_REQUEST
def test_reset(self):
FSM.clear_all()
FSM.set_state(1, BotState.NAME_REQUEST)
FSM.reset(1)
assert FSM.get_state(1) == BotState.IDLE
def test_valid_transition(self):
FSM.clear_all()
result = FSM.transition(1, "start")
assert result == BotState.NAME_REQUEST
def test_invalid_transition_returns_same(self):
FSM.clear_all()
# From IDLE, "unknown" should keep us at IDLE
result = FSM.transition(1, "unknown_event")
assert result == BotState.IDLE
def test_can_transition_true(self):
FSM.clear_all()
assert FSM.can_transition(1, "start") is True
def test_can_transition_false(self):
FSM.clear_all()
assert FSM.can_transition(1, "unknown_event") is False
def test_full_greeting_flow(self):
FSM.clear_all()
assert FSM.transition(1, "start") == BotState.NAME_REQUEST
assert FSM.transition(1, "name_provided") == BotState.CONSENT_REQUEST
assert FSM.transition(1, "consent_given") == BotState.CONTACT_REQUEST
assert FSM.transition(1, "contact_provided") == BotState.INQUIRY_REQUEST
assert FSM.transition(1, "inquiry_provided") == BotState.CATEGORY_SELECT
assert FSM.transition(1, "category_selected") == BotState.CONFIRMATION
assert FSM.transition(1, "done") == BotState.IDLE
def test_consent_refused_flow(self):
FSM.clear_all()
FSM.set_state(1, BotState.CONSENT_REQUEST)
assert FSM.transition(1, "consent_refused") == BotState.IDLE
def test_handoff_flow(self):
FSM.clear_all()
FSM.set_state(1, BotState.HANDOFF_REQUEST)
assert FSM.transition(1, "confirmed") == BotState.HANDOFF_CONFIRMATION
assert FSM.transition(1, "done") == BotState.IDLE
def test_handoff_cancel_to_menu(self):
FSM.clear_all()
FSM.set_state(1, BotState.HANDOFF_REQUEST)
assert FSM.transition(1, "cancel") == BotState.MAIN_MENU
def test_main_menu_new_inquiry(self):
FSM.clear_all()
FSM.set_state(1, BotState.MAIN_MENU)
assert FSM.transition(1, "new_inquiry") == BotState.NAME_REQUEST
def test_main_menu_features(self):
FSM.clear_all()
FSM.set_state(1, BotState.MAIN_MENU)
assert FSM.transition(1, "feature_risk_score") == BotState.FEATURE_RISK_SCORE
FSM.set_state(1, BotState.MAIN_MENU)
assert FSM.transition(1, "feature_sla_status") == BotState.FEATURE_SLA_STATUS
FSM.set_state(1, BotState.MAIN_MENU)
assert FSM.transition(1, "feature_photo_report") == BotState.FEATURE_PHOTO_REPORT
FSM.set_state(1, BotState.MAIN_MENU)
assert FSM.transition(1, "feature_appointment") == BotState.FEATURE_APPOINTMENT
FSM.set_state(1, BotState.MAIN_MENU)
assert FSM.transition(1, "feature_quality_rate") == BotState.FEATURE_QUALITY_RATE
FSM.set_state(1, BotState.MAIN_MENU)
assert FSM.transition(1, "feature_commercial") == BotState.FEATURE_COMMERCIAL
FSM.set_state(1, BotState.MAIN_MENU)
assert FSM.transition(1, "feature_my_objects") == BotState.FEATURE_MY_OBJECTS
FSM.set_state(1, BotState.MAIN_MENU)
assert FSM.transition(1, "sla_ticket_create") == BotState.SLA_TICKET_CREATE
def test_feature_done_returns_to_menu(self):
FSM.clear_all()
FSM.set_state(1, BotState.FEATURE_RISK_SCORE)
assert FSM.transition(1, "done") == BotState.MAIN_MENU
FSM.set_state(1, BotState.FEATURE_RISK_SCORE)
assert FSM.transition(1, "cancel") == BotState.MAIN_MENU
def test_out_of_hours_flow(self):
FSM.clear_all()
FSM.set_state(1, BotState.OUT_OF_HOURS)
assert FSM.transition(1, "leave_message") == BotState.INQUIRY_REQUEST
FSM.set_state(1, BotState.OUT_OF_HOURS)
assert FSM.transition(1, "callback") == BotState.NAME_REQUEST
FSM.set_state(1, BotState.OUT_OF_HOURS)
assert FSM.transition(1, "cancel") == BotState.IDLE
FSM.set_state(1, BotState.OUT_OF_HOURS)
assert FSM.transition(1, "main_menu") == BotState.MAIN_MENU
def test_category_select_flow(self):
FSM.clear_all()
FSM.set_state(1, BotState.CATEGORY_SELECT)
assert FSM.transition(1, "category_selected") == BotState.CONFIRMATION
FSM.set_state(1, BotState.CATEGORY_SELECT)
assert FSM.transition(1, "cancel") == BotState.IDLE
def test_kb_search_found(self):
FSM.clear_all()
FSM.set_state(1, BotState.KB_SEARCH)
assert FSM.transition(1, "found") == BotState.MAIN_MENU
FSM.set_state(1, BotState.KB_SEARCH)
assert FSM.transition(1, "not_found") == BotState.INQUIRY_REQUEST
def test_waiting_1c_response(self):
FSM.clear_all()
FSM.set_state(1, BotState.WAITING_1C_RESPONSE)
assert FSM.transition(1, "received") == BotState.MAIN_MENU
FSM.set_state(1, BotState.WAITING_1C_RESPONSE)
assert FSM.transition(1, "timeout") == BotState.IDLE
def test_rating_flow(self):
FSM.clear_all()
FSM.set_state(1, BotState.AWAITING_RATING)
assert FSM.transition(1, "rating_provided") == BotState.IDLE
def test_new_user_start_via_callback(self):
FSM.clear_all()
# Simulate callback: from MAIN_MENU, cancel goes to IDLE
FSM.set_state(1, BotState.MAIN_MENU)
assert FSM.transition(1, "cancel") == BotState.IDLE
def test_idle_handoff_event(self):
FSM.clear_all()
assert FSM.transition(1, "handoff") == BotState.HANDOFF_REQUEST
def test_edit_from_confirmation(self):
FSM.clear_all()
FSM.set_state(1, BotState.CONFIRMATION)
assert FSM.transition(1, "edit_name") == BotState.NAME_REQUEST
FSM.set_state(1, BotState.CONFIRMATION)
assert FSM.transition(1, "edit_contact") == BotState.CONTACT_REQUEST
FSM.set_state(1, BotState.CONFIRMATION)
assert FSM.transition(1, "edit_inquiry") == BotState.INQUIRY_REQUEST
def test_clear_all(self):
FSM.clear_all()
FSM.set_state(1, BotState.NAME_REQUEST)
FSM.set_state(2, BotState.CONSENT_REQUEST)
FSM.clear_all()
assert FSM.get_state(1) == BotState.IDLE
assert FSM.get_state(2) == BotState.IDLE
def test_all_states_have_transitions(self):
for state in BotState:
assert state in STATE_TRANSITIONS, f"{state} missing from STATE_TRANSITIONS"
def test_all_transitions_go_to_valid_states(self):
for state, events in STATE_TRANSITIONS.items():
for event, target in events.items():
assert target in BotState.__members__.values(), \
f"{state}.{event} -> {target} is not a valid BotState"
+132 -137
View File
@@ -1,179 +1,174 @@
import pytest
from unittest.mock import AsyncMock
from unittest.mock import AsyncMock, MagicMock, patch, ANY
from app.handlers.greeting import analyze_and_respond
from app.handlers.consent import handle_consent_response
from app.handlers.contact import handle_manual_contact
from app.handlers.inquiry import handle_inquiry
from app.handlers.handoff import handle_callback
from app.models import BotConversation, BotUser, BotTicket, BotKnowledgeBase
from app.fsm import BotState, FSM
from app.handlers.greeting import handle_start
from app.handlers.consent import handle_consent_request, handle_consent_given, handle_consent_refused
from app.handlers.main_menu import handle_main_menu
from app.settings_cache import SettingsCache
def make_mock_db():
db = AsyncMock()
result = MagicMock()
result.scalar_one_or_none.return_value = None
result.scalars.return_value.all.return_value = []
db.execute.return_value = result
return db
@pytest.mark.asyncio
async def test_handle_start_new_user(test_session, mock_max_api, bot):
FSM.clear_all()
user_data = {"user_id": 12345, "first_name": "Иван", "last_name": "Петров"}
async def test_consent_response_yes():
mock_max_api = MagicMock()
mock_max_api.send_message = AsyncMock()
await SettingsCache.refresh(test_session)
await handle_start(bot, user_data, test_session, mock_max_api)
with patch("app.handlers.consent.max_api", mock_max_api), \
patch("app.handlers.consent.async_session") as mock_session:
mock_max_api.send_message_with_keyboard.assert_called_once()
call_args = mock_max_api.send_message_with_keyboard.call_args
assert call_args[0][0] == 12345
assert FSM.get_state(12345) == BotState.IDLE
mock_db = make_mock_db()
mock_session.return_value.__aenter__.return_value = mock_db
mock_user = MagicMock(spec=BotUser)
mock_user.consent_given = False
mock_user.consent_date = None
mock_conv = MagicMock(spec=BotConversation)
mock_conv.id = 1
mock_result = MagicMock()
mock_result.scalar_one_or_none.side_effect = [mock_user, mock_conv]
mock_db.execute.return_value = mock_result
await handle_consent_response(12345, 1, "даю согласие")
assert mock_max_api.send_message.called
@pytest.mark.asyncio
async def test_handle_start_returning_user(test_session, mock_max_api, bot):
from app.conversation import get_or_create_user, create_conversation
FSM.clear_all()
user_data = {"user_id": 67890, "first_name": "Пётр"}
async def test_consent_response_no():
mock_max_api = MagicMock()
mock_max_api.send_message = AsyncMock()
user = await get_or_create_user(test_session, 67890, "Пётр")
await test_session.flush()
await create_conversation(test_session, user.id)
await test_session.flush()
with patch("app.handlers.consent.max_api", mock_max_api), \
patch("app.handlers.consent.async_session") as mock_session, \
patch("app.handlers.consent.config_reader") as mock_config:
await SettingsCache.refresh(test_session)
await handle_start(bot, user_data, test_session, mock_max_api)
mock_db = make_mock_db()
mock_session.return_value.__aenter__.return_value = mock_db
mock_max_api.send_message_with_keyboard.assert_called_once()
assert FSM.get_state(67890) == BotState.IDLE
mock_config.get_phones.return_value = [("+7 (861) 203-33-30", "+78612033330")]
mock_config.get_site_mail.return_value = "mail@aegisone.ru"
mock_conv = MagicMock(spec=BotConversation)
mock_conv.id = 1
mock_result = MagicMock()
mock_result.scalar_one_or_none.return_value = mock_conv
mock_db.execute.return_value = mock_result
await handle_consent_response(12345, 1, "нет")
assert mock_max_api.send_message.called
@pytest.mark.asyncio
async def test_handle_consent_request(test_session, mock_max_api, bot):
FSM.clear_all()
user_data = {"user_id": 111, "first_name": "Анна"}
async def test_manual_contact_valid_phone():
mock_max_api = MagicMock()
mock_max_api.send_message = AsyncMock()
await SettingsCache.refresh(test_session)
await handle_consent_request(bot, user_data, test_session, mock_max_api)
with patch("app.handlers.contact.max_api", mock_max_api), \
patch("app.handlers.contact.async_session") as mock_session, \
patch("app.handlers.contact.handle_contact_received",
new=AsyncMock()) as mock_received:
mock_max_api.send_message_with_keyboard.assert_called_once()
assert FSM.get_state(111) == BotState.CONSENT_REQUEST
mock_db = make_mock_db()
mock_session.return_value.__aenter__.return_value = mock_db
await handle_manual_contact(12345, 1, "+78612033330")
assert mock_received.called
@pytest.mark.asyncio
async def test_handle_consent_given(test_session, mock_max_api, bot):
from app.conversation import get_or_create_user
FSM.clear_all()
user_data = {"user_id": 222}
async def test_manual_contact_invalid():
mock_max_api = MagicMock()
mock_max_api.send_message = AsyncMock()
user = await get_or_create_user(test_session, 222)
await test_session.flush()
with patch("app.handlers.contact.max_api", mock_max_api), \
patch("app.handlers.contact.async_session") as mock_session:
await handle_consent_given(bot, user_data, test_session, mock_max_api)
mock_db = make_mock_db()
mock_session.return_value.__aenter__.return_value = mock_db
assert user.consent_given is True
mock_max_api.send_message_with_keyboard.assert_called_once()
assert FSM.get_state(222) == BotState.CONTACT_REQUEST
await handle_manual_contact(12345, 1, "просто текст")
assert mock_max_api.send_message.called
@pytest.mark.asyncio
async def test_handle_consent_refused(test_session, mock_max_api, bot):
from app.conversation import get_or_create_user
FSM.clear_all()
user_data = {"user_id": 333}
async def test_callback_consent_yes():
mock_max_api = MagicMock()
mock_max_api.send_message = AsyncMock()
user = await get_or_create_user(test_session, 333)
await test_session.flush()
with patch("app.handlers.handoff.max_api", mock_max_api), \
patch("app.handlers.consent.max_api", mock_max_api), \
patch("app.handlers.handoff.async_session") as mock_hoff_session, \
patch("app.handlers.consent.async_session") as mock_consent_session:
await SettingsCache.refresh(test_session)
await handle_consent_refused(bot, user_data, test_session, mock_max_api)
mock_db = make_mock_db()
mock_hoff_session.return_value.__aenter__.return_value = mock_db
mock_consent_session.return_value.__aenter__.return_value = mock_db
mock_max_api.send_message_with_keyboard.assert_called_once()
assert FSM.get_state(333) == BotState.IDLE
mock_conv = MagicMock(spec=BotConversation)
mock_conv.id = 1
mock_user = MagicMock(spec=BotUser)
mock_user.consent_given = False
mock_user.consent_date = None
mock_result = MagicMock()
mock_result.scalar_one_or_none.side_effect = [mock_conv, mock_user, mock_conv]
mock_db.execute.return_value = mock_result
await handle_callback(12345, "consent_yes", {})
assert mock_max_api.send_message.called
@pytest.mark.asyncio
async def test_handle_main_menu_new_inquiry_without_consent(test_session, mock_max_api, bot):
FSM.clear_all()
user_data = {"user_id": 444, "payload": "new_inquiry"}
async def test_inquiry_handling():
mock_max_api = MagicMock()
mock_max_api.send_message = AsyncMock()
await SettingsCache.refresh(test_session)
await handle_main_menu(bot, user_data, test_session, mock_max_api)
mock_email = MagicMock()
mock_email.send_ticket_escalation = MagicMock(return_value=True)
# Should go to consent request
mock_max_api.send_message_with_keyboard.assert_called_once()
with patch("app.handlers.inquiry.max_api", mock_max_api), \
patch("app.handlers.inquiry.email_sender", mock_email), \
patch("app.handlers.inquiry.async_session") as mock_session, \
patch("app.handlers.inquiry.settings_cache") as mock_cache:
mock_db = make_mock_db()
mock_session.return_value.__aenter__.return_value = mock_db
@pytest.mark.asyncio
async def test_handle_main_menu_cancel(test_session, mock_max_api, bot):
FSM.clear_all()
user_data = {"user_id": 555, "payload": "cancel"}
mock_conv = MagicMock(spec=BotConversation)
mock_conv.id = 1
mock_conv.intent = "ticket"
mock_conv.state = "awaiting_inquiry"
mock_conv.inquiry_text = None
await SettingsCache.refresh(test_session)
await handle_main_menu(bot, user_data, test_session, mock_max_api)
mock_user = MagicMock(spec=BotUser)
mock_user.id = 12345
mock_user.first_name = "Иван"
mock_user.phone = "+78612033330"
mock_max_api.send_message_with_keyboard.assert_called_once()
assert FSM.get_state(555) == BotState.IDLE
mock_conv_result = MagicMock()
mock_conv_result.scalar_one_or_none.return_value = mock_conv
mock_user_result = MagicMock()
mock_user_result.scalar_one_or_none.return_value = mock_user
mock_db.execute.side_effect = [
mock_conv_result, mock_user_result,
mock_conv_result,
MagicMock(), MagicMock(), MagicMock(),
]
@pytest.mark.asyncio
async def test_handle_main_menu_unknown_payload(test_session, mock_max_api, bot):
FSM.clear_all()
user_data = {"user_id": 666, "payload": "unknown_command"}
mock_cache.get = AsyncMock(side_effect=lambda k, d="": {
"support_email": "support@aegisone.ru",
"email_subject": "Test subject"
}.get(k, d))
await SettingsCache.refresh(test_session)
await handle_main_menu(bot, user_data, test_session, mock_max_api)
mock_max_api.send_message_with_keyboard.assert_called_once()
assert FSM.get_state(666) == BotState.IDLE
@pytest.mark.asyncio
async def test_handle_main_menu_handoff(test_session, mock_max_api, bot):
from app.conversation import get_or_create_user
from app.handlers.handoff import handle_handoff_request
FSM.clear_all()
user_data = {"user_id": 668, "payload": "handoff"}
await get_or_create_user(test_session, 668, "Тест")
await test_session.flush()
await SettingsCache.refresh(test_session)
# Call directly (goes to out_of_hours if after hours, or handoff template)
await handle_handoff_request(bot, user_data, test_session, mock_max_api)
# Either send_message (handoff) or send_message_with_keyboard (out_of_hours)
assert mock_max_api.send_message.called or mock_max_api.send_message_with_keyboard.called
@pytest.mark.asyncio
async def test_handle_out_of_hours(test_session, mock_max_api, bot):
from app.handlers.out_of_hours import handle_out_of_hours
FSM.clear_all()
user_data = {"user_id": 777}
await SettingsCache.refresh(test_session)
await handle_out_of_hours(bot, user_data, test_session, mock_max_api)
mock_max_api.send_message_with_keyboard.assert_called_once()
assert FSM.get_state(777) == BotState.OUT_OF_HOURS
@pytest.mark.asyncio
async def test_handle_out_of_hours_leave_message(test_session, mock_max_api, bot):
from app.handlers.out_of_hours import handle_out_of_hours_callback
FSM.clear_all()
user_data = {"user_id": 888, "text": "тестовое обращение"}
FSM.set_state(888, BotState.OUT_OF_HOURS)
await SettingsCache.refresh(test_session)
await handle_out_of_hours_callback(bot, user_data, test_session, mock_max_api, "leave_message")
# handle_inquiry completes the flow → ends at CONFIRMATION
assert FSM.get_state(888) == BotState.CONFIRMATION
@pytest.mark.asyncio
async def test_handle_out_of_hours_callback_request(test_session, mock_max_api, bot):
from app.handlers.out_of_hours import handle_out_of_hours_callback
FSM.clear_all()
user_data = {"user_id": 999}
FSM.set_state(999, BotState.OUT_OF_HOURS)
await SettingsCache.refresh(test_session)
await handle_out_of_hours_callback(bot, user_data, test_session, mock_max_api, "callback")
mock_max_api.send_message.assert_called_once()
assert FSM.get_state(999) == BotState.NAME_REQUEST
await handle_inquiry(12345, 1, "Нужна консультация")
assert mock_max_api.send_message.called
+34 -111
View File
@@ -1,134 +1,57 @@
from unittest.mock import AsyncMock, patch, MagicMock
import pytest
from app.max_api import MaxAPIClient
from unittest.mock import AsyncMock, MagicMock, patch
from app.max_api import MaxAPI
@pytest.fixture
def api():
return MaxAPIClient(token="test-token")
@pytest.mark.asyncio
async def test_send_message(api):
api._request = AsyncMock(return_value={"ok": True})
result = await api.send_message(user_id=123, text="Hello")
assert result == {"ok": True}
api._request.assert_called_once()
@pytest.mark.asyncio
async def test_send_message_with_chat_id(api):
api._request = AsyncMock(return_value={"ok": True})
result = await api.send_message(chat_id=456, text="Hello")
assert result == {"ok": True}
@pytest.mark.asyncio
async def test_send_message_with_keyboard(api):
api.send_message = AsyncMock(return_value={"ok": True})
buttons = [[{"type": "message", "text": "Test", "payload": "test"}]]
result = await api.send_message_with_keyboard(user_id=123, text="Menu", buttons=buttons)
assert result == {"ok": True}
api.send_message.assert_called_once()
_, kwargs = api.send_message.call_args
assert kwargs["user_id"] == 123
assert kwargs["text"] == "Menu"
assert len(kwargs["attachments"]) == 1
@pytest.mark.asyncio
async def test_get_me(api):
api._request = AsyncMock(return_value={"ok": True, "bot": "test"})
result = await api.get_me()
assert result["bot"] == "test"
return MaxAPI()
@pytest.mark.asyncio
async def test_subscribe_webhook(api):
api._request = AsyncMock(return_value={"ok": True})
result = await api.subscribe_webhook(url="https://example.com/webhook", secret="secret123")
assert result == {"ok": True}
mock_response = MagicMock()
mock_response.json.return_value = {"success": True}
with patch.object(api.client, "post", new=AsyncMock(return_value=mock_response)):
result = await api.subscribe_webhook()
assert result == {"success": True}
@pytest.mark.asyncio
async def test_answer_callback(api):
api._request = AsyncMock(return_value={"ok": True})
result = await api.answer_callback(callback_id="cb_123", text="Thanks")
assert result == {"ok": True}
async def test_send_message(api):
mock_response = MagicMock()
mock_response.json.return_value = {"ok": True}
with patch.object(api.client, "post", new=AsyncMock(return_value=mock_response)):
result = await api.send_message(12345, "test", format="markdown")
assert result == {"ok": True}
@pytest.mark.asyncio
async def test_send_file(api):
api.upload_file = AsyncMock(return_value={"file_id": "file_123"})
api._request = AsyncMock(return_value={"ok": True})
result = await api.send_file(user_id=123, file_path="/tmp/test.pdf", caption="Here")
assert result == {"ok": True}
async def test_send_message_with_keyboard(api):
mock_response = MagicMock()
mock_response.json.return_value = {"ok": True}
keyboard = [{"type": "inline_keyboard", "payload": {"buttons": [[{"type": "callback", "text": "OK", "payload": "test"}]]}}]
with patch.object(api.client, "post", new=AsyncMock(return_value=mock_response)):
result = await api.send_message(12345, "test", attachments=keyboard)
assert result == {"ok": True}
@pytest.mark.asyncio
async def test_get_file_url(api):
api._request = AsyncMock(return_value={"url": "https://example.com/file.pdf"})
result = await api.get_file_url("file_123")
assert result == "https://example.com/file.pdf"
async def test_answer_callback_with_notification(api):
mock_response = MagicMock()
mock_response.json.return_value = {"success": True}
with patch.object(api.client, "post", new=AsyncMock(return_value=mock_response)):
result = await api.answer_callback("cb_123", notification="OK")
assert result == {"success": True}
@pytest.mark.asyncio
async def test_send_contact_request(api):
api.send_message = AsyncMock(return_value={"ok": True})
result = await api.send_contact_request(user_id=123)
assert result == {"ok": True}
@pytest.mark.asyncio
async def test_edit_message(api):
api._request = AsyncMock(return_value={"ok": True})
result = await api.edit_message(message_id=1, text="Updated")
assert result == {"ok": True}
@pytest.mark.asyncio
async def test_get_subscriptions(api):
api._request = AsyncMock(return_value={"ok": True})
result = await api.get_subscriptions()
assert result == {"ok": True}
@pytest.mark.asyncio
async def test_unsubscribe_webhook(api):
api._request = AsyncMock(return_value={"ok": True})
result = await api.unsubscribe_webhook()
assert result == {"ok": True}
def test_verify_webhook_secret_valid(api):
assert api.verify_webhook_secret("secret123", "secret123") is True
def test_verify_webhook_secret_invalid(api):
assert api.verify_webhook_secret("wrong", "secret123") is False
def test_verify_webhook_secret_empty(api):
assert api.verify_webhook_secret("anything", "") is True
def test_verify_contact_hash(api):
result = api.verify_contact_hash("test vcf", "access_token", "some_hash")
assert result is False or result is True
def test_headers(api):
async def test_headers(api):
headers = api._headers()
assert headers["Authorization"] == "test-token"
assert "Authorization" in headers
assert "Content-Type" in headers
assert headers["Content-Type"] == "application/json"
@pytest.mark.asyncio
async def test_close(api):
session = AsyncMock()
session.closed = False
api._session = session
await api.close()
session.close.assert_awaited_once()
-183
View File
@@ -1,183 +0,0 @@
import json
import pytest
class TestWebhook:
@pytest.mark.asyncio
async def test_health_endpoint(self, client):
response = await client.get("/health")
assert response.status_code == 200
data = response.json()
assert data["status"] == "ok"
assert data["bot"] == "София"
@pytest.mark.asyncio
async def test_webhook_missing_secret(self, client):
payload = {"update_type": "bot_started", "user": {"user_id": 123}}
response = await client.post(
"/webhook",
content=json.dumps(payload),
headers={"Content-Type": "application/json"},
)
assert response.status_code == 403
@pytest.mark.asyncio
async def test_webhook_with_secret(self, client):
payload = {"update_type": "bot_started", "user": {"user_id": 12345}}
response = await client.post(
"/webhook",
content=json.dumps(payload),
headers={
"Content-Type": "application/json",
"X-Max-Bot-Api-Secret": "test-secret",
},
)
assert response.status_code == 200
data = response.json()
assert data["ok"] is True
@pytest.mark.asyncio
async def test_webhook_message_created(self, client):
payload = {
"update_type": "message_created",
"user": {"user_id": 99999, "first_name": "Тест"},
"message": {"body": {"text": "Привет"}},
}
response = await client.post(
"/webhook",
content=json.dumps(payload),
headers={
"Content-Type": "application/json",
"X-Max-Bot-Api-Secret": "test-secret",
},
)
assert response.status_code == 200
data = response.json()
assert data["ok"] is True
@pytest.mark.asyncio
async def test_webhook_invalid_json(self, client):
response = await client.post(
"/webhook",
content="not json",
headers={
"Content-Type": "application/json",
"X-Max-Bot-Api-Secret": "test-secret",
},
)
assert response.status_code == 200
data = response.json()
assert data["ok"] is False
@pytest.mark.asyncio
async def test_webhook_message_callback(self, client):
payload = {
"update_type": "message_callback",
"user": {"user_id": 88888},
"callback": {"payload": "cancel", "id": "cb_001"},
}
response = await client.post(
"/webhook",
content=json.dumps(payload),
headers={
"Content-Type": "application/json",
"X-Max-Bot-Api-Secret": "test-secret",
},
)
assert response.status_code == 200
data = response.json()
assert data["ok"] is True
class TestAPI:
@pytest.mark.asyncio
async def test_api_settings(self, client):
response = await client.get("/api/bot/settings")
assert response.status_code == 200
@pytest.mark.asyncio
async def test_api_features(self, client):
response = await client.get("/api/bot/features")
assert response.status_code == 200
data = response.json()
assert isinstance(data, list)
@pytest.mark.asyncio
async def test_api_categories(self, client):
response = await client.get("/api/bot/categories")
assert response.status_code == 200
@pytest.mark.asyncio
async def test_api_templates(self, client):
response = await client.get("/api/bot/templates")
assert response.status_code == 200
@pytest.mark.asyncio
async def test_api_users(self, client):
response = await client.get("/api/bot/users")
assert response.status_code == 200
data = response.json()
assert "total" in data
assert "users" in data
@pytest.mark.asyncio
async def test_api_conversations(self, client):
response = await client.get("/api/bot/conversations")
assert response.status_code == 200
data = response.json()
assert isinstance(data, list)
@pytest.mark.asyncio
async def test_api_analytics(self, client):
response = await client.get("/api/bot/analytics")
assert response.status_code == 200
data = response.json()
assert "total_users" in data
@pytest.mark.asyncio
async def test_api_test_run(self, client):
response = await client.post(
"/api/bot/test-run",
content=json.dumps({"scenario": "new_dialog", "messages": []}),
headers={"Content-Type": "application/json"},
)
assert response.status_code == 200
data = response.json()
assert data["scenario"] == "new_dialog"
@pytest.mark.asyncio
async def test_api_test_run_out_of_hours(self, client):
response = await client.post(
"/api/bot/test-run",
content=json.dumps({"scenario": "out_of_hours", "messages": []}),
headers={"Content-Type": "application/json"},
)
assert response.status_code == 200
data = response.json()
assert data["scenario"] == "out_of_hours"
# Should have at least a bot response and mention out_of_hours template
assert len(data.get("conversation", [])) >= 1
@pytest.mark.asyncio
async def test_api_broadcast_recipients(self, client):
response = await client.get("/api/bot/broadcast/recipients")
assert response.status_code == 200
data = response.json()
assert "total" in data
assert "users" in data
@pytest.mark.asyncio
async def test_api_broadcast_history(self, client):
response = await client.get("/api/bot/broadcast/history")
assert response.status_code == 200
data = response.json()
assert "total" in data
assert "broadcasts" in data
@pytest.mark.asyncio
async def test_api_kb(self, client):
response = await client.get("/api/bot/kb")
assert response.status_code == 200
data = response.json()
assert isinstance(data, list)
+59
View File
@@ -0,0 +1,59 @@
import pytest
from unittest.mock import AsyncMock, patch, MagicMock
from app.yandex_gpt import YandexGPT
@pytest.fixture
def gpt():
return YandexGPT()
@pytest.mark.asyncio
async def test_analyze_intent_question(gpt):
gpt._load_credentials = AsyncMock(return_value=True)
with patch("app.yandex_gpt.YandexGPT._request", new=AsyncMock(return_value="question")):
result = await gpt.analyze_intent("Что вы делаете?")
assert result == "question"
@pytest.mark.asyncio
async def test_analyze_intent_ticket(gpt):
gpt._load_credentials = AsyncMock(return_value=True)
with patch("app.yandex_gpt.YandexGPT._request", new=AsyncMock(return_value="ticket")):
result = await gpt.analyze_intent("Хочу заказать аудит")
assert result == "ticket"
@pytest.mark.asyncio
async def test_analyze_intent_unknown(gpt):
gpt._load_credentials = AsyncMock(return_value=True)
with patch("app.yandex_gpt.YandexGPT._request", new=AsyncMock(return_value=None)):
result = await gpt.analyze_intent("абырвалг")
assert result == "unknown"
@pytest.mark.asyncio
async def test_analyze_intent_unavailable(gpt):
gpt._load_credentials = AsyncMock(return_value=False)
result = await gpt.analyze_intent("Что вы делаете?")
assert result == "unknown"
@pytest.mark.asyncio
async def test_generate_answer(gpt):
gpt._load_credentials = AsyncMock(return_value=True)
with patch("app.yandex_gpt.YandexGPT._request", new=AsyncMock(return_value="Мы предоставляем услуги аудита...")):
result = await gpt.generate_answer("Какие услуги?", "контекст")
assert result is not None
assert "аудита" in result
@pytest.mark.asyncio
async def test_generate_answer_unavailable(gpt):
gpt._load_credentials = AsyncMock(return_value=False)
result = await gpt.generate_answer("Какие услуги?", "контекст")
assert result is None