Files
core/tests/test_drafts.py
2025-07-31 18:55:59 +03:00

149 lines
5.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import pytest
from auth.orm import Author
from orm.community import CommunityAuthor
from orm.shout import Shout
from resolvers.draft import create_draft, load_drafts
def ensure_test_user_with_roles(db_session):
"""Создает тестового пользователя с ID 1 и назначает ему роли через CommunityAuthor"""
# Создаем пользователя с ID 1 если его нет
test_user = db_session.query(Author).where(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()
# Удаляем старые роли
existing_community_author = (
db_session.query(CommunityAuthor)
.where(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()
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,
}
@pytest.fixture
def test_author(db_session):
"""Create a test author."""
return ensure_test_user_with_roles(db_session)
@pytest.fixture
def test_shout(db_session):
"""Create test shout with required fields."""
author = ensure_test_user_with_roles(db_session)
# Создаем тестовое сообщество если его нет
from orm.community import Community
community = db_session.query(Community).where(Community.id == 1).first()
if not community:
community = Community(
name="Test Community",
slug="test-community",
desc="Test community description",
created_by=author.id
)
db_session.add(community)
db_session.flush()
shout = Shout(
title="Test Shout",
slug="test-shout-drafts",
created_by=author.id, # Обязательное поле
community=community.id, # Обязательное поле
body="Test body",
layout="article",
lang="ru",
)
db_session.add(shout)
db_session.commit()
return shout
@pytest.mark.asyncio
async def test_create_shout(db_session, test_author):
"""Test creating a new draft using direct resolver call."""
# Мокаем local_session чтобы использовать тестовую сессию
from unittest.mock import patch
from services.db import local_session
with patch('services.db.local_session') as mock_local_session:
mock_local_session.return_value = db_session
result = await create_draft(
None,
MockInfo(test_author.id),
draft_input={
"title": "Test Shout",
"body": "This is a test shout",
},
)
# Проверяем результат
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"
@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)
# Мокаем local_session чтобы использовать тестовую сессию
from unittest.mock import patch
from services.db import local_session
with patch('services.db.local_session') as mock_local_session:
mock_local_session.return_value = db_session
# Вызываем резолвер напрямую
result = await load_drafts(None, info)
# Проверяем результат (должен быть список, может быть не пустой из-за предыдущих тестов)
assert "error" not in result or result["error"] is None
assert isinstance(result["drafts"], list)
# Если есть черновики, проверим что они правильной структуры
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