Files
quiz_test/tests/test_quiz.py
Andrey K. Choi b0346e4bd7
Some checks reported errors
continuous-integration/drone/push Build encountered an error
cleaning root
2025-09-11 08:18:31 +09:00

219 lines
8.5 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.

#!/usr/bin/env python3
"""
Интерактивный тестер Quiz Bot
Позволяет протестировать логику бота без Telegram
"""
import asyncio
import random
import sys
from pathlib import Path
project_root = Path(__file__).parent.parent
sys.path.append(str(project_root))
from src.database.database import DatabaseManager
from config.config import config
class LocalQuizTester:
def __init__(self):
self.db = DatabaseManager(config.database_path)
self.user_id = 12345 # Тестовый ID пользователя
async def start_test(self):
"""Интерактивный тест викторины"""
print("🎮 Локальный тестер Quiz Bot")
print("=" * 50)
# Регистрируем тестового пользователя
await self.db.register_user(
user_id=self.user_id,
username="test_user",
first_name="Test",
last_name="User"
)
while True:
print("\n📋 Главное меню:")
print("1. 🎯 Гостевой режим (быстрая викторина)")
print("2. 📚 Режим тестирования (полный тест)")
print("3. 📊 Моя статистика")
print("4. ❌ Выход")
choice = input("\n👉 Ваш выбор (1-4): ").strip()
if choice == "1":
await self.guest_mode()
elif choice == "2":
await self.test_mode()
elif choice == "3":
await self.show_stats()
elif choice == "4":
print("👋 До свидания!")
break
else:
print("❌ Неверный выбор. Попробуйте снова.")
async def guest_mode(self):
"""Гостевой режим - быстрая викторина"""
print("\n🎯 Гостевой режим")
await self.choose_test("guest")
async def test_mode(self):
"""Режим полного тестирования"""
print("\n📚 Режим тестирования")
await self.choose_test("test")
async def choose_test(self, mode: str):
"""Выбор теста"""
tests = await self.db.get_tests_by_category("korean")
if not tests:
print("❌ Тесты не найдены!")
return
print(f"\n🇰🇷 Корейский язык - доступные уровни:")
for i, test in enumerate(tests, 1):
print(f"{i}. Уровень {test['level']} - {test['description']}")
print("0. 🔙 Назад")
try:
choice = int(input("\n👉 Выберите уровень: "))
if choice == 0:
return
elif 1 <= choice <= len(tests):
selected_test = tests[choice - 1]
await self.start_quiz(selected_test, mode)
else:
print("❌ Неверный выбор!")
except ValueError:
print("❌ Введите число!")
async def start_quiz(self, test: dict, mode: str):
"""Начало викторины"""
test_id = test['id']
# Определяем количество вопросов
if mode == "guest":
questions_count = 5
else:
questions_count = 10
# Получаем случайные вопросы
questions = await self.db.get_random_questions(test_id, questions_count)
if not questions:
print("❌ Вопросы для этого теста не найдены!")
return
# Начинаем сессию
await self.db.start_session(
user_id=self.user_id,
test_id=test_id,
questions=questions,
mode=mode
)
print(f"\n🎯 Начинаем тест: {test['name']}")
print(f"📊 Количество вопросов: {len(questions)}")
print(f"🎮 Режим: {'Гостевой' if mode == 'guest' else 'Тестирование'}")
print("-" * 50)
correct_count = 0
# Проходим по вопросам
for i, question in enumerate(questions, 1):
print(f"\n❓ Вопрос {i} из {len(questions)}:")
print(f"{question['question']}")
print()
print(f"1. {question['option1']}")
print(f"2. {question['option2']}")
print(f"3. {question['option3']}")
print(f"4. {question['option4']}")
# Получаем ответ пользователя
while True:
try:
user_answer = int(input("\n👉 Ваш ответ (1-4): "))
if 1 <= user_answer <= 4:
break
else:
print("❌ Введите число от 1 до 4!")
except ValueError:
print("❌ Введите число!")
# Проверяем ответ
correct_answer = question['correct_answer']
is_correct = user_answer == correct_answer
if is_correct:
print("✅ Правильно!")
correct_count += 1
else:
print(f"❌ Неправильно. Правильный ответ: {correct_answer}")
# Обновляем прогресс
await self.db.update_session_progress(self.user_id, i, correct_count)
# Пауза перед следующим вопросом
if i < len(questions):
input("\n⏵️ Нажмите Enter для следующего вопроса...")
# Подсчитываем результат
score = (correct_count / len(questions)) * 100
await self.db.finish_session(self.user_id, score)
# Показываем результат
print("\n" + "=" * 50)
print("🎉 Тест завершен!")
print(f"📊 Результат: {correct_count}/{len(questions)}")
print(f"📈 Точность: {score:.1f}%")
print(f"🏆 Оценка: {self.get_grade(score)}")
print("=" * 50)
input("\n⏵️ Нажмите Enter для возврата в меню...")
async def show_stats(self):
"""Показать статистику пользователя"""
stats = await self.db.get_user_stats(self.user_id)
print("\n📊 Ваша статистика:")
print("-" * 30)
if not stats or stats['total_questions'] == 0:
print("📈 У вас пока нет статистики.")
print("🎯 Пройдите первый тест!")
else:
accuracy = (stats['correct_answers'] / stats['total_questions']) * 100 if stats['total_questions'] > 0 else 0
print(f"Всего вопросов: {stats['total_questions']}")
print(f"✅ Правильных ответов: {stats['correct_answers']}")
print(f"📈 Точность: {accuracy:.1f}%")
print(f"🎯 Завершенных сессий: {stats['sessions_completed'] or 0}")
if stats['best_score']:
print(f"🏆 Лучший результат: {stats['best_score']:.1f}%")
if stats['average_score']:
print(f"📊 Средний балл: {stats['average_score']:.1f}%")
input("\n⏵️ Нажмите Enter для возврата в меню...")
def get_grade(self, score: float) -> str:
"""Получение оценки по проценту"""
if score >= 90:
return "Отлично! 🌟"
elif score >= 70:
return "Хорошо! 👍"
elif score >= 50:
return "Удовлетворительно 📚"
else:
return "Нужно подтянуть знания 📖"
async def main():
tester = LocalQuizTester()
await tester.start_test()
if __name__ == "__main__":
print("🚀 Запуск интерактивного тестера...")
asyncio.run(main())