""" Упрощенный E2E тест удаления сообщества без браузера. Использует новые фикстуры для автоматического запуска сервера. """ import json import time import pytest import requests @pytest.mark.e2e @pytest.mark.api def test_e2e_community_delete_workflow(api_base_url, auth_headers, test_user_credentials): """Упрощенный E2E тест удаления сообщества без браузера""" print("🔐 E2E тест удаления сообщества...\n") # 1. Авторизация print("1️⃣ Авторизуемся...") login_query = """ mutation Login($email: String!, $password: String!) { login(email: $email, password: $password) { success token author { id email } error } } """ variables = test_user_credentials data = {"query": login_query, "variables": variables} 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"): pytest.fail(f"Авторизация не удалась: {result}") token = result["data"]["login"]["token"] print(f"✅ Авторизация успешна, токен: {token[:50]}...") # 2. Получаем список сообществ print("\n2️⃣ Получаем список сообществ...") headers_with_auth = auth_headers(token) communities_query = """ query { get_communities_all { id name slug } } """ data = {"query": communities_query} 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 for community in communities: if community["name"] == "Test Community": test_community = community break if not test_community: # Создаем тестовое сообщество если его нет 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']})" ) # 3. Удаляем сообщество print("\n3️⃣ Удаляем сообщество...") delete_query = """ mutation DeleteCommunity($slug: String!) { delete_community(slug: $slug) { success message error } } """ variables = {"slug": test_community["slug"]} data = {"query": delete_query, "variables": variables} 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"): pytest.fail(f"Ошибка удаления сообщества: {result}") print("✅ Сообщество успешно удалено!") # 4. Проверяем что сообщество удалено print("\n4️⃣ Проверяем что сообщество удалено...") time.sleep(1) # Даем время на обновление БД data = {"query": communities_query} 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: pytest.fail("Сообщество все еще в списке после удаления") print("✅ Сообщество действительно удалено из списка") print("\n🎉 E2E тест удаления сообщества прошел успешно!") @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__": # Для запуска из командной строки pytest.main([__file__, "-v"])