This commit is contained in:
@@ -1,15 +1,20 @@
|
||||
"""
|
||||
Упрощенный E2E тест удаления сообщества без браузера.
|
||||
|
||||
Использует новые фикстуры для автоматического запуска сервера.
|
||||
"""
|
||||
|
||||
import json
|
||||
import time
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
|
||||
def test_e2e_community_delete_workflow():
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.api
|
||||
def test_e2e_community_delete_workflow(api_base_url, auth_headers, test_user_credentials):
|
||||
"""Упрощенный E2E тест удаления сообщества без браузера"""
|
||||
|
||||
url = "http://localhost:8000/graphql"
|
||||
headers = {"Content-Type": "application/json"}
|
||||
|
||||
print("🔐 E2E тест удаления сообщества...\n")
|
||||
|
||||
# 1. Авторизация
|
||||
@@ -28,23 +33,27 @@ def test_e2e_community_delete_workflow():
|
||||
}
|
||||
"""
|
||||
|
||||
variables = {"email": "test_admin@discours.io", "password": "password123"}
|
||||
|
||||
variables = test_user_credentials
|
||||
data = {"query": login_query, "variables": variables}
|
||||
|
||||
response = requests.post(url, headers=headers, json=data)
|
||||
result = response.json()
|
||||
try:
|
||||
response = requests.post(api_base_url, headers=auth_headers(), json=data, timeout=10)
|
||||
response.raise_for_status()
|
||||
result = response.json()
|
||||
except requests.exceptions.RequestException as e:
|
||||
pytest.fail(f"Ошибка HTTP запроса: {e}")
|
||||
except json.JSONDecodeError as e:
|
||||
pytest.fail(f"Ошибка парсинга JSON: {e}")
|
||||
|
||||
if not result.get("data", {}).get("login", {}).get("success"):
|
||||
print(f"❌ Авторизация не удалась: {result}")
|
||||
return False
|
||||
pytest.fail(f"Авторизация не удалась: {result}")
|
||||
|
||||
token = result["data"]["login"]["token"]
|
||||
print(f"✅ Авторизация успешна, токен: {token[:50]}...")
|
||||
|
||||
# 2. Получаем список сообществ
|
||||
print("\n2️⃣ Получаем список сообществ...")
|
||||
headers_with_auth = {"Content-Type": "application/json", "Authorization": f"Bearer {token}"}
|
||||
headers_with_auth = auth_headers(token)
|
||||
|
||||
communities_query = """
|
||||
query {
|
||||
@@ -57,8 +66,13 @@ def test_e2e_community_delete_workflow():
|
||||
"""
|
||||
|
||||
data = {"query": communities_query}
|
||||
response = requests.post(url, headers=headers_with_auth, json=data)
|
||||
result = response.json()
|
||||
|
||||
try:
|
||||
response = requests.post(api_base_url, headers=headers_with_auth, json=data, timeout=10)
|
||||
response.raise_for_status()
|
||||
result = response.json()
|
||||
except requests.exceptions.RequestException as e:
|
||||
pytest.fail(f"Ошибка HTTP запроса при получении сообществ: {e}")
|
||||
|
||||
communities = result.get("data", {}).get("get_communities_all", [])
|
||||
test_community = None
|
||||
@@ -69,8 +83,42 @@ def test_e2e_community_delete_workflow():
|
||||
break
|
||||
|
||||
if not test_community:
|
||||
print("❌ Сообщество Test Community не найдено")
|
||||
return False
|
||||
# Создаем тестовое сообщество если его нет
|
||||
print("📝 Создаем тестовое сообщество...")
|
||||
create_query = """
|
||||
mutation CreateCommunity($name: String!, $slug: String!, $desc: String!) {
|
||||
create_community(name: $name, slug: $slug, desc: $desc) {
|
||||
success
|
||||
community {
|
||||
id
|
||||
name
|
||||
slug
|
||||
}
|
||||
error
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
create_variables = {
|
||||
"name": "Test Community",
|
||||
"slug": "test-community",
|
||||
"desc": "Test community for E2E tests"
|
||||
}
|
||||
|
||||
create_data = {"query": create_query, "variables": create_variables}
|
||||
|
||||
try:
|
||||
response = requests.post(api_base_url, headers=headers_with_auth, json=create_data, timeout=10)
|
||||
response.raise_for_status()
|
||||
create_result = response.json()
|
||||
except requests.exceptions.RequestException as e:
|
||||
pytest.fail(f"Ошибка HTTP запроса при создании сообщества: {e}")
|
||||
|
||||
if not create_result.get("data", {}).get("create_community", {}).get("success"):
|
||||
pytest.fail(f"Ошибка создания сообщества: {create_result}")
|
||||
|
||||
test_community = create_result["data"]["create_community"]["community"]
|
||||
print(f"✅ Создано тестовое сообщество: {test_community['name']}")
|
||||
|
||||
print(
|
||||
f"✅ Найдено сообщество: {test_community['name']} (ID: {test_community['id']}, slug: {test_community['slug']})"
|
||||
@@ -91,15 +139,18 @@ def test_e2e_community_delete_workflow():
|
||||
variables = {"slug": test_community["slug"]}
|
||||
data = {"query": delete_query, "variables": variables}
|
||||
|
||||
response = requests.post(url, headers=headers_with_auth, json=data)
|
||||
result = response.json()
|
||||
try:
|
||||
response = requests.post(api_base_url, headers=headers_with_auth, json=data, timeout=10)
|
||||
response.raise_for_status()
|
||||
result = response.json()
|
||||
except requests.exceptions.RequestException as e:
|
||||
pytest.fail(f"Ошибка HTTP запроса при удалении сообщества: {e}")
|
||||
|
||||
print("Ответ сервера:")
|
||||
print(json.dumps(result, indent=2, ensure_ascii=False))
|
||||
|
||||
if not result.get("data", {}).get("delete_community", {}).get("success"):
|
||||
print("❌ Ошибка удаления сообщества")
|
||||
return False
|
||||
pytest.fail(f"Ошибка удаления сообщества: {result}")
|
||||
|
||||
print("✅ Сообщество успешно удалено!")
|
||||
|
||||
@@ -108,23 +159,40 @@ def test_e2e_community_delete_workflow():
|
||||
time.sleep(1) # Даем время на обновление БД
|
||||
|
||||
data = {"query": communities_query}
|
||||
response = requests.post(url, headers=headers_with_auth, json=data)
|
||||
result = response.json()
|
||||
|
||||
try:
|
||||
response = requests.post(api_base_url, headers=headers_with_auth, json=data, timeout=10)
|
||||
response.raise_for_status()
|
||||
result = response.json()
|
||||
except requests.exceptions.RequestException as e:
|
||||
pytest.fail(f"Ошибка HTTP запроса при проверке удаления: {e}")
|
||||
|
||||
communities_after = result.get("data", {}).get("get_communities_all", [])
|
||||
community_still_exists = any(c["slug"] == test_community["slug"] for c in communities_after)
|
||||
|
||||
if community_still_exists:
|
||||
print("❌ Сообщество все еще в списке")
|
||||
return False
|
||||
pytest.fail("Сообщество все еще в списке после удаления")
|
||||
|
||||
print("✅ Сообщество действительно удалено из списка")
|
||||
|
||||
print("\n🎉 E2E тест удаления сообщества прошел успешно!")
|
||||
return True
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.api
|
||||
def test_e2e_health_check(api_base_url):
|
||||
"""Простой тест проверки здоровья API"""
|
||||
|
||||
print("🏥 Проверяем здоровье API...")
|
||||
|
||||
try:
|
||||
response = requests.get(api_base_url.replace("/graphql", "/"), timeout=5)
|
||||
response.raise_for_status()
|
||||
print(f"✅ API отвечает, статус: {response.status_code}")
|
||||
except requests.exceptions.RequestException as e:
|
||||
pytest.fail(f"API недоступен: {e}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = test_e2e_community_delete_workflow()
|
||||
if not success:
|
||||
exit(1)
|
||||
# Для запуска из командной строки
|
||||
pytest.main([__file__, "-v"])
|
||||
|
||||
Reference in New Issue
Block a user