This commit is contained in:
107
tests/add_admin_role.py
Normal file
107
tests/add_admin_role.py
Normal file
@@ -0,0 +1,107 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Добавление роли админа пользователю test_admin@discours.io
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
def add_admin_role():
|
||||
"""Добавляем роль админа пользователю test_admin@discours.io"""
|
||||
|
||||
# 1. Авторизуемся как системный админ (welcome@discours.io)
|
||||
print("🔐 Авторизуемся как системный админ...")
|
||||
login_response = requests.post(
|
||||
"http://localhost:8000/graphql",
|
||||
headers={"Content-Type": "application/json"},
|
||||
json={
|
||||
"query": """
|
||||
mutation Login($email: String!, $password: String!) {
|
||||
login(email: $email, password: $password) {
|
||||
success
|
||||
token
|
||||
author {
|
||||
id
|
||||
name
|
||||
email
|
||||
}
|
||||
error
|
||||
}
|
||||
}
|
||||
""",
|
||||
"variables": {"email": "welcome@discours.io", "password": "password123"},
|
||||
},
|
||||
)
|
||||
|
||||
login_data = login_response.json()
|
||||
print(f"📡 Ответ авторизации: {json.dumps(login_data, indent=2, ensure_ascii=False)}")
|
||||
|
||||
if not login_data.get("data", {}).get("login", {}).get("success"):
|
||||
print("❌ Ошибка авторизации системного админа")
|
||||
return
|
||||
|
||||
token = login_data["data"]["login"]["token"]
|
||||
admin_id = login_data["data"]["login"]["author"]["id"]
|
||||
print(f"✅ Авторизация успешна, системный админ ID: {admin_id}")
|
||||
|
||||
# 2. Добавляем роль админа пользователю test_admin@discours.io в системном сообществе
|
||||
print("🔧 Добавляем роль админа пользователю test_admin@discours.io...")
|
||||
add_role_response = requests.post(
|
||||
"http://localhost:8000/graphql",
|
||||
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
|
||||
json={
|
||||
"query": """
|
||||
mutation AddUserRole($community_id: Int!, $user_id: Int!, $role: String!) {
|
||||
add_user_role(community_id: $community_id, user_id: $user_id, role: $role) {
|
||||
success
|
||||
message
|
||||
error
|
||||
}
|
||||
}
|
||||
""",
|
||||
"variables": {
|
||||
"community_id": 1, # Системное сообщество
|
||||
"user_id": 2500, # test_admin@discours.io
|
||||
"role": "admin",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
add_role_data = add_role_response.json()
|
||||
print(f"📡 Ответ добавления роли: {json.dumps(add_role_data, indent=2, ensure_ascii=False)}")
|
||||
|
||||
if add_role_data.get("data", {}).get("add_user_role", {}).get("success"):
|
||||
print("✅ Роль админа успешно добавлена")
|
||||
|
||||
# 3. Проверяем, что роль добавилась
|
||||
print("🔍 Проверяем роли пользователя...")
|
||||
check_roles_response = requests.post(
|
||||
"http://localhost:8000/graphql",
|
||||
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
|
||||
json={
|
||||
"query": """
|
||||
query GetUserCommunityRoles($community_id: Int!, $user_id: Int!) {
|
||||
adminGetUserCommunityRoles(community_id: $community_id, user_id: $user_id) {
|
||||
roles
|
||||
user {
|
||||
id
|
||||
name
|
||||
email
|
||||
}
|
||||
}
|
||||
}
|
||||
""",
|
||||
"variables": {"community_id": 1, "user_id": 2500},
|
||||
},
|
||||
)
|
||||
|
||||
check_roles_data = check_roles_response.json()
|
||||
print(f"📡 Ответ проверки ролей: {json.dumps(check_roles_data, indent=2, ensure_ascii=False)}")
|
||||
else:
|
||||
print("❌ Ошибка добавления роли")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
add_admin_role()
|
||||
110
tests/add_admin_role_db.py
Normal file
110
tests/add_admin_role_db.py
Normal file
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Добавление роли админа пользователю test_admin@discours.io через базу данных
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from settings import DATABASE_URL
|
||||
|
||||
|
||||
def add_admin_role_db():
|
||||
"""Добавляем роль админа пользователю test_admin@discours.io через базу данных"""
|
||||
|
||||
print("🔧 Подключаемся к базе данных...")
|
||||
engine = create_engine(DATABASE_URL)
|
||||
|
||||
with engine.connect() as conn:
|
||||
# 1. Проверяем, что пользователь test_admin@discours.io существует
|
||||
print("🔍 Проверяем пользователя test_admin@discours.io...")
|
||||
result = conn.execute(text("SELECT id, name, email FROM author WHERE email = 'test_admin@discours.io'"))
|
||||
user = result.fetchone()
|
||||
|
||||
if not user:
|
||||
print("❌ Пользователь test_admin@discours.io не найден в базе данных")
|
||||
return
|
||||
|
||||
user_id = user[0]
|
||||
print(f"✅ Найден пользователь: {user[1]} (ID: {user_id}, email: {user[2]})")
|
||||
|
||||
# 2. Проверяем, что системное сообщество существует
|
||||
print("🔍 Проверяем системное сообщество...")
|
||||
result = conn.execute(text("SELECT id, name, slug FROM community WHERE id = 1"))
|
||||
community = result.fetchone()
|
||||
|
||||
if not community:
|
||||
print("❌ Системное сообщество (ID=1) не найдено в базе данных")
|
||||
return
|
||||
|
||||
print(f"✅ Найдено системное сообщество: {community[1]} (ID: {community[0]}, slug: {community[2]})")
|
||||
|
||||
# 3. Проверяем, есть ли уже роль у пользователя в системном сообществе
|
||||
print("🔍 Проверяем существующие роли...")
|
||||
result = conn.execute(
|
||||
text("""
|
||||
SELECT roles FROM community_author
|
||||
WHERE author_id = :user_id AND community_id = :community_id
|
||||
"""),
|
||||
{"user_id": user_id, "community_id": 1},
|
||||
)
|
||||
|
||||
existing_roles_row = result.fetchone()
|
||||
existing_roles = existing_roles_row[0].split(",") if existing_roles_row and existing_roles_row[0] else []
|
||||
print(f"📋 Существующие роли: {existing_roles}")
|
||||
|
||||
# 4. Добавляем роль admin, если её нет
|
||||
if "admin" not in existing_roles:
|
||||
print("👑 Добавляем роль admin...")
|
||||
if existing_roles_row:
|
||||
# Обновляем существующую запись
|
||||
new_roles = ",".join(existing_roles + ["admin"])
|
||||
conn.execute(
|
||||
text("""
|
||||
UPDATE community_author
|
||||
SET roles = :roles
|
||||
WHERE author_id = :user_id AND community_id = :community_id
|
||||
"""),
|
||||
{"roles": new_roles, "user_id": user_id, "community_id": 1},
|
||||
)
|
||||
else:
|
||||
# Создаем новую запись
|
||||
conn.execute(
|
||||
text("""
|
||||
INSERT INTO community_author (community_id, author_id, roles, joined_at)
|
||||
VALUES (:community_id, :user_id, :roles, :joined_at)
|
||||
"""),
|
||||
{"community_id": 1, "user_id": user_id, "roles": "admin", "joined_at": 0},
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
print("✅ Роль admin успешно добавлена")
|
||||
else:
|
||||
print("ℹ️ Роль admin уже существует")
|
||||
|
||||
# 5. Проверяем результат
|
||||
print("🔍 Проверяем результат...")
|
||||
result = conn.execute(
|
||||
text("""
|
||||
SELECT roles FROM community_author
|
||||
WHERE author_id = :user_id AND community_id = :community_id
|
||||
"""),
|
||||
{"user_id": user_id, "community_id": 1},
|
||||
)
|
||||
|
||||
final_roles_row = result.fetchone()
|
||||
final_roles = final_roles_row[0].split(",") if final_roles_row and final_roles_row[0] else []
|
||||
print(f"📋 Финальные роли: {final_roles}")
|
||||
|
||||
if "admin" in final_roles:
|
||||
print("🎉 Пользователь test_admin@discours.io теперь имеет роль admin в системном сообществе!")
|
||||
else:
|
||||
print("❌ Роль admin не была добавлена")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
add_admin_role_db()
|
||||
126
tests/check_communities.py
Normal file
126
tests/check_communities.py
Normal file
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Проверка существующих сообществ
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
def check_communities():
|
||||
"""Проверяем существующие сообщества"""
|
||||
|
||||
# 1. Авторизуемся как test_admin@discours.io
|
||||
print("🔐 Авторизуемся как test_admin@discours.io...")
|
||||
login_response = requests.post(
|
||||
"http://localhost:8000/graphql",
|
||||
headers={"Content-Type": "application/json"},
|
||||
json={
|
||||
"query": """
|
||||
mutation Login($email: String!, $password: String!) {
|
||||
login(email: $email, password: $password) {
|
||||
success
|
||||
token
|
||||
author {
|
||||
id
|
||||
name
|
||||
email
|
||||
}
|
||||
error
|
||||
}
|
||||
}
|
||||
""",
|
||||
"variables": {"email": "test_admin@discours.io", "password": "password123"},
|
||||
},
|
||||
)
|
||||
|
||||
login_data = login_response.json()
|
||||
if not login_data.get("data", {}).get("login", {}).get("success"):
|
||||
print("❌ Ошибка авторизации test_admin@discours.io")
|
||||
return
|
||||
|
||||
token = login_data["data"]["login"]["token"]
|
||||
user_id = login_data["data"]["login"]["author"]["id"]
|
||||
print(f"✅ Авторизация успешна, пользователь ID: {user_id}")
|
||||
|
||||
# 2. Получаем все сообщества
|
||||
print("🔍 Получаем все сообщества...")
|
||||
communities_response = requests.post(
|
||||
"http://localhost:8000/graphql",
|
||||
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
|
||||
json={
|
||||
"query": """
|
||||
query GetCommunities {
|
||||
get_communities_all {
|
||||
id
|
||||
name
|
||||
slug
|
||||
created_by {
|
||||
id
|
||||
name
|
||||
email
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
},
|
||||
)
|
||||
|
||||
communities_data = communities_response.json()
|
||||
print(f"📡 Ответ сообществ: {json.dumps(communities_data, indent=2, ensure_ascii=False)}")
|
||||
|
||||
# 3. Ищем сообщества, созданные test_admin@discours.io
|
||||
if communities_data.get("data", {}).get("get_communities_all"):
|
||||
communities = communities_data["data"]["get_communities_all"]
|
||||
print(f"\n📋 Найдено {len(communities)} сообществ:")
|
||||
|
||||
test_admin_communities = []
|
||||
for community in communities:
|
||||
creator = community.get("created_by", {})
|
||||
print(f" - {community['name']} (ID: {community['id']}, slug: {community['slug']})")
|
||||
print(f" Создатель: {creator.get('name', 'N/A')} (ID: {creator.get('id', 'N/A')})")
|
||||
|
||||
if creator.get("id") == user_id:
|
||||
test_admin_communities.append(community)
|
||||
print(" ✅ Это сообщество создано test_admin@discours.io")
|
||||
print()
|
||||
|
||||
if test_admin_communities:
|
||||
print(f"🎯 Найдено {len(test_admin_communities)} сообществ, созданных test_admin@discours.io:")
|
||||
for community in test_admin_communities:
|
||||
print(f" - {community['name']} (ID: {community['id']}, slug: {community['slug']})")
|
||||
else:
|
||||
print("❌ test_admin@discours.io не создал ни одного сообщества")
|
||||
|
||||
# 4. Проверяем права на удаление сообществ
|
||||
print("\n🔍 Проверяем права на удаление...")
|
||||
if communities_data.get("data", {}).get("get_communities_all"):
|
||||
communities = communities_data["data"]["get_communities_all"]
|
||||
if communities:
|
||||
test_community = communities[0] # Берем первое сообщество для теста
|
||||
print(f"🧪 Тестируем удаление сообщества: {test_community['name']} (slug: {test_community['slug']})")
|
||||
|
||||
delete_response = requests.post(
|
||||
"http://localhost:8000/graphql",
|
||||
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
|
||||
json={
|
||||
"query": """
|
||||
mutation DeleteCommunity($slug: String!) {
|
||||
delete_community(slug: $slug) {
|
||||
success
|
||||
message
|
||||
error
|
||||
}
|
||||
}
|
||||
""",
|
||||
"variables": {"slug": test_community["slug"]},
|
||||
},
|
||||
)
|
||||
|
||||
delete_data = delete_response.json()
|
||||
print(f"📡 Ответ удаления: {json.dumps(delete_data, indent=2, ensure_ascii=False)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
check_communities()
|
||||
88
tests/check_communities_table.py
Normal file
88
tests/check_communities_table.py
Normal file
@@ -0,0 +1,88 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Скрипт для проверки содержимого таблицы сообществ через браузер
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
|
||||
async def check_communities_table():
|
||||
async with async_playwright() as p:
|
||||
# Определяем headless режим из переменной окружения
|
||||
headless_mode = os.getenv("PLAYWRIGHT_HEADLESS", "false").lower() == "true"
|
||||
print(f"🔧 Headless режим: {headless_mode}")
|
||||
|
||||
browser = await p.chromium.launch(headless=headless_mode)
|
||||
page = await browser.new_page()
|
||||
|
||||
try:
|
||||
# В CI/CD фронтенд обслуживается бэкендом на порту 8000
|
||||
frontend_url = "http://localhost:3000"
|
||||
print(f"🌐 Открываем админ-панель на {frontend_url}...")
|
||||
await page.goto(frontend_url)
|
||||
await page.wait_for_load_state("networkidle")
|
||||
await page.wait_for_timeout(3000)
|
||||
|
||||
# Авторизуемся
|
||||
print("🔐 Авторизуемся...")
|
||||
await page.wait_for_selector('input[type="email"]', timeout=30000)
|
||||
await page.fill('input[type="email"]', "test_admin@discours.io")
|
||||
await page.fill('input[type="password"]', "password123")
|
||||
await page.click('button[type="submit"]')
|
||||
await page.wait_for_url(f"{frontend_url}/admin/**", timeout=10000)
|
||||
|
||||
# Переходим на страницу сообществ
|
||||
print("📋 Переходим на страницу сообществ...")
|
||||
await page.wait_for_selector('button:has-text("Сообщества")', timeout=30000)
|
||||
await page.click('button:has-text("Сообщества")')
|
||||
await page.wait_for_load_state("networkidle")
|
||||
|
||||
# Проверяем содержимое таблицы
|
||||
print("🔍 Проверяем содержимое таблицы...")
|
||||
await page.wait_for_selector("table", timeout=10000)
|
||||
await page.wait_for_selector("table tbody tr", timeout=10000)
|
||||
|
||||
# Получаем все строки таблицы
|
||||
communities = await page.evaluate("""
|
||||
() => {
|
||||
const rows = document.querySelectorAll('table tbody tr');
|
||||
return Array.from(rows).map(row => {
|
||||
const cells = row.querySelectorAll('td');
|
||||
return {
|
||||
id: cells[0]?.textContent?.trim(),
|
||||
name: cells[1]?.textContent?.trim(),
|
||||
slug: cells[2]?.textContent?.trim(),
|
||||
actions: cells[3]?.textContent?.trim()
|
||||
};
|
||||
});
|
||||
}
|
||||
""")
|
||||
|
||||
print(f"📊 Найдено {len(communities)} сообществ в таблице:")
|
||||
for i, community in enumerate(communities[:10]): # Показываем первые 10
|
||||
print(f" {i + 1}. ID: {community['id']}, Name: {community['name']}, Slug: {community['slug']}")
|
||||
|
||||
if len(communities) > 10:
|
||||
print(f" ... и еще {len(communities) - 10} сообществ")
|
||||
|
||||
# Ищем конкретное сообщество
|
||||
target_slug = "test-admin-community-test-26b67fa4"
|
||||
found = any(c["slug"] == target_slug for c in communities)
|
||||
print(f"\n🔍 Ищем сообщество '{target_slug}': {'✅ НАЙДЕНО' if found else '❌ НЕ НАЙДЕНО'}")
|
||||
|
||||
# Делаем скриншот
|
||||
await page.screenshot(path="test-results/communities_table_debug.png")
|
||||
print("📸 Скриншот сохранен в test-results/communities_table_debug.png")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Ошибка: {e}")
|
||||
await page.screenshot(path="test-results/error_debug.png")
|
||||
finally:
|
||||
await browser.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(check_communities_table())
|
||||
108
tests/check_user_roles.py
Normal file
108
tests/check_user_roles.py
Normal file
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Проверка ролей пользователя
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
def check_user_roles():
|
||||
"""Проверяем роли пользователя test_admin@discours.io"""
|
||||
|
||||
# 1. Авторизуемся
|
||||
print("🔐 Авторизуемся...")
|
||||
login_response = requests.post(
|
||||
"http://localhost:8000/graphql",
|
||||
headers={"Content-Type": "application/json"},
|
||||
json={
|
||||
"query": """
|
||||
mutation Login($email: String!, $password: String!) {
|
||||
login(email: $email, password: $password) {
|
||||
success
|
||||
token
|
||||
author {
|
||||
id
|
||||
name
|
||||
email
|
||||
}
|
||||
error
|
||||
}
|
||||
}
|
||||
""",
|
||||
"variables": {"email": "test_admin@discours.io", "password": "password123"},
|
||||
},
|
||||
)
|
||||
|
||||
login_data = login_response.json()
|
||||
print(f"📡 Ответ авторизации: {json.dumps(login_data, indent=2, ensure_ascii=False)}")
|
||||
|
||||
if not login_data.get("data", {}).get("login", {}).get("success"):
|
||||
print("❌ Ошибка авторизации")
|
||||
return
|
||||
|
||||
token = login_data["data"]["login"]["token"]
|
||||
user_id = login_data["data"]["login"]["author"]["id"]
|
||||
print(f"✅ Авторизация успешна, пользователь ID: {user_id}")
|
||||
|
||||
# 2. Проверяем, является ли пользователь админом
|
||||
print("🔍 Проверяем админские права...")
|
||||
admin_response = requests.post(
|
||||
"http://localhost:8000/graphql",
|
||||
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
|
||||
json={
|
||||
"query": """
|
||||
query CheckAdmin {
|
||||
isAdmin
|
||||
}
|
||||
"""
|
||||
},
|
||||
)
|
||||
|
||||
admin_data = admin_response.json()
|
||||
print(f"📡 Ответ админ-проверки: {json.dumps(admin_data, indent=2, ensure_ascii=False)}")
|
||||
|
||||
# 3. Проверяем роли пользователя
|
||||
print("🔍 Проверяем роли пользователя...")
|
||||
roles_response = requests.post(
|
||||
"http://localhost:8000/graphql",
|
||||
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
|
||||
json={
|
||||
"query": """
|
||||
query GetRoles {
|
||||
getRoles {
|
||||
id
|
||||
name
|
||||
}
|
||||
}
|
||||
"""
|
||||
},
|
||||
)
|
||||
|
||||
roles_data = roles_response.json()
|
||||
print(f"📡 Ответ ролей: {json.dumps(roles_data, indent=2, ensure_ascii=False)}")
|
||||
|
||||
# 4. Проверяем админские роли
|
||||
print("🔍 Проверяем админские роли...")
|
||||
admin_roles_response = requests.post(
|
||||
"http://localhost:8000/graphql",
|
||||
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
|
||||
json={
|
||||
"query": """
|
||||
query GetAdminRoles {
|
||||
adminGetRoles {
|
||||
id
|
||||
name
|
||||
}
|
||||
}
|
||||
"""
|
||||
},
|
||||
)
|
||||
|
||||
admin_roles_data = admin_roles_response.json()
|
||||
print(f"📡 Ответ админ-ролей: {json.dumps(admin_roles_data, indent=2, ensure_ascii=False)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
check_user_roles()
|
||||
100
tests/check_users.py
Normal file
100
tests/check_users.py
Normal file
@@ -0,0 +1,100 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Проверка пользователей в системе
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
def check_users():
|
||||
"""Проверяем пользователей в системе"""
|
||||
|
||||
# 1. Авторизуемся как test_admin@discours.io
|
||||
print("🔐 Авторизуемся как test_admin@discours.io...")
|
||||
login_response = requests.post(
|
||||
"http://localhost:8000/graphql",
|
||||
headers={"Content-Type": "application/json"},
|
||||
json={
|
||||
"query": """
|
||||
mutation Login($email: String!, $password: String!) {
|
||||
login(email: $email, password: $password) {
|
||||
success
|
||||
token
|
||||
author {
|
||||
id
|
||||
name
|
||||
email
|
||||
}
|
||||
error
|
||||
}
|
||||
}
|
||||
""",
|
||||
"variables": {"email": "test_admin@discours.io", "password": "password123"},
|
||||
},
|
||||
)
|
||||
|
||||
login_data = login_response.json()
|
||||
if not login_data.get("data", {}).get("login", {}).get("success"):
|
||||
print("❌ Ошибка авторизации test_admin@discours.io")
|
||||
return
|
||||
|
||||
token = login_data["data"]["login"]["token"]
|
||||
user_id = login_data["data"]["login"]["author"]["id"]
|
||||
print(f"✅ Авторизация успешна, пользователь ID: {user_id}")
|
||||
|
||||
# 2. Получаем список пользователей
|
||||
print("🔍 Получаем список пользователей...")
|
||||
users_response = requests.post(
|
||||
"http://localhost:8000/graphql",
|
||||
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
|
||||
json={
|
||||
"query": """
|
||||
query GetUsers {
|
||||
adminGetUsers {
|
||||
authors {
|
||||
id
|
||||
name
|
||||
email
|
||||
slug
|
||||
}
|
||||
total
|
||||
page
|
||||
perPage
|
||||
totalPages
|
||||
}
|
||||
}
|
||||
"""
|
||||
},
|
||||
)
|
||||
|
||||
users_data = users_response.json()
|
||||
print(f"📡 Ответ пользователей: {json.dumps(users_data, indent=2, ensure_ascii=False)}")
|
||||
|
||||
# 3. Ищем системных админов
|
||||
if users_data.get("data", {}).get("adminGetUsers", {}).get("authors"):
|
||||
users = users_data["data"]["adminGetUsers"]["authors"]
|
||||
total = users_data["data"]["adminGetUsers"]["total"]
|
||||
print(f"\n📋 Найдено {len(users)} пользователей (всего: {total}):")
|
||||
|
||||
system_admins = []
|
||||
for user in users:
|
||||
print(f" - {user['name']} (ID: {user['id']}, email: {user.get('email', 'N/A')})")
|
||||
|
||||
# Проверяем, является ли пользователь системным админом
|
||||
if user.get("email") in ["welcome@discours.io", "services@discours.io", "guests@discours.io"]:
|
||||
system_admins.append(user)
|
||||
print(" ✅ Системный админ")
|
||||
print()
|
||||
|
||||
if system_admins:
|
||||
print(f"🎯 Найдено {len(system_admins)} системных админов:")
|
||||
for admin in system_admins:
|
||||
print(f" - {admin['name']} (ID: {admin['id']}, email: {admin.get('email', 'N/A')})")
|
||||
else:
|
||||
print("❌ Системные админы не найдены")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
check_users()
|
||||
126
tests/create_community_db.py
Normal file
126
tests/create_community_db.py
Normal file
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Создание сообщества в базе данных напрямую для test_admin@discours.io
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
import time
|
||||
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from settings import DATABASE_URL
|
||||
|
||||
|
||||
def create_community_db():
|
||||
"""Создаем сообщество в базе данных напрямую для test_admin@discours.io"""
|
||||
|
||||
print("🔧 Подключаемся к базе данных...")
|
||||
engine = create_engine(DATABASE_URL)
|
||||
|
||||
with engine.connect() as conn:
|
||||
# 1. Проверяем, что пользователь test_admin@discours.io существует
|
||||
print("🔍 Проверяем пользователя test_admin@discours.io...")
|
||||
result = conn.execute(text("SELECT id, name, email FROM author WHERE email = 'test_admin@discours.io'"))
|
||||
user = result.fetchone()
|
||||
|
||||
if not user:
|
||||
print("❌ Пользователь test_admin@discours.io не найден в базе данных")
|
||||
return
|
||||
|
||||
user_id = user[0]
|
||||
print(f"✅ Найден пользователь: {user[1]} (ID: {user_id}, email: {user[2]})")
|
||||
|
||||
# 2. Создаем новое сообщество
|
||||
print("🏘️ Создаем новое сообщество...")
|
||||
community_name = "Test Admin Community E2E"
|
||||
community_slug = f"test-admin-community-e2e-{int(time.time())}"
|
||||
community_desc = "Сообщество для E2E тестирования удаления"
|
||||
|
||||
# Вставляем сообщество
|
||||
result = conn.execute(
|
||||
text("""
|
||||
INSERT INTO community (name, slug, desc, pic, created_by, created_at)
|
||||
VALUES (:name, :slug, :desc, :pic, :created_by, :created_at)
|
||||
"""),
|
||||
{
|
||||
"name": community_name,
|
||||
"slug": community_slug,
|
||||
"desc": community_desc,
|
||||
"pic": "", # Пустое поле для изображения
|
||||
"created_by": user_id,
|
||||
"created_at": int(time.time()),
|
||||
},
|
||||
)
|
||||
|
||||
# Получаем ID созданного сообщества
|
||||
community_id = conn.execute(text("SELECT last_insert_rowid()")).scalar()
|
||||
|
||||
conn.commit()
|
||||
print(f"✅ Сообщество создано: {community_name} (ID: {community_id}, slug: {community_slug})")
|
||||
|
||||
# 3. Добавляем создателя как админа сообщества
|
||||
print("👑 Добавляем создателя как админа сообщества...")
|
||||
conn.execute(
|
||||
text("""
|
||||
INSERT INTO community_author (community_id, author_id, roles, joined_at)
|
||||
VALUES (:community_id, :author_id, :roles, :joined_at)
|
||||
"""),
|
||||
{
|
||||
"community_id": community_id,
|
||||
"author_id": user_id,
|
||||
"roles": "admin,author,editor",
|
||||
"joined_at": int(time.time()),
|
||||
},
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
print("✅ Создатель добавлен как админ сообщества")
|
||||
|
||||
# 4. Проверяем результат
|
||||
print("🔍 Проверяем результат...")
|
||||
result = conn.execute(
|
||||
text("""
|
||||
SELECT c.id, c.name, c.slug, c.created_by, a.name as creator_name
|
||||
FROM community c
|
||||
JOIN author a ON c.created_by = a.id
|
||||
WHERE c.id = :community_id
|
||||
"""),
|
||||
{"community_id": community_id},
|
||||
)
|
||||
|
||||
community = result.fetchone()
|
||||
if community:
|
||||
print("✅ Сообщество в базе данных:")
|
||||
print(f" - ID: {community[0]}")
|
||||
print(f" - Название: {community[1]}")
|
||||
print(f" - Slug: {community[2]}")
|
||||
print(f" - Создатель ID: {community[3]}")
|
||||
print(f" - Создатель: {community[4]}")
|
||||
|
||||
# Проверяем роли
|
||||
result = conn.execute(
|
||||
text("""
|
||||
SELECT roles FROM community_author
|
||||
WHERE community_id = :community_id AND author_id = :author_id
|
||||
"""),
|
||||
{"community_id": community_id, "author_id": user_id},
|
||||
)
|
||||
|
||||
roles_row = result.fetchone()
|
||||
if roles_row:
|
||||
roles = roles_row[0].split(",") if roles_row[0] else []
|
||||
print(f"✅ Роли создателя в сообществе: {roles}")
|
||||
|
||||
print("\n🎉 Сообщество успешно создано!")
|
||||
print("📋 Для использования в E2E тесте:")
|
||||
print(f" - ID: {community_id}")
|
||||
print(f" - Slug: {community_slug}")
|
||||
print(f" - Название: {community_name}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
create_community_db()
|
||||
99
tests/create_community_for_test.py
Normal file
99
tests/create_community_for_test.py
Normal file
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Создание сообщества для test_admin@discours.io
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
def create_community():
|
||||
# 1. Авторизуемся
|
||||
print("🔐 Авторизуемся...")
|
||||
login_response = requests.post(
|
||||
"http://localhost:8000/graphql",
|
||||
json={
|
||||
"query": """
|
||||
mutation Login($email: String!, $password: String!) {
|
||||
login(email: $email, password: $password) {
|
||||
success
|
||||
token
|
||||
author {
|
||||
id
|
||||
email
|
||||
}
|
||||
error
|
||||
}
|
||||
}
|
||||
""",
|
||||
"variables": {"email": "test_admin@discours.io", "password": "password123"},
|
||||
},
|
||||
)
|
||||
|
||||
login_data = login_response.json()
|
||||
if not login_data.get("data", {}).get("login", {}).get("success"):
|
||||
print("❌ Авторизация не удалась")
|
||||
return
|
||||
|
||||
token = login_data["data"]["login"]["token"]
|
||||
user_id = login_data["data"]["login"]["author"]["id"]
|
||||
print(f"✅ Авторизация успешна, пользователь ID: {user_id}")
|
||||
|
||||
# 2. Создаем сообщество
|
||||
print("🏘️ Создаем сообщество...")
|
||||
create_response = requests.post(
|
||||
"http://localhost:8000/graphql",
|
||||
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
|
||||
json={
|
||||
"query": """
|
||||
mutation CreateCommunity($community_input: CommunityInput!) {
|
||||
create_community(community_input: $community_input) {
|
||||
success
|
||||
community {
|
||||
id
|
||||
name
|
||||
slug
|
||||
desc
|
||||
created_by {
|
||||
id
|
||||
name
|
||||
email
|
||||
}
|
||||
}
|
||||
error
|
||||
}
|
||||
}
|
||||
""",
|
||||
"variables": {
|
||||
"community_input": {
|
||||
"name": "Test Admin Community",
|
||||
"slug": "test-admin-community-e2e",
|
||||
"desc": "Сообщество для E2E тестирования удаления",
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
create_data = create_response.json()
|
||||
print(f"📡 Ответ создания: {json.dumps(create_data, indent=2)}")
|
||||
|
||||
if create_data.get("data", {}).get("create_community", {}).get("success"):
|
||||
community = create_data["data"]["create_community"]["community"]
|
||||
print("✅ Сообщество создано успешно!")
|
||||
print(f" ID: {community['id']}")
|
||||
print(f" Name: {community['name']}")
|
||||
print(f" Slug: {community['slug']}")
|
||||
print(f" Создатель: {community['created_by']}")
|
||||
|
||||
print("📝 Для E2E теста используйте:")
|
||||
print(f' test_community_name = "{community["name"]}"')
|
||||
print(f' test_community_slug = "{community["slug"]}"')
|
||||
else:
|
||||
print("❌ Создание сообщества не удалось")
|
||||
error = create_data.get("data", {}).get("create_community", {}).get("error")
|
||||
print(f"Ошибка: {error}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
create_community()
|
||||
78
tests/debug_context.py
Normal file
78
tests/debug_context.py
Normal file
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Отладочный скрипт для проверки содержимого GraphQL контекста
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
import requests
|
||||
|
||||
# GraphQL endpoint
|
||||
url = "http://localhost:8000/graphql"
|
||||
|
||||
# Сначала авторизуемся
|
||||
login_mutation = """
|
||||
mutation Login($email: String!, $password: String!) {
|
||||
login(email: $email, password: $password) {
|
||||
token
|
||||
author {
|
||||
id
|
||||
name
|
||||
email
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
login_variables = {"email": "test_admin@discours.io", "password": "password123"}
|
||||
|
||||
print("🔐 Авторизуемся...")
|
||||
response = requests.post(url, json={"query": login_mutation, "variables": login_variables})
|
||||
|
||||
if response.status_code != 200:
|
||||
print(f"❌ Ошибка авторизации: {response.status_code}")
|
||||
print(response.text)
|
||||
exit(1)
|
||||
|
||||
login_data = response.json()
|
||||
print(f"✅ Авторизация успешна: {json.dumps(login_data, indent=2)}")
|
||||
|
||||
if "errors" in login_data:
|
||||
print(f"❌ Ошибки в авторизации: {login_data['errors']}")
|
||||
exit(1)
|
||||
|
||||
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-admin-community-e2e-1754005730"}
|
||||
|
||||
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
||||
|
||||
print(f"\n🗑️ Пытаемся удалить сообщество {delete_variables['slug']}...")
|
||||
response = requests.post(url, json={"query": delete_mutation, "variables": delete_variables}, headers=headers)
|
||||
|
||||
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']}")
|
||||
else:
|
||||
print(f"✅ Результат: {data['data']['delete_community']}")
|
||||
else:
|
||||
print(f"❌ HTTP ошибка: {response.status_code}")
|
||||
Reference in New Issue
Block a user