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, Video 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": "
Лид.
", "bodyHtml": "Текст.
", "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) def test_lists_and_reads_drafts_with_source_video(self): with Session(self.engine) as session: video = Video( external_id="vk-123", source_url="https://vkvideo.ru/video-1_123", title="Исходный ролик", duration_seconds=321, ) session.add(video) session.flush() session.add( Article( video_id=video.id, slug="draft-from-video", title="Черновик из ролика", lead="Вступление.
", body_html="Текст.
", cta_html="", status="draft", ) ) session.commit() video_id = video.id response = self.client.get(f"/api/v1/drafts?videoId={video_id}", headers=self.headers) self.assertEqual(response.status_code, 200) data = response.json() self.assertEqual(data["total"], 1) self.assertEqual(data["items"][0]["title"], "Черновик из ролика") self.assertEqual(data["items"][0]["video"]["sourceUrl"], "https://vkvideo.ru/video-1_123") self.assertIn("bodyHtml", data["items"][0]) detail = self.client.get(f"/api/v1/drafts/{data['items'][0]['id']}", headers=self.headers) self.assertEqual(detail.status_code, 200) self.assertEqual(detail.json()["slug"], "draft-from-video") if __name__ == "__main__": unittest.main()