core/tests/test_drafts.py

124 lines
3.9 KiB
Python
Raw Normal View History

2025-02-09 19:26:50 +00:00
import pytest
2025-02-11 09:00:35 +00:00
2025-07-02 19:30:21 +00:00
from auth.orm import Author
from orm.community import CommunityAuthor
2025-02-11 09:00:35 +00:00
from orm.shout import Shout
from resolvers.draft import create_draft, load_drafts
def ensure_test_user_with_roles(db_session):
2025-07-02 19:30:21 +00:00
"""Создает тестового пользователя с ID 1 и назначает ему роли через CommunityAuthor"""
# Создаем пользователя с ID 1 если его нет
test_user = db_session.query(Author).filter(Author.id == 1).first()
if not test_user:
test_user = Author(id=1, email="test@example.com", name="Test User", slug="test-user")
test_user.set_password("password123")
db_session.add(test_user)
db_session.flush()
2025-07-02 19:30:21 +00:00
# Удаляем старые роли
existing_community_author = (
db_session.query(CommunityAuthor)
.filter(CommunityAuthor.author_id == test_user.id, CommunityAuthor.community_id == 1)
.first()
)
if existing_community_author:
db_session.delete(existing_community_author)
# Создаем новую запись с ролями
community_author = CommunityAuthor(
community_id=1,
author_id=test_user.id,
roles="reader,author", # CSV строка с ролями
)
db_session.add(community_author)
db_session.commit()
2025-07-02 19:30:21 +00:00
return test_user
class MockInfo:
"""Мок для GraphQL info объекта"""
def __init__(self, author_id: int):
self.context = {
"request": None, # Тестовый режим
"author": {"id": author_id, "name": "Test User"},
"roles": ["reader", "author"],
"is_admin": False,
}
2025-02-11 09:00:35 +00:00
2025-02-09 19:26:50 +00:00
@pytest.fixture
def test_author(db_session):
"""Create a test author."""
return ensure_test_user_with_roles(db_session)
2025-02-09 19:26:50 +00:00
2025-02-11 09:00:35 +00:00
2025-02-09 19:26:50 +00:00
@pytest.fixture
def test_shout(db_session):
"""Create test shout with required fields."""
author = ensure_test_user_with_roles(db_session)
2025-02-09 19:26:50 +00:00
shout = Shout(
title="Test Shout",
slug="test-shout-drafts",
2025-02-09 19:26:50 +00:00
created_by=author.id, # Обязательное поле
body="Test body",
layout="article",
2025-02-11 09:00:35 +00:00
lang="ru",
2025-02-09 19:26:50 +00:00
)
db_session.add(shout)
db_session.commit()
return shout
2025-02-11 09:00:35 +00:00
2025-02-09 19:26:50 +00:00
@pytest.mark.asyncio
async def test_create_shout(db_session, test_author):
"""Test creating a new draft using direct resolver call."""
# Создаем мок info
info = MockInfo(test_author.id)
# Вызываем резолвер напрямую
result = await create_draft(
None,
info,
draft_input={
"title": "Test Shout",
"body": "This is a test shout",
2025-02-11 09:00:35 +00:00
},
2025-02-09 19:26:50 +00:00
)
2025-02-11 09:00:35 +00:00
# Проверяем результат
assert "error" not in result or result["error"] is None
assert result["draft"].title == "Test Shout"
assert result["draft"].body == "This is a test shout"
2025-02-09 19:26:50 +00:00
2025-02-11 09:00:35 +00:00
2025-02-09 19:26:50 +00:00
@pytest.mark.asyncio
async def test_load_drafts(db_session):
"""Test retrieving drafts using direct resolver call."""
# Создаем тестового пользователя
test_user = ensure_test_user_with_roles(db_session)
# Создаем мок info
info = MockInfo(test_user.id)
# Вызываем резолвер напрямую
result = await load_drafts(None, info)
# Проверяем результат (должен быть список, может быть не пустой из-за предыдущих тестов)
assert "error" not in result or result["error"] is None
assert isinstance(result["drafts"], list)
2025-02-11 09:00:35 +00:00
# Если есть черновики, проверим что они правильной структуры
if result["drafts"]:
draft = result["drafts"][0]
assert "id" in draft
assert "title" in draft
assert "body" in draft
assert "authors" in draft
assert "topics" in draft