e2e-improved
Some checks failed
Deploy on push / deploy (push) Failing after 7s

This commit is contained in:
2025-08-27 18:31:51 +03:00
parent e7cdcbc5dd
commit f3fc6c34ae
10 changed files with 170 additions and 88 deletions

View File

@@ -15,8 +15,8 @@ async def test_ensure_user_has_reader_role(db_session):
if not community:
community = Community(
id=1,
name="Test Community",
slug="test-community",
name="Auth Service Test Community",
slug="auth-service-test-community",
desc="Test community for auth tests",
created_at=int(asyncio.get_event_loop().time())
)

View File

@@ -832,6 +832,89 @@ def backend_server():
backend_process.wait()
@pytest.fixture(scope="session")
def frontend_server():
"""
🚀 Фикстура для автоматического запуска/остановки фронтенд сервера.
Запускает фронтенд только если он не запущен.
"""
frontend_process: Optional[subprocess.Popen] = None
frontend_running = False
# Проверяем, не запущен ли уже фронтенд
try:
response = requests.get("http://localhost:3000/", timeout=2)
if response.status_code == 200:
print("✅ Фронтенд сервер уже запущен")
frontend_running = True
else:
frontend_running = False
except:
frontend_running = False
if not frontend_running:
print("🔄 Запускаем фронтенд сервер для тестов...")
try:
# Проверяем наличие node_modules
node_modules_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "node_modules")
if not os.path.exists(node_modules_path):
print("📦 Устанавливаем зависимости фронтенда...")
subprocess.run(["npm", "install"], check=True,
cwd=os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Запускаем фронтенд сервер
env = os.environ.copy()
env["NODE_ENV"] = "development"
frontend_process = subprocess.Popen(
["npm", "run", "dev"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
env=env,
cwd=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
)
# Ждем запуска фронтенда
print("⏳ Ждем запуска фронтенда...")
for i in range(60): # Ждем максимум 60 секунд
try:
response = requests.get("http://localhost:3000/", timeout=2)
if response.status_code == 200:
print("✅ Фронтенд сервер запущен")
frontend_running = True
break
except:
pass
time.sleep(1)
else:
print("❌ Фронтенд сервер не запустился за 60 секунд")
if frontend_process:
frontend_process.terminate()
frontend_process.wait()
# Не падаем жестко, а возвращаем False
frontend_running = False
except Exception as e:
print(f"❌ Ошибка запуска фронтенда: {e}")
if frontend_process:
frontend_process.terminate()
frontend_process.wait()
# Не падаем жестко, а возвращаем False
frontend_running = False
yield frontend_running
# Cleanup: останавливаем фронтенд только если мы его запускали
if frontend_process:
print("🛑 Останавливаем фронтенд сервер...")
try:
frontend_process.terminate()
frontend_process.wait(timeout=10)
except subprocess.TimeoutExpired:
frontend_process.kill()
frontend_process.wait()
@pytest.fixture
def test_client(backend_server):
"""
@@ -1124,8 +1207,8 @@ def test_community(db_session, test_users):
# Создаем сообщество с ID 2, так как ID 1 уже занят основным сообществом
community = Community(
id=2, # Используем ID 2, чтобы не конфликтовать с основным сообществом
name="Test Community",
slug="test-community",
name="Test Community Fixture",
slug="test-community-fixture", # Уникальный slug для этой фикстуры
desc="A test community for testing purposes",
created_by=test_users[0].id, # Администратор создает сообщество
settings={

View File

@@ -26,8 +26,8 @@ def test_community(db_session, test_users):
"""Создает тестовое сообщество"""
community = Community(
id=100,
name="Test Community",
slug="test-community",
name="Auth Test Community",
slug="auth-test-community", # Уникальный slug для auth тестов
desc="Test community for auth tests",
created_by=test_users[0].id,
created_at=int(time.time())

View File

@@ -35,8 +35,8 @@ def test_community(db_session, test_users):
if not community:
community = Community(
id=1,
name="Test Community",
slug="test-community",
name="RBAC Test Community",
slug="rbac-test-community",
desc="Test community for RBAC tests",
created_by=test_users[0].id,
created_at=int(time.time())

View File

@@ -8,75 +8,47 @@ import requests
import pytest
@pytest.mark.skip_ci
def test_backend_health():
def test_backend_health(backend_server):
"""Проверяем здоровье бэкенда"""
max_retries = 10
for attempt in range(1, max_retries + 1):
try:
response = requests.get("http://localhost:8000/", timeout=10)
if response.status_code == 200:
print(f"✅ Бэкенд готов (попытка {attempt})")
return
except requests.exceptions.RequestException as e:
print(f"⚠️ Попытка {attempt}/{max_retries}: Бэкенд не готов - {e}")
if attempt < max_retries:
time.sleep(3)
else:
pytest.fail(f"Бэкенд не готов после {max_retries} попыток")
assert backend_server, "Бэкенд сервер должен быть запущен"
response = requests.get("http://localhost:8000/", timeout=10)
assert response.status_code == 200, f"Бэкенд вернул статус {response.status_code}"
print("✅ Бэкенд здоров")
@pytest.mark.skip_ci
def test_frontend_health():
def test_frontend_health(frontend_server):
"""Проверяем здоровье фронтенда"""
max_retries = 10
for attempt in range(1, max_retries + 1):
try:
response = requests.get("http://localhost:3000/", timeout=10)
if response.status_code == 200:
print(f"✅ Фронтенд готов (попытка {attempt})")
return
except requests.exceptions.RequestException as e:
print(f"⚠️ Попытка {attempt}/{max_retries}: Фронтенд не готов - {e}")
if attempt < max_retries:
time.sleep(3)
else:
# В CI фронтенд может быть не запущен, поэтому не падаем
pytest.skip("Фронтенд не запущен (ожидаемо в некоторых CI средах)")
if not frontend_server:
pytest.skip("Фронтенд сервер не удалось запустить (возможно отсутствует npm или зависимости)")
response = requests.get("http://localhost:3000/", timeout=10)
assert response.status_code == 200, f"Фронтенд вернул статус {response.status_code}"
print("✅ Фронтенд здоров")
@pytest.mark.skip_ci
def test_graphql_endpoint():
def test_graphql_endpoint(backend_server):
"""Проверяем доступность GraphQL endpoint"""
try:
response = requests.post(
"http://localhost:8000/graphql",
headers={"Content-Type": "application/json"},
json={"query": "{ __schema { types { name } } }"},
timeout=15
)
if response.status_code == 200:
print("GraphQL endpoint доступен")
return
else:
pytest.fail(f"GraphQL endpoint вернул статус {response.status_code}")
except requests.exceptions.RequestException as e:
pytest.fail(f"GraphQL endpoint недоступен: {e}")
assert backend_server, "Бэкенд сервер должен быть запущен"
response = requests.post(
"http://localhost:8000/graphql",
headers={"Content-Type": "application/json"},
json={"query": "{ __schema { types { name } } }"},
timeout=15
)
assert response.status_code == 200, f"GraphQL endpoint вернул статус {response.status_code}"
print("✅ GraphQL endpoint доступен")
@pytest.mark.skip_ci
def test_admin_panel_access():
def test_admin_panel_access(frontend_server):
"""Проверяем доступность админ-панели"""
try:
response = requests.get("http://localhost:3000/admin", timeout=15)
if response.status_code == 200:
print("✅ Админ-панель доступна")
return
else:
pytest.fail(f"Админ-панель вернула статус {response.status_code}")
except requests.exceptions.RequestException as e:
# В CI фронтенд может быть не запущен, поэтому не падаем
pytest.skip("Админ-панель недоступна (фронтенд не запущен)")
if not frontend_server:
pytest.skip("Фронтенд сервер не запущен - админ-панель недоступна")
response = requests.get("http://localhost:3000/admin", timeout=15)
assert response.status_code == 200, f"Админ-панель вернула статус {response.status_code}"
print("✅ Админ-панель доступна")
if __name__ == "__main__":