188 lines
8.0 KiB
Python
188 lines
8.0 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}")
|
||
|
||
# Проверяем, что авторизация прошла успешно
|
||
if not login_data["data"]["login"]["token"] or not login_data["data"]["login"]["author"]:
|
||
print("⚠️ Авторизация не прошла - токен или author отсутствуют")
|
||
print("🔄 Пробуем альтернативный способ авторизации...")
|
||
|
||
# Пробуем создать пользователя и войти
|
||
try:
|
||
create_user_mutation = """
|
||
mutation CreateUser($input: AuthorInput!) {
|
||
create_author(input: $input) {
|
||
success
|
||
author {
|
||
id
|
||
email
|
||
name
|
||
}
|
||
error
|
||
}
|
||
}
|
||
"""
|
||
|
||
create_user_variables = {
|
||
"input": {
|
||
"email": "test-user-delete@example.com",
|
||
"name": "Test User Delete",
|
||
"password": "testpass123"
|
||
}
|
||
}
|
||
|
||
create_response = requests.post(
|
||
api_base_url,
|
||
json={"query": create_user_mutation, "variables": create_user_variables},
|
||
headers=auth_headers(),
|
||
timeout=10
|
||
)
|
||
|
||
if create_response.status_code == 200:
|
||
create_data = create_response.json()
|
||
if create_data.get("data", {}).get("create_author", {}).get("success"):
|
||
print("✅ Пользователь создан, пробуем войти...")
|
||
# Теперь пробуем войти с новым пользователем
|
||
login_response = requests.post(
|
||
api_base_url,
|
||
json={"query": login_mutation, "variables": create_user_variables},
|
||
headers=auth_headers(),
|
||
timeout=10
|
||
)
|
||
|
||
if login_response.status_code == 200:
|
||
new_login_data = login_response.json()
|
||
if new_login_data.get("data", {}).get("login", {}).get("token"):
|
||
token = new_login_data["data"]["login"]["token"]
|
||
author_id = new_login_data["data"]["login"]["author"]["id"]
|
||
print(f"✅ Авторизация с новым пользователем успешна")
|
||
print(f"🔑 Токен получен: {token[:50]}...")
|
||
print(f"👤 Author ID: {author_id}")
|
||
else:
|
||
pytest.skip("Не удалось авторизоваться даже с новым пользователем")
|
||
else:
|
||
pytest.skip("Ошибка при входе с новым пользователем")
|
||
else:
|
||
pytest.skip("Не удалось создать тестового пользователя")
|
||
else:
|
||
pytest.skip("Ошибка при создании пользователя")
|
||
except Exception as e:
|
||
pytest.skip(f"Не удалось создать пользователя: {e}")
|
||
else:
|
||
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"])
|