refactor
This commit is contained in:
163
tests/test_admin_improvements.py
Normal file
163
tests/test_admin_improvements.py
Normal file
@@ -0,0 +1,163 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Тест всех новых функций: пакетного добавления счетов и админских хэндлеров
|
||||
"""
|
||||
import asyncio
|
||||
import sys
|
||||
import os
|
||||
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from src.core.database import async_session_maker, engine
|
||||
from src.core.services import UserService, LotteryService, ParticipationService
|
||||
from src.utils.account_utils import validate_account_number, format_account_number, mask_account_number
|
||||
from src.display.winner_display import format_winner_display
|
||||
import random
|
||||
|
||||
async def test_comprehensive_features():
|
||||
print("🧪 Комплексное тестирование всех функций")
|
||||
print("="*60)
|
||||
|
||||
async with async_session_maker() as session:
|
||||
# 1. Создаем тестовых пользователей с номерами счетов
|
||||
print("\n1. 📝 Создание тестовых пользователей:")
|
||||
test_users = []
|
||||
test_accounts = []
|
||||
|
||||
for i in range(5):
|
||||
# Генерируем уникальные данные
|
||||
unique_id = random.randint(10000000, 99999999)
|
||||
account = f"{random.randint(10,99)}-{random.randint(10,99)}-{random.randint(10,99)}-{random.randint(10,99)}-{random.randint(10,99)}-{random.randint(10,99)}-{random.randint(10,99)}-{random.randint(10,99)}"
|
||||
|
||||
user = await UserService.get_or_create_user(
|
||||
session,
|
||||
telegram_id=unique_id,
|
||||
username=f'test_user_{i}_{unique_id}',
|
||||
first_name=f'Тестовый{i}',
|
||||
last_name=f'Пользователь{i}'
|
||||
)
|
||||
|
||||
# Устанавливаем номер счёта
|
||||
success = await UserService.set_account_number(session, user.telegram_id, account)
|
||||
if success:
|
||||
test_users.append(user)
|
||||
test_accounts.append(account)
|
||||
print(f"✅ Пользователь {i+1}: {user.first_name} ({account})")
|
||||
else:
|
||||
print(f"❌ Не удалось создать пользователя {i+1}")
|
||||
|
||||
# 2. Создаем тестовый розыгрыш
|
||||
print(f"\n2. 🎯 Создание тестового розыгрыша:")
|
||||
lottery = await LotteryService.create_lottery(
|
||||
session,
|
||||
title="Тест массовых операций",
|
||||
description="Розыгрыш для тестирования массовых операций",
|
||||
prizes=["Приз 1", "Приз 2"],
|
||||
creator_id=1
|
||||
)
|
||||
print(f"✅ Розыгрыш создан: {lottery.title}")
|
||||
|
||||
# 3. Тестируем массовое добавление по номерам счетов
|
||||
print(f"\n3. 🏦 Массовое добавление по номерам счетов:")
|
||||
accounts_to_add = test_accounts[:3] # Первые 3
|
||||
print(f"Добавляем {len(accounts_to_add)} счетов: {', '.join(accounts_to_add)}")
|
||||
|
||||
results = await ParticipationService.add_participants_by_accounts_bulk(
|
||||
session, lottery.id, accounts_to_add
|
||||
)
|
||||
|
||||
print(f"📊 Результат:")
|
||||
print(f" ✅ Добавлено: {results['added']}")
|
||||
print(f" ⚠️ Пропущено: {results['skipped']}")
|
||||
print(f" ❌ Ошибок: {len(results['errors'])}")
|
||||
|
||||
# 4. Проверяем участников
|
||||
print(f"\n4. 👥 Проверка участников:")
|
||||
participants = await ParticipationService.get_participants(session, lottery.id)
|
||||
print(f"Участников в розыгрыше: {len(participants)}")
|
||||
for participant in participants:
|
||||
print(f" • {participant.first_name} ({participant.account_number})")
|
||||
|
||||
# 5. Тестируем настройки отображения победителей
|
||||
print(f"\n5. 🎭 Тестирование настроек отображения:")
|
||||
for display_type in ["username", "chat_id", "account_number"]:
|
||||
await LotteryService.set_winner_display_type(session, lottery.id, display_type)
|
||||
lottery.winner_display_type = display_type # Обновляем локально
|
||||
|
||||
if participants:
|
||||
test_participant = participants[0]
|
||||
public_display = format_winner_display(test_participant, lottery, show_sensitive_data=False)
|
||||
admin_display = format_winner_display(test_participant, lottery, show_sensitive_data=True)
|
||||
|
||||
print(f" 📺 Тип {display_type}:")
|
||||
print(f" 👥 Публично: {public_display}")
|
||||
print(f" 🔧 Админ: {admin_display}")
|
||||
|
||||
# 6. Тестируем массовое удаление по счетам
|
||||
print(f"\n6. 🗑️ Массовое удаление по номерам счетов:")
|
||||
accounts_to_remove = test_accounts[:2] # Первые 2
|
||||
print(f"Удаляем {len(accounts_to_remove)} счетов")
|
||||
|
||||
results = await ParticipationService.remove_participants_by_accounts_bulk(
|
||||
session, lottery.id, accounts_to_remove
|
||||
)
|
||||
|
||||
print(f"📊 Результат:")
|
||||
print(f" ✅ Удалено: {results['removed']}")
|
||||
print(f" ⚠️ Не найдено: {results['not_found']}")
|
||||
print(f" ❌ Ошибок: {len(results['errors'])}")
|
||||
|
||||
# 7. Проверяем оставшихся участников
|
||||
print(f"\n7. 👥 Проверка оставшихся участников:")
|
||||
remaining_participants = await ParticipationService.get_participants(session, lottery.id)
|
||||
print(f"Участников осталось: {len(remaining_participants)}")
|
||||
for participant in remaining_participants:
|
||||
print(f" • {participant.first_name} ({participant.account_number})")
|
||||
|
||||
# 8. Тестируем методы управления розыгрышем
|
||||
print(f"\n8. ⚙️ Тестирование управления розыгрышем:")
|
||||
|
||||
# Деактивируем
|
||||
success = await LotteryService.set_lottery_active(session, lottery.id, False)
|
||||
print(f" 🔴 Деактивация: {'✅' if success else '❌'}")
|
||||
|
||||
# Активируем обратно
|
||||
success = await LotteryService.set_lottery_active(session, lottery.id, True)
|
||||
print(f" 🟢 Активация: {'✅' if success else '❌'}")
|
||||
|
||||
# Завершаем
|
||||
success = await LotteryService.complete_lottery(session, lottery.id)
|
||||
print(f" 🏁 Завершение: {'✅' if success else '❌'}")
|
||||
|
||||
# 9. Тестируем валидацию счетов с неправильными форматами
|
||||
print(f"\n9. 🔍 Тестирование валидации:")
|
||||
|
||||
invalid_accounts = [
|
||||
"invalid-account",
|
||||
"12345", # Слишком короткий
|
||||
"12-34-56-78", # Неполный
|
||||
"ab-cd-ef-gh-12-34-56-78", # С буквами
|
||||
"12-34-56-78-90-12-34-56-78" # Слишком длинный
|
||||
]
|
||||
|
||||
results = await ParticipationService.add_participants_by_accounts_bulk(
|
||||
session, lottery.id, invalid_accounts
|
||||
)
|
||||
|
||||
print(f"📊 Результат добавления невалидных счетов:")
|
||||
print(f" ✅ Добавлено: {results['added']}")
|
||||
print(f" 🚫 Неверных форматов: {len(results['invalid_accounts'])}")
|
||||
print(f" ❌ Ошибок: {len(results['errors'])}")
|
||||
|
||||
if results['invalid_accounts']:
|
||||
print(f" 🚫 Неверные форматы:")
|
||||
for invalid in results['invalid_accounts']:
|
||||
print(f" • {invalid}")
|
||||
|
||||
print(f"\n🎉 Все тесты завершены успешно!")
|
||||
print(f"✅ Массовое добавление и удаление по счетам работает")
|
||||
print(f"✅ Настройка отображения победителей работает")
|
||||
print(f"✅ Управление розыгрышами работает")
|
||||
print(f"✅ Валидация счетов работает")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(test_comprehensive_features())
|
||||
Reference in New Issue
Block a user