dzen.nstarikov.ru/tests/test_draft_api.py

149 lines
5.1 KiB
Python
Raw Normal View History

2026-08-24 13:19:45 +03:00
import unittest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from sqlalchemy import create_engine, func, select
from sqlalchemy.orm import Session
from sqlalchemy.pool import StaticPool
from app.config import Settings, get_settings
from app.database import Base, get_session
from app.models import AppSetting, Article
from app.routes import SETTING_DRAFT_API_KEY_HASH, draft_api_key_hash, router
class DraftApiTest(unittest.TestCase):
def setUp(self):
self.engine = create_engine(
"sqlite://",
connect_args={"check_same_thread": False},
poolclass=StaticPool,
)
Base.metadata.create_all(self.engine)
self.api_key = "dzen_draft_test_key"
with Session(self.engine) as session:
session.add(
AppSetting(
key=SETTING_DRAFT_API_KEY_HASH,
value=draft_api_key_hash(self.api_key),
)
)
session.commit()
app = FastAPI()
app.include_router(router)
def override_session():
with Session(self.engine) as session:
yield session
app.dependency_overrides[get_session] = override_session
app.dependency_overrides[get_settings] = lambda: Settings(public_base_url="https://example.test")
self.client = TestClient(app)
self.headers = {"Authorization": f"Bearer {self.api_key}"}
def tearDown(self):
self.engine.dispose()
@staticmethod
def payload(slug: str) -> dict[str, str]:
return {
"title": "Заголовок статьи",
"slug": slug,
"lead": "<p>Лид.</p>",
"bodyHtml": "<h2>Раздел</h2><p>Текст.</p>",
"featureImageUrl": "https://example.test/cover.webp",
"ctaHtml": "",
}
def test_creates_draft_with_exact_requested_slug(self):
response = self.client.post(
"/api/v1/drafts",
json=self.payload("zagolovok-stati"),
headers=self.headers,
)
self.assertEqual(response.status_code, 201)
data = response.json()
self.assertEqual(data["slug"], "zagolovok-stati")
self.assertEqual(data["url"], "https://example.test/posts/zagolovok-stati")
self.assertEqual(data["status"], "draft")
self.assertIsNone(data["publishedAt"])
with Session(self.engine) as session:
article = session.scalar(select(Article).where(Article.slug == "zagolovok-stati"))
self.assertIsNotNone(article)
def test_normalizes_case_and_outer_whitespace(self):
response = self.client.post(
"/api/v1/drafts",
json=self.payload(" Zagolovok-Stati "),
headers=self.headers,
)
self.assertEqual(response.status_code, 201)
self.assertEqual(response.json()["slug"], "zagolovok-stati")
def test_rejects_missing_slug(self):
payload = self.payload("zagolovok-stati")
payload.pop("slug")
response = self.client.post("/api/v1/drafts", json=payload, headers=self.headers)
self.assertEqual(response.status_code, 422)
def test_rejects_invalid_or_too_long_slug_without_creating_rows(self):
for slug in ("кириллица", "with_underscore", "double--hyphen", "a" * 241):
with self.subTest(slug=slug[:30]):
response = self.client.post(
"/api/v1/drafts",
json=self.payload(slug),
headers=self.headers,
)
self.assertEqual(response.status_code, 422)
with Session(self.engine) as session:
self.assertEqual(session.scalar(select(func.count(Article.id))), 0)
def test_accepts_slug_at_maximum_length(self):
slug = "a" * 240
response = self.client.post(
"/api/v1/drafts",
json=self.payload(slug),
headers=self.headers,
)
self.assertEqual(response.status_code, 201)
self.assertEqual(response.json()["slug"], slug)
def test_duplicate_slug_returns_conflict_without_random_suffix(self):
first = self.client.post(
"/api/v1/drafts",
json=self.payload("zagolovok-stati"),
headers=self.headers,
)
second = self.client.post(
"/api/v1/drafts",
json=self.payload("zagolovok-stati"),
headers=self.headers,
)
self.assertEqual(first.status_code, 201)
self.assertEqual(second.status_code, 409)
self.assertEqual(second.json()["detail"], "Slug уже используется.")
with Session(self.engine) as session:
self.assertEqual(session.scalar(select(func.count(Article.id))), 1)
def test_rejects_invalid_api_key(self):
response = self.client.post(
"/api/v1/drafts",
json=self.payload("zagolovok-stati"),
headers={"Authorization": "Bearer wrong"},
)
self.assertEqual(response.status_code, 401)
if __name__ == "__main__":
unittest.main()