tests: API tests

This commit is contained in:
Black_Raven committed 2026-03-22 17:04:05 +03:00
1 parent 90630d393f
commit 96a941be36
1 file changed
+180
+180
View File
@@ -0,0 +1,180 @@
import requests
import json
import sys
BASE_URL = "http://localhost:80/api"
def check_server():
"""Проверка доступности сервера"""
try:
response = requests.get("http://localhost:5000/health", timeout=5)
if response.status_code == 200:
print("✅ Сервер доступен")
return True
except requests.exceptions.ConnectionError:
print("❌ Ошибка: Сервер не запущен!")
print(" Запустите сначала: python app.py")
return False
except Exception as e:
print(f"❌ Ошибка: {e}")
return False
def test_get_categories():
"""Тест получения всех категорий"""
print("\n" + "="*50)
print("Тест 1: GET /api/categories")
print("="*50)
try:
response = requests.get(f"{BASE_URL}/categories")
print(f"Статус: {response.status_code}")
if response.status_code == 200:
categories = response.json()
print(f"✅ Найдено категорий: {len(categories)}")
if categories:
print(f"\nПервая категория:")
print(json.dumps(categories[0], indent=2, ensure_ascii=False))
else:
print(f"❌ Ошибка: {response.text}")
except requests.exceptions.RequestException as e:
print(f"❌ Ошибка запроса: {e}")
def test_get_products():
"""Тест получения товаров"""
print("\n" + "="*50)
print("Тест 2: GET /api/products")
print("="*50)
params = {
"categoryId": 2, # ID категории "Для внутренней канализации"
"page": 1,
"limit": 5
}
try:
response = requests.get(f"{BASE_URL}/products", params=params)
print(f"Статус: {response.status_code}")
print(f"Параметры: {params}")
if response.status_code == 200:
data = response.json()
print(f"✅ Всего товаров: {data['total']}")
print(f"✅ Страница: {data['page']}/{data.get('total_pages', 1)}")
print(f"✅ Показано: {len(data['items'])} товаров")
if data['items']:
print(f"\nПервый товар:")
print(json.dumps(data['items'][0], indent=2, ensure_ascii=False))
else:
print(f"❌ Ошибка: {response.text}")
except requests.exceptions.RequestException as e:
print(f"❌ Ошибка запроса: {e}")
def test_get_products_with_filters():
"""Тест получения товаров с фильтрами"""
print("\n" + "="*50)
print("Тест 3: GET /api/products с фильтрами")
print("="*50)
params = {
"categoryId": 2,
"color": "серый",
"page": 1,
"limit": 5
}
try:
response = requests.get(f"{BASE_URL}/products", params=params)
print(f"Статус: {response.status_code}")
print(f"Фильтры: color=серый")
if response.status_code == 200:
data = response.json()
print(f"✅ Найдено товаров с фильтром: {data['total']}")
else:
print(f"❌ Ошибка: {response.text}")
except requests.exceptions.RequestException as e:
print(f"❌ Ошибка запроса: {e}")
def test_get_product_by_id():
"""Тест получения товара по ID"""
print("\n" + "="*50)
print("Тест 4: GET /api/products/{id}")
print("="*50)
try:
# Сначала получим первый товар
params = {"categoryId": 2, "limit": 1}
response = requests.get(f"{BASE_URL}/products", params=params)
if response.status_code == 200:
data = response.json()
if data['items']:
product_id = data['items'][0]['id']
print(f"Тестируем получение товара с ID: {product_id}")
response = requests.get(f"{BASE_URL}/products/{product_id}")
print(f"Статус: {response.status_code}")
if response.status_code == 200:
product = response.json()
print(f"✅ Товар найден:")
print(json.dumps(product, indent=2, ensure_ascii=False))
else:
print(f"❌ Ошибка: {response.text}")
else:
print("⚠️ Нет товаров для тестирования")
else:
print("❌ Не удалось получить список товаров")
except requests.exceptions.RequestException as e:
print(f"❌ Ошибка запроса: {e}")
def test_invalid_category():
"""Тест на некорректный categoryId"""
print("\n" + "="*50)
print("Тест 5: Обработка ошибок")
print("="*50)
try:
response = requests.get(f"{BASE_URL}/products", params={"page": 1})
print(f"Запрос без categoryId")
print(f"Статус: {response.status_code}")
if response.status_code == 400:
data = response.json()
print(f"✅ Корректная ошибка: {data.get('error', 'Unknown error')}")
else:
print(f"⚠️ Неожиданный статус: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"❌ Ошибка запроса: {e}")
def main():
"""Главная функция"""
print("\n🚀 Начинаем тестирование API")
print("="*50)
# Проверяем доступность сервера
if not check_server():
print("\n💡 Совет: Запустите сервер командой: python app.py")
sys.exit(1)
# Запускаем тесты
test_get_categories()
test_get_products()
test_get_products_with_filters()
test_get_product_by_id()
test_invalid_category()
print("\n" + "="*50)
print("✅ Тестирование завершено")
print("="*50)
if __name__ == "__main__":
main()