Files
new_lottery_bot/test_basic_features.py
2025-11-12 20:57:36 +09:00

111 lines
4.4 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.

"""
Простой тест основной функциональности без многопоточности
"""
import asyncio
import sys
import os
# Добавляем путь к проекту
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from database import init_db, async_session_maker
from services import UserService, LotteryService
from account_utils import generate_account_number, validate_account_number, mask_account_number
from winner_display import format_winner_display, validate_display_type
async def test_basic_functionality():
"""Простой тест основной функциональности"""
print("🧪 Тестирование основной функциональности")
print("=" * 50)
# Инициализируем базу данных
await init_db()
async with async_session_maker() as session:
# 1. Тест создания пользователя с номером счёта
print("\n1. 👤 Создание пользователя с номером счёта:")
test_account = "12-34-56-78-90-12-34-56"
user = await UserService.get_or_create_user(
session,
telegram_id=999999999,
username='test_client',
first_name='Тестовый',
last_name='Клиент'
)
success = await UserService.set_account_number(
session, user.telegram_id, test_account
)
if success:
print(f"✅ Пользователь создан и счёт {test_account} установлен")
else:
print(f"❌ Ошибка установки номера счёта")
# 2. Тест валидации номеров
print("\n2. 📋 Тестирование валидации номеров:")
test_cases = [
("12-34-56-78-90-12-34-56", True),
("invalid-number", False),
("12345678901234567890", False)
]
for number, expected in test_cases:
result = validate_account_number(number)
status = "" if result == expected else ""
print(f"{status} '{number}' -> {result}")
# 3. Тест маскирования
print("\n3. 🎭 Тестирование маскирования:")
masked = mask_account_number(test_account, show_last_digits=4)
print(f"Полный номер: {test_account}")
print(f"Маскированный: {masked}")
# 4. Тест поиска по счёту
print("\n4. 🔍 Тестирование поиска по номеру счёта:")
found_user = await UserService.get_user_by_account(session, test_account)
if found_user:
print(f"✅ Пользователь найден по номеру счёта: {found_user.first_name}")
else:
print(f"❌ Пользователь не найден")
# 5. Тест отображения победителей
print("\n5. 🎨 Тестирование отображения победителей:")
# Создаём тестовый розыгрыш
lottery = await LotteryService.create_lottery(
session,
title="Тест отображения",
description="Тестовый розыгрыш",
prizes=["Приз 1"],
creator_id=1
)
display_types = ['username', 'chat_id', 'account_number']
for display_type in display_types:
await LotteryService.set_winner_display_type(
session, lottery.id, display_type
)
updated_lottery = await LotteryService.get_lottery(session, lottery.id)
if updated_lottery:
public = format_winner_display(user, updated_lottery, show_sensitive_data=False)
admin = format_winner_display(user, updated_lottery, show_sensitive_data=True)
print(f"\n📺 Тип: {display_type}")
print(f" 👥 Публично: {public}")
print(f" 🔧 Админ: {admin}")
print("\n🎉 Основные тесты завершены успешно!")
if __name__ == "__main__":
asyncio.run(test_basic_functionality())