dzen.nstarikov.ru/tests/test_draft_api.py
nstarikov 367e772e65
Some checks failed
Deploy Dzen assistant / deploy (push) Failing after 0s
Add safe external draft update API
2026-10-18 15:12:44 +03:00

390 lines
15 KiB
Python

import unittest
from datetime import datetime, timezone
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, sanitize_article_editor_html
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 create_video_draft(self, *, slug: str = "draft-from-video") -> tuple[int, int]:
with Session(self.engine) as session:
video = Video(
external_id=f"vk-{slug}",
source_url="https://vkvideo.ru/video-1_123",
title="Исходный ролик",
duration_seconds=321,
)
session.add(video)
session.flush()
article = Article(
video_id=video.id,
slug=slug,
title="Черновик из ролика",
lead="<p>Вступление.</p>",
body_html="<h2>Раздел</h2><p>Текст.</p>",
cta_html="",
status="draft",
)
session.add(article)
session.commit()
return article.id, video.id
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="<p>Вступление.</p>",
body_html="<h2>Раздел</h2><p>Текст.</p>",
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")
def test_sanitizer_keeps_vk_embed_and_removes_other_iframes(self):
html = (
'<p>До видео</p>'
'<iframe src="https://vkvideo.ru/video_ext.php?oid=-1&id=2" title="VK"></iframe>'
'<iframe src="https://example.com/video.html"></iframe>'
)
sanitized = sanitize_article_editor_html(html)
self.assertIn('src="https://vkvideo.ru/video_ext.php?oid=-1&amp;id=2"', sanitized)
self.assertNotIn("example.com", sanitized)
def test_updates_editorial_fields_and_preserves_draft_video_boundary(self):
article_id, video_id = self.create_video_draft()
response = self.client.patch(
f"/api/v1/drafts/{article_id}",
json={
"title": " Новый заголовок ",
"slug": " New-Draft-Slug ",
"lead": '<p>Новый лид.</p><script>alert("x")</script>',
"bodyHtml": (
"<h1>Новый заголовок</h1>"
'<p>Новый текст.</p><iframe src="https://example.com/embed"></iframe>'
),
"featureImageUrl": "/media/covers/new-cover.jpg",
"ctaHtml": '<p>Подпись.</p><script>alert("x")</script>',
},
headers=self.headers,
)
self.assertEqual(response.status_code, 200)
data = response.json()
self.assertEqual(data["title"], "Новый заголовок")
self.assertEqual(data["slug"], "new-draft-slug")
self.assertEqual(data["featureImageUrl"], "/media/covers/new-cover.jpg")
self.assertEqual(data["lead"], "<p>Новый лид.</p>")
self.assertNotIn("<h1", data["bodyHtml"])
self.assertIn("Новый текст.", data["bodyHtml"])
self.assertNotIn("example.com", data["bodyHtml"])
self.assertEqual(data["ctaHtml"], "<p>Подпись.</p>")
self.assertEqual(data["video"]["id"], video_id)
self.assertEqual(data["status"], "draft")
self.assertIsNone(data["publishedAt"])
with Session(self.engine) as session:
article = session.get(Article, article_id)
self.assertEqual(article.video_id, video_id)
self.assertEqual(article.status, "draft")
self.assertIsNone(article.published_at)
def test_update_rejects_empty_payload(self):
article_id, _ = self.create_video_draft()
response = self.client.patch(f"/api/v1/drafts/{article_id}", json={}, headers=self.headers)
self.assertEqual(response.status_code, 422)
def test_update_rejects_explicit_null(self):
article_id, _ = self.create_video_draft()
response = self.client.patch(
f"/api/v1/drafts/{article_id}",
json={"lead": None},
headers=self.headers,
)
self.assertEqual(response.status_code, 422)
def test_update_changes_only_supplied_fields(self):
article_id, video_id = self.create_video_draft()
response = self.client.patch(
f"/api/v1/drafts/{article_id}",
json={"lead": "<p>Только новый лид.</p>"},
headers=self.headers,
)
self.assertEqual(response.status_code, 200)
data = response.json()
self.assertEqual(data["lead"], "<p>Только новый лид.</p>")
self.assertEqual(data["title"], "Черновик из ролика")
self.assertEqual(data["slug"], "draft-from-video")
self.assertEqual(data["bodyHtml"], "<h2>Раздел</h2><p>Текст.</p>")
self.assertEqual(data["video"]["id"], video_id)
self.assertEqual(data["status"], "draft")
self.assertIsNone(data["publishedAt"])
def test_update_rejects_invalid_api_key(self):
article_id, _ = self.create_video_draft()
response = self.client.patch(
f"/api/v1/drafts/{article_id}",
json={"lead": "<p>Новый лид.</p>"},
headers={"Authorization": "Bearer wrong"},
)
self.assertEqual(response.status_code, 401)
def test_update_missing_article_returns_not_found(self):
response = self.client.patch(
"/api/v1/drafts/999999",
json={"lead": "<p>Новый лид.</p>"},
headers=self.headers,
)
self.assertEqual(response.status_code, 404)
def test_update_rejected_article_returns_not_found(self):
article_id, _ = self.create_video_draft()
with Session(self.engine) as session:
article = session.get(Article, article_id)
article.status = "rejected"
session.commit()
response = self.client.patch(
f"/api/v1/drafts/{article_id}",
json={"lead": "<p>Новый лид.</p>"},
headers=self.headers,
)
self.assertEqual(response.status_code, 404)
def test_update_rejects_published_or_non_draft_article(self):
for status, published_at in (
("published", None),
("draft", datetime.now(timezone.utc)),
("processing", None),
):
with self.subTest(status=status, published_at=published_at):
article_id, _ = self.create_video_draft(slug=f"guarded-{status}-{bool(published_at)}")
with Session(self.engine) as session:
article = session.get(Article, article_id)
article.status = status
article.published_at = published_at
session.commit()
response = self.client.patch(
f"/api/v1/drafts/{article_id}",
json={"lead": "<p>Новый лид.</p>"},
headers=self.headers,
)
self.assertEqual(response.status_code, 409)
def test_update_rejects_duplicate_slug(self):
article_id, _ = self.create_video_draft(slug="first-draft")
self.create_video_draft(slug="occupied-slug")
response = self.client.patch(
f"/api/v1/drafts/{article_id}",
json={"slug": "occupied-slug"},
headers=self.headers,
)
self.assertEqual(response.status_code, 409)
self.assertEqual(response.json()["detail"], "Slug уже используется.")
def test_update_rejects_invalid_cover_url(self):
article_id, _ = self.create_video_draft()
response = self.client.patch(
f"/api/v1/drafts/{article_id}",
json={"featureImageUrl": "javascript:alert(1)"},
headers=self.headers,
)
self.assertEqual(response.status_code, 422)
def test_update_rejects_unknown_or_forbidden_fields(self):
article_id, _ = self.create_video_draft()
for payload in ({"status": "published"}, {"videoId": None}, {"unknown": "value"}):
with self.subTest(payload=payload):
response = self.client.patch(
f"/api/v1/drafts/{article_id}",
json=payload,
headers=self.headers,
)
self.assertEqual(response.status_code, 422)
if __name__ == "__main__":
unittest.main()