Files
core/tests/test_delete_existing_community.py
Untone 4b88a8c449
Some checks failed
Deploy on push / deploy (push) Failing after 1m11s
ci-testing
2025-08-17 11:09:29 +03:00

121 lines
4.6 KiB
Python

#!/usr/bin/env python3
"""
Тестовый скрипт для проверки удаления существующего сообщества через API
"""
import json
import pytest
import requests
@pytest.mark.e2e
@pytest.mark.api
def test_delete_existing_community(api_base_url, auth_headers, test_user_credentials):
"""Тест удаления существующего сообщества через API"""
# Сначала авторизуемся
login_mutation = """
mutation Login($email: String!, $password: String!) {
login(email: $email, password: $password) {
token
author {
id
name
email
}
}
}
"""
login_variables = test_user_credentials
print("🔐 Авторизуемся...")
try:
response = requests.post(
api_base_url,
json={"query": login_mutation, "variables": login_variables},
headers=auth_headers(),
timeout=10
)
response.raise_for_status()
except requests.exceptions.RequestException as e:
pytest.skip(f"Сервер недоступен: {e}")
login_data = response.json()
print(f"✅ Авторизация успешна: {json.dumps(login_data, indent=2)}")
if "errors" in login_data:
print(f"❌ Ошибки в авторизации: {login_data['errors']}")
pytest.fail(f"Ошибки в авторизации: {login_data['errors']}")
if "data" not in login_data or "login" not in login_data["data"]:
print(f"❌ Неожиданная структура ответа: {login_data}")
pytest.fail(f"Неожиданная структура ответа: {login_data}")
token = login_data["data"]["login"]["token"]
author_id = login_data["data"]["login"]["author"]["id"]
print(f"🔑 Токен получен: {token[:50]}...")
print(f"👤 Author ID: {author_id}")
# Теперь попробуем удалить существующее сообщество
delete_mutation = """
mutation DeleteCommunity($slug: String!) {
delete_community(slug: $slug) {
success
error
}
}
"""
# Используем тестовое сообщество, которое мы создаем в других тестах
delete_variables = {"slug": "test-community"}
headers = auth_headers(token)
print(f"\n🗑️ Пытаемся удалить сообщество {delete_variables['slug']}...")
try:
response = requests.post(
api_base_url,
json={"query": delete_mutation, "variables": delete_variables},
headers=headers,
timeout=10
)
response.raise_for_status()
except requests.exceptions.RequestException as e:
pytest.fail(f"Ошибка HTTP запроса: {e}")
print(f"📊 Статус ответа: {response.status_code}")
print(f"📄 Ответ: {response.text}")
if response.status_code == 200:
data = response.json()
print(f"📋 JSON ответ: {json.dumps(data, indent=2)}")
if "errors" in data:
print(f"❌ GraphQL ошибки: {data['errors']}")
# Это может быть нормально - сообщество может не существовать
print("💡 Сообщество может не существовать, это нормально для тестов")
return
if "data" in data and "delete_community" in data["data"]:
result = data["data"]["delete_community"]
print(f"✅ Результат: {result}")
# Проверяем, что удаление прошло успешно или сообщество не найдено
if result.get("success"):
print("✅ Сообщество успешно удалено")
else:
print(f"⚠️ Сообщество не удалено: {result.get('error', 'Неизвестная ошибка')}")
# Это может быть нормально - сообщество может не существовать
else:
print(f"⚠️ Неожиданная структура ответа: {data}")
else:
print(f"❌ HTTP ошибка: {response.status_code}")
pytest.fail(f"HTTP ошибка: {response.status_code}")
if __name__ == "__main__":
# Для запуска как скрипт
pytest.main([__file__, "-v"])