Spaces:
Sleeping
Sleeping
| import requests | |
| import json | |
| from time import sleep | |
| BASE_URL = "http://localhost:8000" | |
| def print_response(title, response): | |
| """Красивый вывод ответа""" | |
| print(f"\n{'='*60}") | |
| print(f"🔹 {title}") | |
| print(f"{'='*60}") | |
| print(f"Status: {response.status_code}") | |
| try: | |
| print(json.dumps(response.json(), indent=2, ensure_ascii=False)) | |
| except: | |
| print(response.text) | |
| def test_api(): | |
| """Тестирование всех эндпоинтов API""" | |
| # 1. Проверка корневого эндпоинта | |
| print("\n🚀 НАЧАЛО ТЕСТИРОВАНИЯ API") | |
| response = requests.get(f"{BASE_URL}/") | |
| print_response("GET / - Корневой эндпоинт", response) | |
| # 2. Health check | |
| response = requests.get(f"{BASE_URL}/health") | |
| print_response("GET /health - Проверка здоровья", response) | |
| # 3. Регистрация нового пользователя | |
| user_data = { | |
| "username": "testuser", | |
| "email": "test@example.com", | |
| "password": "password123" | |
| } | |
| response = requests.post(f"{BASE_URL}/api/auth/register", json=user_data) | |
| print_response("POST /api/auth/register - Регистрация", response) | |
| # 4. Вход пользователя | |
| login_data = { | |
| "username": "testuser", | |
| "password": "password123" | |
| } | |
| response = requests.post( | |
| f"{BASE_URL}/api/auth/login", | |
| data=login_data, | |
| headers={"Content-Type": "application/x-www-form-urlencoded"} | |
| ) | |
| print_response("POST /api/auth/login - Вход пользователя", response) | |
| if response.status_code == 200: | |
| user_token = response.json()["access_token"] | |
| print(f"✅ Получен токен пользователя") | |
| else: | |
| print("❌ Не удалось получить токен") | |
| return | |
| # 5. Информация о текущем пользователе | |
| headers = {"Authorization": f"Bearer {user_token}"} | |
| response = requests.get(f"{BASE_URL}/api/auth/me", headers=headers) | |
| print_response("GET /api/auth/me - Текущий пользователь", response) | |
| # 6. Получение статистики игрока | |
| response = requests.get(f"{BASE_URL}/api/game/stats", headers=headers) | |
| print_response("GET /api/game/stats - Статистика игрока", response) | |
| # 7. Начало игровой сессии | |
| response = requests.post(f"{BASE_URL}/api/game/session/start", headers=headers) | |
| print_response("POST /api/game/session/start - Начало сессии", response) | |
| # 8. Расход энергии | |
| response = requests.post(f"{BASE_URL}/api/game/stats/consume-energy?amount=10", headers=headers) | |
| print_response("POST /api/game/stats/consume-energy - Расход энергии", response) | |
| # 9. Восстановление энергии | |
| response = requests.post(f"{BASE_URL}/api/game/stats/restore-energy?amount=5", headers=headers) | |
| print_response("POST /api/game/stats/restore-energy - Восстановление энергии", response) | |
| # 10. Расход сытости | |
| response = requests.post(f"{BASE_URL}/api/game/stats/consume-hunger?amount=15", headers=headers) | |
| print_response("POST /api/game/stats/consume-hunger - Расход сытости", response) | |
| # 11. Восстановление сытости (еда) | |
| response = requests.post(f"{BASE_URL}/api/game/stats/restore-hunger?amount=20", headers=headers) | |
| print_response("POST /api/game/stats/restore-hunger - Еда", response) | |
| # 12. Обновление статистики | |
| stats_update = { | |
| "experience": 50, | |
| "coins": 100, | |
| "rooms_visited": 5, | |
| "items_collected": 10, | |
| "enemies_defeated": 3 | |
| } | |
| response = requests.patch(f"{BASE_URL}/api/game/stats", json=stats_update, headers=headers) | |
| print_response("PATCH /api/game/stats - Обновление статистики", response) | |
| # 13. Логирование действия | |
| response = requests.post( | |
| f"{BASE_URL}/api/game/action/move?action_data=room_1_to_room_2", | |
| headers=headers | |
| ) | |
| print_response("POST /api/game/action/move - Логирование действия", response) | |
| # Подождем 2 секунды для сессии | |
| print("\n⏳ Ждем 2 секунды для статистики сессии...") | |
| sleep(2) | |
| # 14. Завершение сессии | |
| response = requests.post(f"{BASE_URL}/api/game/session/end", headers=headers) | |
| print_response("POST /api/game/session/end - Завершение сессии", response) | |
| # 15. История сессий | |
| response = requests.get(f"{BASE_URL}/api/game/sessions?limit=5", headers=headers) | |
| print_response("GET /api/game/sessions - История сессий", response) | |
| # ТЕСТИРОВАНИЕ АДМИНКИ | |
| print("\n" + "="*60) | |
| print("👨💼 ТЕСТИРОВАНИЕ АДМИН-ПАНЕЛИ") | |
| print("="*60) | |
| # 16. Вход администратора | |
| admin_login = { | |
| "username": "admin", | |
| "password": "admin123" | |
| } | |
| response = requests.post( | |
| f"{BASE_URL}/api/auth/login", | |
| data=admin_login, | |
| headers={"Content-Type": "application/x-www-form-urlencoded"} | |
| ) | |
| print_response("POST /api/auth/login - Вход администратора", response) | |
| if response.status_code == 200: | |
| admin_token = response.json()["access_token"] | |
| print(f"✅ Получен токен администратора") | |
| else: | |
| print("❌ Не удалось получить токен администратора") | |
| return | |
| admin_headers = {"Authorization": f"Bearer {admin_token}"} | |
| # 17. Общая статистика | |
| response = requests.get(f"{BASE_URL}/api/admin/stats/overview", headers=admin_headers) | |
| print_response("GET /api/admin/stats/overview - Общая статистика", response) | |
| # 18. Список пользователей | |
| response = requests.get(f"{BASE_URL}/api/admin/users", headers=admin_headers) | |
| print_response("GET /api/admin/users - Список пользователей", response) | |
| # 19. Топ игроков | |
| response = requests.get(f"{BASE_URL}/api/admin/stats/top-players?metric=level&limit=5", headers=admin_headers) | |
| print_response("GET /api/admin/stats/top-players - Топ по уровню", response) | |
| # 20. График сессий | |
| response = requests.get(f"{BASE_URL}/api/admin/stats/sessions-timeline?days=7", headers=admin_headers) | |
| print_response("GET /api/admin/stats/sessions-timeline - График сессий", response) | |
| # 21. Тепловая карта активности | |
| response = requests.get(f"{BASE_URL}/api/admin/stats/activity-heatmap", headers=admin_headers) | |
| print_response("GET /api/admin/stats/activity-heatmap - Тепловая карта", response) | |
| # 22. Удержание пользователей | |
| response = requests.get(f"{BASE_URL}/api/admin/stats/user-retention", headers=admin_headers) | |
| print_response("GET /api/admin/stats/user-retention - Удержание", response) | |
| # 23. Игровые метрики | |
| response = requests.get(f"{BASE_URL}/api/admin/stats/game-metrics", headers=admin_headers) | |
| print_response("GET /api/admin/stats/game-metrics - Игровые метрики", response) | |
| # 24. Последние действия | |
| response = requests.get(f"{BASE_URL}/api/admin/actions/recent?limit=10", headers=admin_headers) | |
| print_response("GET /api/admin/actions/recent - Последние действия", response) | |
| # Итоги | |
| print("\n" + "="*60) | |
| print("✅ ТЕСТИРОВАНИЕ ЗАВЕРШЕНО!") | |
| print("="*60) | |
| print("\n📊 Проверьте документацию API: http://localhost:8000/docs") | |
| print("📊 Альтернативная документация: http://localhost:8000/redoc") | |
| if __name__ == "__main__": | |
| try: | |
| test_api() | |
| except requests.exceptions.ConnectionError: | |
| print("\n❌ Ошибка: Не удалось подключиться к серверу") | |
| print("Убедитесь, что сервер запущен на http://localhost:8000") | |
| except Exception as e: | |
| print(f"\n❌ Ошибка: {e}") | |