logboard/test_api.py
Сергей Антропов 85757ca717 fix: добавлен CORS middleware и тестовые файлы для диагностики
- Добавлен CORSMiddleware в app.py для решения проблем с CORS
- Создан test_api.py для тестирования API endpoints
- Создан test_websocket.py для тестирования WebSocket соединений
- Создан test_browser.html для тестирования в браузере
- Все тесты показывают, что API и WebSocket работают корректно

Диагностика показала:
 API endpoints работают (health, auth, containers, logs)
 WebSocket соединения работают и передают логи
 Проблема может быть в браузере или localStorage

Для тестирования в браузере:
1. Откройте http://localhost:9001/test_browser.html
2. Выполните тесты по порядку
3. Проверьте консоль браузера на ошибки

Автор: Сергей Антропов
Сайт: https://devops.org.ru
2025-08-20 20:50:28 +03:00

108 lines
4.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
# -*- coding: utf-8 -*-
"""
Тестовый скрипт для проверки API LogBoard+
Автор: Сергей Антропов
Сайт: https://devops.org.ru
"""
import requests
import json
def test_api():
"""Тестирование API endpoints"""
base_url = "http://localhost:9001"
# 1. Проверяем health endpoint
print("🔍 Проверка health endpoint...")
try:
response = requests.get(f"{base_url}/healthz")
print(f" Health: {response.status_code} - {response.text}")
except Exception as e:
print(f" ❌ Ошибка health: {e}")
return
# 2. Проверяем API без токена
print("\n🔍 Проверка API без токена...")
try:
response = requests.get(f"{base_url}/api/containers/services")
print(f" API без токена: {response.status_code}")
if response.status_code == 401:
print(" ✅ Правильно - требует аутентификации")
else:
print(" ⚠️ Неожиданный статус")
except Exception as e:
print(f" ❌ Ошибка API без токена: {e}")
# 3. Вход в систему
print("\n🔐 Вход в систему...")
login_data = {"username": "admin", "password": "admin"}
try:
response = requests.post(f"{base_url}/api/auth/login", json=login_data)
if response.status_code != 200:
print(f" ❌ Ошибка входа: {response.status_code}")
return
token = response.json()["access_token"]
headers = {"Authorization": f"Bearer {token}"}
print(" ✅ Вход выполнен успешно")
except Exception as e:
print(f" ❌ Ошибка входа: {e}")
return
# 4. Проверяем API с токеном
print("\n🔍 Проверка API с токеном...")
try:
response = requests.get(f"{base_url}/api/containers/services", headers=headers)
print(f" API с токеном: {response.status_code}")
if response.status_code == 200:
containers = response.json()
print(f" ✅ Получено контейнеров: {len(containers)}")
# Показываем первые 3 контейнера
for i, container in enumerate(containers[:3]):
print(f" {i+1}. {container.get('name', 'N/A')} ({container.get('status', 'N/A')})")
else:
print(f" ❌ Ошибка API: {response.text}")
except Exception as e:
print(f" ❌ Ошибка API с токеном: {e}")
# 5. Проверяем WebSocket status
print("\n🔍 Проверка WebSocket status...")
try:
response = requests.get(f"{base_url}/api/websocket/status", headers=headers)
print(f" WebSocket status: {response.status_code}")
if response.status_code == 200:
status = response.json()
print(f" ✅ WebSocket статус: {status}")
else:
print(f" ❌ Ошибка WebSocket status: {response.text}")
except Exception as e:
print(f" ❌ Ошибка WebSocket status: {e}")
# 6. Проверяем логи для первого контейнера
try:
response = requests.get(f"{base_url}/api/containers/services", headers=headers)
if response.status_code == 200:
containers = response.json()
if containers:
first_container = containers[0]
container_id = first_container.get('id')
print(f"\n🔍 Проверка логов для контейнера {first_container.get('name')}...")
try:
response = requests.get(f"{base_url}/api/logs/{container_id}?tail=5", headers=headers)
print(f" Логи: {response.status_code}")
if response.status_code == 200:
logs = response.json()
print(f" ✅ Получено строк логов: {len(logs.get('logs', []))}")
else:
print(f" ❌ Ошибка логов: {response.text}")
except Exception as e:
print(f" ❌ Ошибка логов: {e}")
except Exception as e:
print(f" ❌ Ошибка получения контейнеров: {e}")
if __name__ == "__main__":
test_api()