Files
chat/tests/test_emergency_fix.py
Andrey K. Choi 3050e084fa
All checks were successful
continuous-integration/drone/push Build is passing
main functions commit
2025-10-19 19:50:00 +09:00

102 lines
5.2 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
"""
🚨 ТЕСТ ИСПРАВЛЕНИЯ EMERGENCY ENDPOINTS
Проверяем работу мобильных endpoints после исправления SQLAlchemy
"""
import requests
import json
BASE_URL = "http://localhost:8002"
# Тестовый токен (временный для разработки)
TEST_TOKEN = "temp_token_123"
def test_emergency_endpoints():
"""Тестируем критические endpoints для мобильного приложения"""
print("🧪 ТЕСТИРОВАНИЕ ИСПРАВЛЕНИЯ EMERGENCY ENDPOINTS")
print("=" * 60)
headers = {"Authorization": f"Bearer {TEST_TOKEN}"}
# Список endpoints для проверки
endpoints = [
("GET", "/api/v1/emergency/events", "Получить все события"),
("GET", "/api/v1/emergency/events/nearby", "Ближайшие события"),
("GET", "/api/v1/emergency/events/my", "Мои события"),
("GET", "/api/v1/websocket/stats", "WebSocket статистика"),
("GET", "/health", "Проверка здоровья"),
]
results = []
for method, endpoint, description in endpoints:
print(f"\n🔍 Тестируем: {method} {endpoint}")
print(f" 📝 {description}")
try:
if method == "GET":
if endpoint == "/health":
# Health endpoint не требует авторизации
response = requests.get(f"{BASE_URL}{endpoint}", timeout=5)
elif endpoint == "/api/v1/emergency/events/nearby":
# Добавляем параметры для nearby endpoint
params = {"latitude": 37.7749, "longitude": -122.4194, "radius": 1000}
response = requests.get(f"{BASE_URL}{endpoint}", headers=headers, params=params, timeout=5)
else:
response = requests.get(f"{BASE_URL}{endpoint}", headers=headers, timeout=5)
# Анализируем ответ
if response.status_code == 200:
print(f" ✅ 200 OK - Endpoint работает полностью!")
results.append(("", endpoint, "200 OK", "Работает"))
elif response.status_code == 401:
print(f" ⚠️ 401 Unauthorized - Endpoint существует, нужна авторизация")
results.append(("⚠️", endpoint, "401 Unauthorized", "Endpoint существует"))
elif response.status_code == 403:
print(f" ⚠️ 403 Forbidden - Endpoint работает, нужны права доступа")
results.append(("⚠️", endpoint, "403 Forbidden", "Endpoint работает"))
elif response.status_code == 404:
print(f" ❌ 404 Not Found - Endpoint НЕ существует")
results.append(("", endpoint, "404 Not Found", "НЕ существует"))
elif response.status_code == 500:
print(f" 🚨 500 Server Error - SQLAlchemy проблема НЕ исправлена")
results.append(("🚨", endpoint, "500 Server Error", "SQLAlchemy ошибка"))
else:
print(f" 🔸 {response.status_code} - Неожиданный код ответа")
results.append(("🔸", endpoint, f"{response.status_code}", "Неожиданный код"))
except requests.exceptions.ConnectionError:
print(f" 💀 CONNECTION ERROR - Сервис НЕ запущен на порту 8002")
results.append(("💀", endpoint, "CONNECTION ERROR", "Сервис не запущен"))
except Exception as e:
print(f" ⚡ ERROR: {str(e)}")
results.append(("", endpoint, "ERROR", str(e)))
# Итоговый отчет
print("\n" + "=" * 60)
print("📊 ИТОГОВЫЙ ОТЧЕТ")
print("=" * 60)
working_count = sum(1 for r in results if r[0] in ["", "⚠️"])
total_count = len(results)
print(f"✅ Работающие endpoints: {working_count}/{total_count}")
print()
print("📋 Детали:")
for status, endpoint, code, description in results:
print(f" {status} {code:<20} {endpoint}")
print()
print("🏆 РЕЗУЛЬТАТ ИСПРАВЛЕНИЯ:")
if any(r[2] == "500 Server Error" for r in results):
print("❌ SQLAlchemy проблема НЕ исправлена - все еще есть 500 ошибки")
else:
print("✅ SQLAlchemy проблема ИСПРАВЛЕНА - нет больше 500 ошибок!")
if any(r[2] == "404 Not Found" for r in results if "emergency" in r[1]):
print("❌ Мобильные endpoints НЕ работают - есть 404 ошибки")
else:
print("✅ Мобильные endpoints РАБОТАЮТ - нет 404 ошибок!")
if __name__ == "__main__":
test_emergency_endpoints()