qa-and-rag-ai-assistant/tests/test_bot.py
2026-01-13 15:38:27 +03:00

113 lines
3.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
Test file for bot.py
To run the bot:
python bot.py
To test the bot functionality:
python -m pytest tests/test_bot.py -v
or
python tests/test_bot.py
"""
import pytest
import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
import sys
import os
# Add parent directory to path to import bot module
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from bot import cmd_start, fake_db
class TestBot:
"""Test cases for bot functionality"""
def setup_method(self):
"""Clear fake_db before each test"""
fake_db.clear()
@pytest.mark.asyncio
async def test_start_command_without_token(self):
"""Test /start command without token"""
# Create mock message
message = AsyncMock()
message.from_user.id = 12345
message.from_user.username = "test_user"
message.answer = AsyncMock()
# Create mock command object
command = MagicMock()
command.args = None
# Call the handler
await cmd_start(message, command)
# Verify the response
message.answer.assert_called_once_with(
"Пожалуйста, перейдите по ссылке с сайта для авторизации."
)
@pytest.mark.asyncio
async def test_start_command_with_valid_token(self):
"""Test /start command with valid token"""
# Setup: add token to fake_db
test_token = "test-token-123"
fake_db[test_token] = {"status": "pending"}
# Create mock message
message = AsyncMock()
message.from_user.id = 12345
message.from_user.username = "test_user"
message.answer = AsyncMock()
# Create mock command object
command = MagicMock()
command.args = test_token
# Call the handler
await cmd_start(message, command)
# Verify the response
message.answer.assert_called_once_with(
"Успешная авторизация! Вернитесь на сайт, вас должно автоматически авторизовать."
)
# Verify fake_db was updated
assert fake_db[test_token]["status"] == "success"
assert fake_db[test_token]["telegram_id"] == 12345
assert fake_db[test_token]["username"] == "test_user"
@pytest.mark.asyncio
async def test_start_command_with_invalid_token(self):
"""Test /start command with invalid token"""
# Create mock message
message = AsyncMock()
message.from_user.id = 12345
message.from_user.username = "test_user"
message.answer = AsyncMock()
# Create mock command object
command = MagicMock()
command.args = "invalid-token"
# Call the handler
await cmd_start(message, command)
# Verify the response
message.answer.assert_called_once_with(
"Ошибка: неверный или истекший токен."
)
# Verify fake_db was not updated
assert "invalid-token" not in fake_db
if __name__ == "__main__":
"""Run tests directly"""
print("Running bot tests...")
pytest.main([__file__, "-v"])