🧪 Smoke-test: fix admin_content — патч ADMIN_IDS в модуле

Root cause: admin_content.py использует 'from config import ADMIN_IDS' —
значение импортируется при загрузке модуля. Патч config.ADMIN_IDS
не влияет на уже загруженный модуль.

Fix: патчим admin_content_module.ADMIN_IDS напрямую (как для admin,
feed, support, users).

Было: 8 FAILED (403 для всех admin_content)
Стало: ожидаем 8 PASSED
This commit is contained in:
2026-09-26 09:54:09 +00:00
parent ccfe31b9fa
commit d6231b7b0f
+712 -9
View File
@@ -28,6 +28,21 @@ leaderboard, assistant, support, admin, feed.
learning (5), teacher (8), achievements (8), users (2), admin (1),
assistant (2), support (2), feed (1), hints (2), game (2).
AI-эндпоинты помечены @pytest.mark.skip или обёрнуты в try/except.
РАСШИРЕНО (26.09.2026, ночь): волна 7 (подволна A3) — добавлено 26 сценариев:
игры (wordquiz/bubblewords/sentences/typing — next/progress/hint),
achievements (all), assistant (history/clear) — 12 сценариев;
admin_content (8), admin_feed (6, 3 из них skip по AI).
ФИКС (26.09.2026): admin_fixture_module_patch —
config.ADMIN_IDS импортируется в модули как значение (from config import ADMIN_IDS).
Патч config_module.ADMIN_IDS НЕ работает — нужно патчить ADMIN_IDS в каждом
модуле: routers.admin, routers.feed, routers.support, routers.users.
ФИКС (26.09.2026, вечер): admin_content_module_patch —
8 FAILED были из-за того, что admin_content.py тоже использует
from config import ADMIN_IDS. Добавлен патч для routers.admin_content.
Итого патчим 5 модулей: admin, feed, support, users, admin_content.
"""
import hashlib
import hmac
@@ -49,6 +64,9 @@ from config import BOT_TOKEN
SMOKE_USER_ID = 9999999999
SMOKE_USER_FIRST_NAME = "SmokeTestUser"
SMOKE_ADMIN_ID = 9999999998
SMOKE_ADMIN_FIRST_NAME = "SmokeAdmin"
# ============ Генерация initData (1:1 с auth.py) ============
@@ -107,19 +125,26 @@ NON_FK_TABLES = [
]
async def _cleanup(conn) -> None:
async def _cleanup_user(conn, user_id: int) -> None:
"""Удаляет все данные пользователя. Используется и для smoke_user,
и для smoke_admin (чтобы не дублировать код)."""
async with conn.transaction():
for table in NON_FK_TABLES:
await conn.execute(f"DELETE FROM {table} WHERE user_id = $1", SMOKE_USER_ID)
await conn.execute(f"DELETE FROM {table} WHERE user_id = $1", user_id)
await conn.execute(
"DELETE FROM support_messages WHERE ticket_id IN "
"(SELECT id FROM support_tickets WHERE user_id = $1)",
SMOKE_USER_ID,
user_id,
)
await conn.execute("DELETE FROM support_tickets WHERE user_id = $1", SMOKE_USER_ID)
await conn.execute("DELETE FROM support_tickets WHERE user_id = $1", user_id)
await conn.execute("DELETE FROM users WHERE telegram_id = $1", SMOKE_USER_ID)
await conn.execute("DELETE FROM users WHERE telegram_id = $1", user_id)
async def _cleanup(conn) -> None:
"""Удаляет данные smoke_user (обратная совместимость)."""
await _cleanup_user(conn, SMOKE_USER_ID)
# ============ Фикстуры ============
@@ -154,6 +179,78 @@ async def smoke_user(smoke_conn):
_write_report()
@pytest.fixture(scope="session")
async def smoke_admin(smoke_user, smoke_conn):
"""Создаёт админ-юзера + патчит ADMIN_IDS ВО ВСЕХ МОДУЛЯХ, где он импортирован.
ВАЖНО (26.09.2026): config.ADMIN_IDS импортируется в модули через
`from config import ADMIN_IDS` — это ЗНАЧЕНИЕ, а не ссылка. Патч
config_module.ADMIN_IDS не сработает. Нужно патчить ADMIN_IDS в каждом
модуле отдельно.
Патчим 5 модулей:
- routers.admin
- routers.feed
- routers.support
- routers.users
- routers.admin_content ← ГЛАВНОЕ ДОБАВЛЕНИЕ (26.09.2026, вечер)
Без него 8 admin_content-сценариев падали с 403.
Также зависим от smoke_user — это гарантирует, что admin создастся
ПОСЛЕ user и удалится РАНЬШЕ (LIFO порядок cleanup у pytest).
"""
import routers.admin as admin_module
import routers.feed as feed_module
import routers.support as support_module
import routers.users as users_module
import routers.admin_content as admin_content_module
# Сохраняем оригиналы
originals = {
"admin": admin_module.ADMIN_IDS,
"feed": feed_module.ADMIN_IDS,
"support": support_module.ADMIN_IDS,
"users": users_module.ADMIN_IDS,
"admin_content": admin_content_module.ADMIN_IDS,
}
# Патчим — новый список с SMOKE_ADMIN_ID
new_ids = list(originals["admin"]) + [SMOKE_ADMIN_ID]
admin_module.ADMIN_IDS = new_ids
feed_module.ADMIN_IDS = new_ids
support_module.ADMIN_IDS = new_ids
users_module.ADMIN_IDS = new_ids
admin_content_module.ADMIN_IDS = new_ids
# Cleanup старого админа (если остался от предыдущего прогона)
await _cleanup_user(smoke_conn, SMOKE_ADMIN_ID)
# Регистрируем админа
init_data = _build_init_data(SMOKE_ADMIN_ID, SMOKE_ADMIN_FIRST_NAME, BOT_TOKEN)
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://test",
headers={"Authorization": f"tma {init_data}"},
) as client:
resp = await client.post("/users/register")
assert resp.status_code == 200, (
f"Не удалось зарегистрировать админа: {resp.status_code} {resp.text[:200]}"
)
yield client
# Восстанавливаем ADMIN_IDS во всех модулях
admin_module.ADMIN_IDS = originals["admin"]
feed_module.ADMIN_IDS = originals["feed"]
support_module.ADMIN_IDS = originals["support"]
users_module.ADMIN_IDS = originals["users"]
admin_content_module.ADMIN_IDS = originals["admin_content"]
# Cleanup админа
await _cleanup_user(smoke_conn, SMOKE_ADMIN_ID)
# ============================================================
# ВОЛНА 1 — игры (базовые)
# ============================================================
@@ -1434,7 +1531,6 @@ async def test_feed_post_detail(smoke_user, smoke_conn):
# 🔧 НОВОЕ (26.09.2026): волна 6 — achievements (8 track + user)
# Это волна с 8 track-эндпоинтами достижений + один общий.
async def test_achievements_track_teacher_menu(smoke_user):
"""POST /achievements/track-teacher-menu → new_achievements (список)."""
@@ -1583,7 +1679,6 @@ async def test_achievements_user(smoke_user):
# 🔧 НОВОЕ (26.09.2026): волна 6 — users (is_admin + set_level)
# Это дополнение к волне 2 (set_language).
async def test_users_is_admin(smoke_user):
"""GET /users/me/is-admin → is_admin == False (тестовый юзер не админ)."""
@@ -1636,7 +1731,6 @@ async def test_users_set_level(smoke_user, smoke_conn):
# 🔧 НОВОЕ (26.09.2026): волна 6 — hints (word-list + remaining)
# Это дополнение к волне 1 (first-letter).
async def test_hints_word_list(smoke_user):
"""GET /hints/word-list/{level_id} → список слов. level_id=1."""
@@ -1686,7 +1780,6 @@ async def test_hints_remaining(smoke_user):
# 🔧 НОВОЕ (26.09.2026): волна 6 — game (progress + check-word)
# Это дополнение к волне 1 (complete-level).
async def test_game_progress(smoke_user):
"""GET /game/progress → last_completed_level, total_score, current_level."""
@@ -1735,6 +1828,616 @@ async def test_game_check_word(smoke_user):
assert passed
# ============================================================
# ВОЛНА 7 (подволна A3) — остатки игр + achievements
# ============================================================
# --- wordquiz (next + progress) ---
async def test_wordquiz_next(smoke_user):
"""GET /wordquiz/next → correct_polish + options + difficulty."""
client = smoke_user
resp = await client.get("/wordquiz/next")
ok = resp.status_code == 200
body = resp.json() if ok else {}
has_correct = bool(body.get("correct_polish"))
has_options = isinstance(body.get("options"), list) and len(body.get("options")) >= 3
has_difficulty = body.get("difficulty") in ("easy", "medium", "hard", "expert")
passed = ok and has_correct and has_options and has_difficulty
RESULTS.append(ScenarioResult(
"wordquiz_next", "wordquiz", passed,
f"status={resp.status_code}, correct={bool(body.get('correct_polish'))}, options={len(body.get('options', []))}, diff={body.get('difficulty')}",
{"status": resp.status_code, "correct": body.get("correct_polish"), "options_count": len(body.get("options", [])), "difficulty": body.get("difficulty")},
))
assert passed
async def test_wordquiz_progress(smoke_user):
"""GET /wordquiz/progress → words_guessed, total_score, difficulty."""
client = smoke_user
resp = await client.get("/wordquiz/progress")
ok = resp.status_code == 200
body = resp.json() if ok else {}
has_words = "words_guessed" in body
has_score = "total_score" in body
has_difficulty = "difficulty" in body
passed = ok and has_words and has_score and has_difficulty
RESULTS.append(ScenarioResult(
"wordquiz_progress", "wordquiz", passed,
f"status={resp.status_code}, words={body.get('words_guessed')}, score={body.get('total_score')}",
{"status": resp.status_code, "words_guessed": body.get("words_guessed"), "difficulty": body.get("difficulty")},
))
assert passed
# --- bubblewords (next + progress) ---
async def test_bubblewords_next(smoke_user):
"""GET /bubblewords/next → words + bubbles + level."""
client = smoke_user
resp = await client.get("/bubblewords/next")
ok = resp.status_code == 200
body = resp.json() if ok else {}
has_words = isinstance(body.get("words"), list) and len(body.get("words")) >= 2
has_bubbles = isinstance(body.get("bubbles"), list) and len(body.get("bubbles")) > 0
has_level = isinstance(body.get("level"), int)
passed = ok and has_words and has_bubbles and has_level
RESULTS.append(ScenarioResult(
"bubblewords_next", "bubblewords", passed,
f"status={resp.status_code}, words={len(body.get('words', []))}, bubbles={len(body.get('bubbles', []))}, level={body.get('level')}",
{"status": resp.status_code, "words_count": len(body.get("words", [])), "bubbles_count": len(body.get("bubbles", [])), "level": body.get("level")},
))
assert passed
async def test_bubblewords_progress(smoke_user):
"""GET /bubblewords/progress → levels_completed, total_score."""
client = smoke_user
resp = await client.get("/bubblewords/progress")
ok = resp.status_code == 200
body = resp.json() if ok else {}
has_levels = "levels_completed" in body
has_score = "total_score" in body
passed = ok and has_levels and has_score
RESULTS.append(ScenarioResult(
"bubblewords_progress", "bubblewords", passed,
f"status={resp.status_code}, levels={body.get('levels_completed')}, score={body.get('total_score')}",
{"status": resp.status_code, "levels_completed": body.get("levels_completed")},
))
assert passed
# --- sentences (next + stats + hint) ---
async def test_sentences_next(smoke_user):
"""GET /sentences/next → id + words + correct_words."""
client = smoke_user
resp = await client.get("/sentences/next")
ok = resp.status_code == 200
body = resp.json() if ok else {}
# Может быть: {completed: True} если всё пройдено
if body.get("completed") is True:
RESULTS.append(ScenarioResult(
"sentences_next", "sentences", True,
"Все предложения пройдены (completed=True)",
{"completed": True},
))
return
has_id = body.get("id") is not None
has_words = isinstance(body.get("words"), list)
has_correct = isinstance(body.get("correct_words"), list)
passed = ok and has_id and has_words and has_correct
RESULTS.append(ScenarioResult(
"sentences_next", "sentences", passed,
f"status={resp.status_code}, id={body.get('id')}, words={len(body.get('words', []))}",
{"status": resp.status_code, "id": body.get("id"), "words_count": len(body.get("words", []))},
))
assert passed
async def test_sentences_stats(smoke_user):
"""GET /sentences/stats → total_sentences, completed, progress_percent."""
client = smoke_user
resp = await client.get("/sentences/stats")
ok = resp.status_code == 200
body = resp.json() if ok else {}
has_total = "total_sentences" in body
has_completed = "completed" in body
has_percent = "progress_percent" in body
passed = ok and has_total and has_completed and has_percent
RESULTS.append(ScenarioResult(
"sentences_stats", "sentences", passed,
f"status={resp.status_code}, total={body.get('total_sentences')}, completed={body.get('completed')}, percent={body.get('progress_percent')}",
{"status": resp.status_code, "total": body.get("total_sentences"), "completed": body.get("completed")},
))
assert passed
async def test_sentences_hint(smoke_user, smoke_conn):
"""GET /sentences/{id}/hint → sentence_pl, лимит 1 раз."""
client = smoke_user
# Берём предложение, которое юзер ещё НЕ проходил и НЕ брал подсказку
sentence_id = await smoke_conn.fetchval("""
SELECT id FROM sentences
WHERE id NOT IN (
SELECT sentence_id FROM sentence_hints_used WHERE user_id = $1
)
ORDER BY id LIMIT 1
""", SMOKE_USER_ID)
if not sentence_id:
pytest.skip("Нет предложений для hint-теста")
return
# 1. Первый запрос — 200
resp1 = await client.get(f"/sentences/{sentence_id}/hint")
ok1 = resp1.status_code == 200
body1 = resp1.json() if ok1 else {}
has_sentence = bool(body1.get("sentence_pl"))
# 2. Проверка в БД
recorded = await smoke_conn.fetchval(
"SELECT 1 FROM sentence_hints_used WHERE user_id = $1 AND sentence_id = $2",
SMOKE_USER_ID, sentence_id,
) is not None
# 3. Второй запрос — 403 (лимит)
resp2 = await client.get(f"/sentences/{sentence_id}/hint")
limit_ok = resp2.status_code == 403
passed = ok1 and has_sentence and recorded and limit_ok
RESULTS.append(ScenarioResult(
"sentences_hint", "sentences", passed,
f"first={resp1.status_code}, recorded={recorded}, second={resp2.status_code} (ожидали 403)",
{"first_status": resp1.status_code, "recorded": recorded, "second_status": resp2.status_code},
))
assert passed
# --- typing (next + hint + progress) ---
async def test_typing_next(smoke_user):
"""GET /typing/next → sentence_id + translation (или completed)."""
client = smoke_user
resp = await client.get("/typing/next")
ok = resp.status_code == 200
body = resp.json() if ok else {}
# Может быть: {completed: True}
if body.get("completed") is True:
RESULTS.append(ScenarioResult(
"typing_next", "typing", True,
"Все предложения пройдены",
{"completed": True},
))
return
has_id = body.get("sentence_id") is not None
has_translation = bool(body.get("translation"))
passed = ok and has_id and has_translation
RESULTS.append(ScenarioResult(
"typing_next", "typing", passed,
f"status={resp.status_code}, sentence_id={body.get('sentence_id')}",
{"status": resp.status_code, "sentence_id": body.get("sentence_id")},
))
assert passed
async def test_typing_hint(smoke_user, smoke_conn):
"""GET /typing/hint/{id} → correct_answer, лимит 1 раз."""
client = smoke_user
sentence_id = await smoke_conn.fetchval("""
SELECT id FROM sentences
WHERE id NOT IN (
SELECT sentence_id FROM typing_hints_used WHERE user_id = $1
)
ORDER BY id LIMIT 1
""", SMOKE_USER_ID)
if not sentence_id:
pytest.skip("Нет предложений для hint-теста")
return
resp1 = await client.get(f"/typing/hint/{sentence_id}")
ok1 = resp1.status_code == 200
body1 = resp1.json() if ok1 else {}
has_answer = bool(body1.get("correct_answer"))
recorded = await smoke_conn.fetchval(
"SELECT 1 FROM typing_hints_used WHERE user_id = $1 AND sentence_id = $2",
SMOKE_USER_ID, sentence_id,
) is not None
resp2 = await client.get(f"/typing/hint/{sentence_id}")
limit_ok = resp2.status_code == 403
passed = ok1 and has_answer and recorded and limit_ok
RESULTS.append(ScenarioResult(
"typing_hint", "typing", passed,
f"first={resp1.status_code}, recorded={recorded}, second={resp2.status_code} (ожидали 403)",
{"first_status": resp1.status_code, "recorded": recorded, "second_status": resp2.status_code},
))
assert passed
async def test_typing_progress(smoke_user):
"""GET /typing/progress → total, completed, remaining."""
client = smoke_user
resp = await client.get("/typing/progress")
ok = resp.status_code == 200
body = resp.json() if ok else {}
has_total = "total" in body
has_completed = "completed" in body
has_remaining = "remaining" in body
passed = ok and has_total and has_completed and has_remaining
RESULTS.append(ScenarioResult(
"typing_progress", "typing", passed,
f"status={resp.status_code}, {body.get('completed')}/{body.get('total')}, remaining={body.get('remaining')}",
{"status": resp.status_code, "total": body.get("total"), "completed": body.get("completed")},
))
assert passed
# --- achievements (all) ---
async def test_achievements_all(smoke_user):
"""GET /achievements → все достижения."""
client = smoke_user
resp = await client.get("/achievements")
ok = resp.status_code == 200
body = resp.json() if ok else {}
achievements = body.get("achievements", [])
passed = ok and isinstance(achievements, list) and len(achievements) > 0
RESULTS.append(ScenarioResult(
"achievements_all", "achievements", passed,
f"status={resp.status_code}, всего={len(achievements)}",
{"status": resp.status_code, "count": len(achievements)},
))
assert passed
# --- assistant (history/clear) ---
async def test_assistant_history_clear(smoke_user, smoke_conn):
"""POST /assistant/history/clear → история пуста."""
client = smoke_user
resp = await client.post("/assistant/history/clear")
ok = resp.status_code == 200
remaining = await smoke_conn.fetchval(
"SELECT COUNT(*) FROM chat_history WHERE user_id = $1", SMOKE_USER_ID,
) or 0
passed = ok and remaining == 0
RESULTS.append(ScenarioResult(
"assistant_history_clear", "assistant", passed,
f"status={resp.status_code}, remaining={remaining}",
{"status": resp.status_code, "remaining": remaining},
))
assert passed
# ============================================================
# ВОЛНА 8 (подволна A3) — admin_content (требует smoke_admin)
# ============================================================
async def test_admin_content_summary(smoke_admin):
"""GET /admin/content/summary → сводка по уровням."""
client = smoke_admin
resp = await client.get("/admin/content/summary")
ok = resp.status_code == 200
body = resp.json() if ok else {}
levels = body.get("levels", [])
passed = ok and isinstance(levels, list) and len(levels) > 0
RESULTS.append(ScenarioResult(
"admin_content_summary", "admin_content", passed,
f"status={resp.status_code}, уровней={len(levels)}",
{"status": resp.status_code, "count": len(levels)},
))
assert passed
async def test_admin_content_word_levels(smoke_admin):
"""GET /admin/content/words/levels → уровни со счётчиками слов."""
client = smoke_admin
resp = await client.get("/admin/content/words/levels")
ok = resp.status_code == 200
body = resp.json() if ok else {}
levels = body.get("levels", [])
passed = ok and isinstance(levels, list) and len(levels) > 0
RESULTS.append(ScenarioResult(
"admin_content_word_levels", "admin_content", passed,
f"status={resp.status_code}, уровней={len(levels)}",
{"status": resp.status_code, "count": len(levels)},
))
assert passed
async def test_admin_content_word_detail(smoke_admin, smoke_conn):
"""GET /admin/content/words/word/{id} → одно слово."""
client = smoke_admin
word_id = await smoke_conn.fetchval(
"SELECT id FROM level_words WHERE level_id IS NULL LIMIT 1"
)
if not word_id:
pytest.skip("Нет слов уровня")
return
resp = await client.get(f"/admin/content/words/word/{word_id}")
ok = resp.status_code == 200
body = resp.json() if ok else {}
has_word = bool(body.get("word_pl"))
passed = ok and has_word
RESULTS.append(ScenarioResult(
"admin_content_word_detail", "admin_content", passed,
f"status={resp.status_code}, word_id={word_id}, word_pl={body.get('word_pl')}",
{"status": resp.status_code, "word_id": word_id},
))
assert passed
async def test_admin_content_texts_levels(smoke_admin):
"""GET /admin/content/texts/levels → уровни со счётчиками текстов."""
client = smoke_admin
resp = await client.get("/admin/content/texts/levels")
ok = resp.status_code == 200
body = resp.json() if ok else {}
levels = body.get("levels", [])
passed = ok and isinstance(levels, list) and len(levels) > 0
RESULTS.append(ScenarioResult(
"admin_content_texts_levels", "admin_content", passed,
f"status={resp.status_code}, уровней={len(levels)}",
{"status": resp.status_code, "count": len(levels)},
))
assert passed
async def test_admin_content_lessons_levels(smoke_admin):
"""GET /admin/content/lessons/levels → уровни со счётчиками тем/уроков."""
client = smoke_admin
resp = await client.get("/admin/content/lessons/levels")
ok = resp.status_code == 200
body = resp.json() if ok else {}
levels = body.get("levels", [])
passed = ok and isinstance(levels, list) and len(levels) > 0
RESULTS.append(ScenarioResult(
"admin_content_lessons_levels", "admin_content", passed,
f"status={resp.status_code}, уровней={len(levels)}",
{"status": resp.status_code, "count": len(levels)},
))
assert passed
async def test_admin_content_lesson_topics(smoke_admin, smoke_conn):
"""GET /admin/content/lessons/level/A1/topics → темы A1."""
client = smoke_admin
resp = await client.get("/admin/content/lessons/level/A1/topics")
ok = resp.status_code == 200
body = resp.json() if ok else {}
topics = body.get("topics", [])
passed = ok and isinstance(topics, list)
RESULTS.append(ScenarioResult(
"admin_content_lesson_topics", "admin_content", passed,
f"status={resp.status_code}, тем A1={len(topics)}",
{"status": resp.status_code, "count": len(topics)},
))
assert passed
async def test_admin_content_lesson_detail(smoke_admin, smoke_conn):
"""GET /admin/content/lessons/lesson/{id} → урок с вопросами и опциями."""
client = smoke_admin
lesson_id = await smoke_conn.fetchval(
"SELECT lesson_id FROM learning_lessons WHERE is_active = TRUE LIMIT 1"
)
if not lesson_id:
pytest.skip("Нет уроков")
return
resp = await client.get(f"/admin/content/lessons/lesson/{lesson_id}")
ok = resp.status_code == 200
body = resp.json() if ok else {}
has_lesson = "lesson" in body
has_examples = isinstance(body.get("examples"), list)
has_questions = isinstance(body.get("questions"), list)
passed = ok and has_lesson and has_examples and has_questions
RESULTS.append(ScenarioResult(
"admin_content_lesson_detail", "admin_content", passed,
f"status={resp.status_code}, lesson={has_lesson}, examples={len(body.get('examples', []))}, questions={len(body.get('questions', []))}",
{"status": resp.status_code, "has_lesson": has_lesson, "questions_count": len(body.get("questions", []))},
))
assert passed
async def test_admin_content_wrong_because(smoke_admin):
"""GET /admin/content/wrong-because → справочник wrong_because."""
client = smoke_admin
resp = await client.get("/admin/content/wrong-because")
ok = resp.status_code == 200
body = resp.json() if ok else {}
items = body.get("items", [])
passed = ok and isinstance(items, list) and len(items) > 0
RESULTS.append(ScenarioResult(
"admin_content_wrong_because", "admin_content", passed,
f"status={resp.status_code}, записей={len(items)}",
{"status": resp.status_code, "count": len(items)},
))
assert passed
# ============================================================
# ВОЛНА 9 (подволна A3) — admin_feed (требует smoke_admin)
# ============================================================
async def test_admin_feed_section_news(smoke_admin):
"""GET /feed/news (публичный) → 200 + posts."""
client = smoke_admin
resp = await client.get("/feed/news")
ok = resp.status_code == 200
body = resp.json() if ok else {}
posts = body.get("posts")
passed = ok and isinstance(posts, list)
RESULTS.append(ScenarioResult(
"admin_feed_section_news", "admin_feed", passed,
f"status={resp.status_code}, постов={len(posts) if posts else 0}",
{"status": resp.status_code, "count": len(posts) if posts else 0},
))
assert passed
@pytest.mark.skip(reason="AI endpoint (translate) — тратит токены, запускать вручную")
async def test_admin_feed_create_post(smoke_admin, smoke_conn):
"""POST /admin/feed/post → создать пост + AI-перевод."""
client = smoke_admin
resp = await client.post(
"/admin/feed/post",
json={
"section": "news",
"source_language": "ru",
"title": "Smoke test пост",
"body": "Это тестовый пост для проверки smoke-теста.",
},
timeout=120.0,
)
ok = resp.status_code == 200
body = resp.json() if ok else {}
post_id = body.get("post_id")
# Проверка в БД
in_db = False
if post_id:
in_db = await smoke_conn.fetchval(
"SELECT 1 FROM feed_posts WHERE id = $1", post_id
) is not None
passed = ok and post_id is not None and in_db
# Cleanup поста
if post_id:
await smoke_conn.execute("DELETE FROM feed_posts WHERE id = $1", post_id)
RESULTS.append(ScenarioResult(
"admin_feed_create_post", "admin_feed", passed,
f"status={resp.status_code}, post_id={post_id}, in_db={in_db}",
{"status": resp.status_code, "post_id": post_id, "in_db": in_db},
))
assert passed
@pytest.mark.skip(reason="AI endpoint (translate) — тратит токены, запускать вручную")
async def test_admin_feed_translate(smoke_admin):
"""POST /admin/feed/translate → превью перевода (без сохранения)."""
client = smoke_admin
resp = await client.post(
"/admin/feed/translate",
json={
"title": "Тест",
"body": "Тестовый текст",
"source_language": "ru",
},
timeout=120.0,
)
ok = resp.status_code == 200
body = resp.json() if ok else {}
has_all = all(k in body for k in ["title_pl", "title_ru", "title_uk", "title_en",
"body_pl", "body_ru", "body_uk", "body_en"])
passed = ok and has_all
RESULTS.append(ScenarioResult(
"admin_feed_translate", "admin_feed", passed,
f"status={resp.status_code}, все 8 полей={has_all}",
{"status": resp.status_code, "has_all_fields": has_all},
))
assert passed
async def test_admin_feed_delete_not_found(smoke_admin):
"""POST /admin/feed/post/99999999/delete → 404 (несуществующий пост)."""
client = smoke_admin
resp = await client.post("/admin/feed/post/99999999/delete")
ok = resp.status_code == 404
passed = ok
RESULTS.append(ScenarioResult(
"admin_feed_delete_not_found", "admin_feed", passed,
f"status={resp.status_code} (ожидали 404)",
{"status": resp.status_code},
))
assert passed
async def test_admin_feed_upload_requires_post_id(smoke_admin):
"""POST /admin/feed/upload-image без post_id → 422 (валидация Form)."""
client = smoke_admin
# Отправляем без post_id и без файла — FastAPI вернёт 422
resp = await client.post("/admin/feed/upload-image")
ok = resp.status_code == 422 # Unprocessable Entity
passed = ok
RESULTS.append(ScenarioResult(
"admin_feed_upload_requires_post_id", "admin_feed", passed,
f"status={resp.status_code} (ожидали 422)",
{"status": resp.status_code},
))
assert passed
async def test_admin_feed_forbidden_for_user(smoke_user):
"""POST /admin/feed/post без прав админа → 403."""
client = smoke_user
resp = await client.post(
"/admin/feed/post",
json={
"section": "news",
"source_language": "ru",
"title": "Test",
"body": "Test",
},
)
passed = resp.status_code == 403
RESULTS.append(ScenarioResult(
"admin_feed_forbidden_for_user", "admin_feed", passed,
f"status={resp.status_code} (ожидали 403 — юзер не админ)",
{"status": resp.status_code},
))
assert passed
# ============ Отчёт ============
def _write_report() -> None: