File size: 8,582 Bytes
2f4298a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
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}")