2523 lines
92 KiB
Python
2523 lines
92 KiB
Python
"""
|
||
Smoke-test робот для Filwords PL Backend.
|
||
|
||
Диагност, не хирург: реально дёргает эндпоинты (как фронтенд) и реально
|
||
читает БД (как будто смотрит глазами). Не чинит баги, не меняет код —
|
||
только пишет отчёт, что работает, а что нет, с доказательством из БД.
|
||
|
||
Запуск: pytest tests/test_smoke.py -v
|
||
Отчёт: smoke_test_report.md (в корне репозитория, перезаписывается
|
||
при каждом прогоне)
|
||
|
||
ВАЖНО про ID: используется SMOKE_USER_ID = 9999999999 (10 девяток), а НЕ
|
||
TEST_USER_ID = 999999999 (9 девяток) из conftest.py. Это два разных ID
|
||
специально: TEST_USER_ID уже используется другими тестами через фикстуру
|
||
test_user, которая чистит более короткий список таблиц. Смешивать их —
|
||
риск ложных срабатываний в обоих наборах тестов.
|
||
|
||
ФИКС (26.09.2026): testclient_asyncpg_conflict —
|
||
TestClient (starlette) создаёт свой event loop для каждого запроса,
|
||
а asyncpg-пул привязан к event loop, в котором создан. Решение:
|
||
httpx.AsyncClient с ASGITransport.
|
||
|
||
РАСШИРЕНО (26.09.2026): волна 2 + волна 3 + волна 4 + волна 5 —
|
||
25 сценариев: игры, learning, teacher, users, achievements,
|
||
leaderboard, assistant, support, admin, feed.
|
||
|
||
РАСШИРЕНО (26.09.2026, вечер): волна 6 — добавлено 27 сценариев:
|
||
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
|
||
import json
|
||
import time
|
||
import urllib.parse
|
||
from dataclasses import dataclass, field
|
||
from datetime import datetime, timezone
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
import httpx
|
||
import pytest
|
||
|
||
from main import app
|
||
from database import get_pool
|
||
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) ============
|
||
|
||
def _build_init_data(user_id: int, first_name: str, bot_token: str) -> str:
|
||
"""Официальный алгоритм Telegram WebApp initData.
|
||
|
||
quote(..., safe='') — НЕ urlencode() — потому что auth.py декодирует
|
||
вручную через unquote(), которая не превращает '+' обратно в пробел.
|
||
"""
|
||
auth_date = int(time.time())
|
||
user_json = json.dumps(
|
||
{"id": user_id, "first_name": first_name, "language_code": "ru"},
|
||
separators=(",", ":"),
|
||
ensure_ascii=False,
|
||
)
|
||
params = {"auth_date": str(auth_date), "query_id": "AAsmoketest", "user": user_json}
|
||
check_string = "\n".join(f"{k}={v}" for k, v in sorted(params.items()))
|
||
|
||
secret_key = hmac.new(b"WebAppData", bot_token.encode(), hashlib.sha256).digest()
|
||
calc_hash = hmac.new(secret_key, check_string.encode(), hashlib.sha256).hexdigest()
|
||
params["hash"] = calc_hash
|
||
|
||
return "&".join(f"{k}={urllib.parse.quote(str(v), safe='')}" for k, v in params.items())
|
||
|
||
|
||
# ============ Результат сценария ============
|
||
|
||
@dataclass
|
||
class ScenarioResult:
|
||
name: str
|
||
section: str
|
||
passed: bool
|
||
message: str
|
||
details: dict[str, Any] = field(default_factory=dict)
|
||
|
||
|
||
RESULTS: list[ScenarioResult] = []
|
||
|
||
|
||
# ============ Очистка ============
|
||
|
||
# Порядок ВАЖЕН: сначала дочерние таблицы (которые ссылаются через FK),
|
||
# потом родительские. Иначе Postgres упадёт на ForeignKeyViolation.
|
||
#
|
||
# user_learning_answers.session_id → learning_sessions.id (FK)
|
||
# Поэтому user_learning_answers ДО learning_sessions.
|
||
NON_FK_TABLES = [
|
||
"user_learning_answers", # дочерняя (session_id → learning_sessions)
|
||
"teacher_chat_history", # независимая
|
||
"teacher_ai_usage", # независимая
|
||
"user_lesson_progress", # независимая
|
||
"user_topic_progress", # независимая
|
||
"user_skill_mastery", # независимая
|
||
"ai_user_context", # независимая
|
||
"learning_sessions", # родительская (удаляем ПОСЛЕДНЕЙ)
|
||
]
|
||
|
||
|
||
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", user_id)
|
||
|
||
await conn.execute(
|
||
"DELETE FROM support_messages WHERE ticket_id IN "
|
||
"(SELECT id FROM support_tickets WHERE user_id = $1)",
|
||
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", user_id)
|
||
|
||
|
||
async def _cleanup(conn) -> None:
|
||
"""Удаляет данные smoke_user (обратная совместимость)."""
|
||
await _cleanup_user(conn, SMOKE_USER_ID)
|
||
|
||
|
||
# ============ Фикстуры ============
|
||
|
||
@pytest.fixture(scope="session")
|
||
async def smoke_conn():
|
||
pool = await get_pool()
|
||
async with pool.acquire() as connection:
|
||
yield connection
|
||
|
||
|
||
@pytest.fixture(scope="session", autouse=True)
|
||
async def smoke_user(smoke_conn):
|
||
"""Цикл на всю сессию: удалить → зарегистрировать → (тесты) → удалить → отчёт."""
|
||
await _cleanup(smoke_conn)
|
||
|
||
init_data = _build_init_data(SMOKE_USER_ID, SMOKE_USER_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
|
||
|
||
await _cleanup(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 — игры (базовые)
|
||
# ============================================================
|
||
|
||
async def test_pronunciation_pool_stress(smoke_user):
|
||
"""30 запросов подряд — проверка утечки пула."""
|
||
client = smoke_user
|
||
N = 30
|
||
seen_words: set[str] = set()
|
||
failures = 0
|
||
|
||
for _ in range(N):
|
||
resp = await client.get("/pronunciation/next")
|
||
if resp.status_code != 200:
|
||
failures += 1
|
||
continue
|
||
body = resp.json()
|
||
word = body.get("word_pl") or body.get("word")
|
||
if word:
|
||
seen_words.add(word)
|
||
|
||
passed = failures == 0
|
||
RESULTS.append(ScenarioResult(
|
||
"pronunciation_pool_stress", "pronunciation", passed,
|
||
f"{N - failures}/{N} запросов, {len(seen_words)} уникальных слов",
|
||
{"failures": failures, "unique_words": len(seen_words)},
|
||
))
|
||
assert passed, f"{failures}/{N} запросов упали"
|
||
|
||
|
||
async def test_hints_first_letter(smoke_user, smoke_conn):
|
||
"""hints_used растёт в user_progress."""
|
||
client = smoke_user
|
||
level_id = 1
|
||
|
||
before = await smoke_conn.fetchrow(
|
||
"SELECT hints_used FROM user_progress WHERE user_id = $1 AND level_id = $2",
|
||
SMOKE_USER_ID, level_id,
|
||
)
|
||
before_count = before["hints_used"] if before else 0
|
||
|
||
resp = await client.get(f"/hints/first-letter/{level_id}")
|
||
ok = resp.status_code == 200
|
||
|
||
after = await smoke_conn.fetchrow(
|
||
"SELECT hints_used FROM user_progress WHERE user_id = $1 AND level_id = $2",
|
||
SMOKE_USER_ID, level_id,
|
||
)
|
||
after_count = after["hints_used"] if after else 0
|
||
|
||
passed = ok and after_count > before_count
|
||
RESULTS.append(ScenarioResult(
|
||
"hints_db_increment", "hints", passed,
|
||
f"GET={resp.status_code}, hints_used {before_count}→{after_count}",
|
||
{"before": before_count, "after": after_count, "status": resp.status_code},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_game_complete_level_flow(smoke_user, smoke_conn):
|
||
"""Идемпотентность + сверка score с БД."""
|
||
client = smoke_user
|
||
level_number = 1
|
||
|
||
resp_level = await client.get(f"/game/level/{level_number}")
|
||
assert resp_level.status_code == 200
|
||
level_id = resp_level.json().get("level", {}).get("id")
|
||
|
||
resp1 = await client.post("/game/complete-level", json={"level_id": level_id, "hints_used": 0})
|
||
assert resp1.status_code == 200
|
||
body1 = resp1.json()
|
||
|
||
resp2 = await client.post("/game/complete-level", json={"level_id": level_id, "hints_used": 0})
|
||
body2 = resp2.json() if resp2.status_code == 200 else {}
|
||
idempotent = bool(body2.get("already_completed"))
|
||
|
||
row = await smoke_conn.fetchrow(
|
||
"SELECT score FROM user_progress WHERE user_id = $1 AND level_id = $2",
|
||
SMOKE_USER_ID, level_id,
|
||
)
|
||
db_score = row["score"] if row else None
|
||
score_matches = db_score == body1.get("score")
|
||
|
||
passed = idempotent and score_matches
|
||
RESULTS.append(ScenarioResult(
|
||
"game_complete_level_full_flow", "game", passed,
|
||
f"idempotent={idempotent}, api={body1.get('score')}, db={db_score}",
|
||
{"api_score": body1.get("score"), "db_score": db_score, "idempotent": idempotent},
|
||
))
|
||
assert passed
|
||
|
||
|
||
# ============================================================
|
||
# ВОЛНА 2 — остальные игры
|
||
# ============================================================
|
||
|
||
async def test_wordquiz_correct_answer(smoke_user, smoke_conn):
|
||
client = smoke_user
|
||
|
||
before = await smoke_conn.fetchval(
|
||
"SELECT total_score FROM word_quiz_progress WHERE user_id = $1", SMOKE_USER_ID
|
||
) or 0
|
||
|
||
resp = await client.post(
|
||
"/wordquiz/check",
|
||
json={"correct_polish": "kot", "answer": "kot", "completion_time": 5},
|
||
)
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
after = await smoke_conn.fetchval(
|
||
"SELECT total_score FROM word_quiz_progress WHERE user_id = $1", SMOKE_USER_ID
|
||
) or 0
|
||
|
||
correct_flag = body.get("correct") is True
|
||
score_grew = after > before
|
||
passed = ok and correct_flag and score_grew
|
||
|
||
RESULTS.append(ScenarioResult(
|
||
"wordquiz_correct_answer", "wordquiz", passed,
|
||
f"status={resp.status_code}, correct={correct_flag}, score {before}→{after}",
|
||
{"before": before, "after": after, "correct": correct_flag},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_wordquiz_wrong_answer(smoke_user, smoke_conn):
|
||
client = smoke_user
|
||
|
||
before = await smoke_conn.fetchval(
|
||
"SELECT current_mistakes FROM word_quiz_progress WHERE user_id = $1", SMOKE_USER_ID
|
||
) or 0
|
||
|
||
resp = await client.post(
|
||
"/wordquiz/check",
|
||
json={"correct_polish": "kot", "answer": "pies", "completion_time": 5},
|
||
)
|
||
ok = resp.status_code == 200
|
||
|
||
after = await smoke_conn.fetchval(
|
||
"SELECT current_mistakes FROM word_quiz_progress WHERE user_id = $1", SMOKE_USER_ID
|
||
) or 0
|
||
|
||
passed = ok and after > before
|
||
RESULTS.append(ScenarioResult(
|
||
"wordquiz_wrong_answer", "wordquiz", passed,
|
||
f"status={resp.status_code}, mistakes {before}→{after}",
|
||
{"before": before, "after": after},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_bubblewords_complete_flow(smoke_user, smoke_conn):
|
||
client = smoke_user
|
||
|
||
before = await smoke_conn.fetchrow(
|
||
"SELECT levels_completed, total_score FROM bubble_words_progress WHERE user_id = $1",
|
||
SMOKE_USER_ID,
|
||
)
|
||
bl = before["levels_completed"] if before else 0
|
||
bs = before["total_score"] if before else 0
|
||
|
||
resp = await client.post(
|
||
"/bubblewords/complete",
|
||
json={"words_count": 3, "completion_time": 30},
|
||
)
|
||
ok = resp.status_code == 200
|
||
|
||
after = await smoke_conn.fetchrow(
|
||
"SELECT levels_completed, total_score FROM bubble_words_progress WHERE user_id = $1",
|
||
SMOKE_USER_ID,
|
||
)
|
||
al = after["levels_completed"] if after else 0
|
||
as_ = after["total_score"] if after else 0
|
||
|
||
passed = ok and al > bl and as_ > bs
|
||
RESULTS.append(ScenarioResult(
|
||
"bubblewords_complete_flow", "bubblewords", passed,
|
||
f"status={resp.status_code}, levels {bl}→{al}, score {bs}→{as_}",
|
||
{"before_levels": bl, "after_levels": al, "before_score": bs, "after_score": as_},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_sentences_check_wrong(smoke_user, smoke_conn):
|
||
client = smoke_user
|
||
|
||
sentence_row = await smoke_conn.fetchrow(
|
||
"SELECT id FROM sentences ORDER BY id LIMIT 1"
|
||
)
|
||
if not sentence_row:
|
||
pytest.skip("Нет предложений для теста")
|
||
return
|
||
|
||
sentence_id = sentence_row["id"]
|
||
before = await smoke_conn.fetchval(
|
||
"SELECT score FROM sentence_progress WHERE user_id = $1 AND sentence_id = $2",
|
||
SMOKE_USER_ID, sentence_id,
|
||
) or 0
|
||
|
||
resp = await client.post(
|
||
"/sentences/check",
|
||
json={
|
||
"sentence_id": sentence_id,
|
||
"words": ["nie", "ma", "takiego", "slowa"],
|
||
"completion_time": 10,
|
||
},
|
||
)
|
||
ok = resp.status_code == 200
|
||
|
||
after = await smoke_conn.fetchval(
|
||
"SELECT score FROM sentence_progress WHERE user_id = $1 AND sentence_id = $2",
|
||
SMOKE_USER_ID, sentence_id,
|
||
) or 0
|
||
|
||
passed = ok and after == before
|
||
RESULTS.append(ScenarioResult(
|
||
"sentences_check_wrong", "sentences", passed,
|
||
f"status={resp.status_code}, score {before}→{after} (неверный)",
|
||
{"before": before, "after": after},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_typing_progress_flow(smoke_user, smoke_conn):
|
||
client = smoke_user
|
||
|
||
resp_next = await client.get("/typing/next")
|
||
if resp_next.status_code != 200:
|
||
pytest.skip(f"GET /typing/next вернул {resp_next.status_code}")
|
||
return
|
||
|
||
body = resp_next.json()
|
||
if body.get("completed") is True:
|
||
RESULTS.append(ScenarioResult(
|
||
"typing_progress_flow", "typing", True,
|
||
"Все предложения пройдены", {"completed": True},
|
||
))
|
||
pytest.skip("Все предложения пройдены")
|
||
return
|
||
|
||
sentence_id = body.get("sentence_id")
|
||
if not sentence_id:
|
||
pytest.skip("Нет sentence_id")
|
||
return
|
||
|
||
sentence_pl = await smoke_conn.fetchval(
|
||
"SELECT sentence_pl FROM sentences WHERE id = $1", sentence_id,
|
||
)
|
||
if not sentence_pl:
|
||
pytest.skip("Нет sentence_pl в БД")
|
||
return
|
||
|
||
resp_check = await client.post(
|
||
"/typing/check",
|
||
json={"sentence_id": sentence_id, "text": sentence_pl},
|
||
)
|
||
ok = resp_check.status_code == 200
|
||
|
||
row = await smoke_conn.fetchrow(
|
||
"SELECT completed_at FROM typing_progress WHERE user_id = $1 AND sentence_id = $2",
|
||
SMOKE_USER_ID, sentence_id,
|
||
)
|
||
recorded = row is not None and row["completed_at"] is not None
|
||
passed = ok and recorded
|
||
|
||
RESULTS.append(ScenarioResult(
|
||
"typing_progress_flow", "typing", passed,
|
||
f"status={resp_check.status_code}, sentence_id={sentence_id}, recorded={recorded}",
|
||
{"status": resp_check.status_code, "recorded": recorded},
|
||
))
|
||
assert passed
|
||
|
||
|
||
# ============================================================
|
||
# ВОЛНА 2 — пользователь и достижения
|
||
# ============================================================
|
||
|
||
async def test_users_set_language(smoke_user, smoke_conn):
|
||
client = smoke_user
|
||
|
||
before = await smoke_conn.fetchval(
|
||
"SELECT app_language FROM users WHERE telegram_id = $1", SMOKE_USER_ID,
|
||
)
|
||
new_lang = "ru" if before != "ru" else "en"
|
||
|
||
resp = await client.post("/users/set-language", json={"language": new_lang})
|
||
ok = resp.status_code == 200
|
||
|
||
after = await smoke_conn.fetchval(
|
||
"SELECT app_language FROM users WHERE telegram_id = $1", SMOKE_USER_ID,
|
||
)
|
||
|
||
passed = ok and after == new_lang
|
||
RESULTS.append(ScenarioResult(
|
||
"users_set_language", "users", passed,
|
||
f"status={resp.status_code}, lang {before}→{after}",
|
||
{"before": before, "after": after, "expected": new_lang},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_achievements_track_login(smoke_user, smoke_conn):
|
||
client = smoke_user
|
||
|
||
before = await smoke_conn.fetchval(
|
||
"SELECT COUNT(*) FROM daily_logins WHERE user_id = $1", SMOKE_USER_ID,
|
||
) or 0
|
||
|
||
resp = await client.post("/achievements/track-login")
|
||
ok = resp.status_code == 200
|
||
|
||
after = await smoke_conn.fetchval(
|
||
"SELECT COUNT(*) FROM daily_logins WHERE user_id = $1", SMOKE_USER_ID,
|
||
) or 0
|
||
|
||
passed = ok and after > before
|
||
RESULTS.append(ScenarioResult(
|
||
"achievements_track_login", "achievements", passed,
|
||
f"status={resp.status_code}, logins {before}→{after}",
|
||
{"before": before, "after": after},
|
||
))
|
||
assert passed
|
||
|
||
|
||
# ============================================================
|
||
# ВОЛНА 3 — learning
|
||
# ============================================================
|
||
|
||
async def test_learning_levels_list(smoke_user):
|
||
"""GET /learning/levels → список уровней."""
|
||
client = smoke_user
|
||
resp = await client.get("/learning/levels")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
levels = body.get("levels", [])
|
||
|
||
passed = ok and len(levels) > 0
|
||
RESULTS.append(ScenarioResult(
|
||
"learning_levels_list", "learning", passed,
|
||
f"status={resp.status_code}, уровней={len(levels)}",
|
||
{"status": resp.status_code, "count": len(levels)},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_learning_topics_list(smoke_user):
|
||
"""GET /learning/topics?level=A1 → список тем."""
|
||
client = smoke_user
|
||
resp = await client.get("/learning/topics?level=A1")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
topics = body.get("topics", [])
|
||
|
||
passed = ok and len(topics) > 0
|
||
RESULTS.append(ScenarioResult(
|
||
"learning_topics_list", "learning", passed,
|
||
f"status={resp.status_code}, тем A1={len(topics)}",
|
||
{"status": resp.status_code, "count": len(topics)},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_learning_topic_detail(smoke_user, smoke_conn):
|
||
"""GET /learning/topics/{topic_id} → тема + уроки."""
|
||
client = smoke_user
|
||
|
||
topic_row = await smoke_conn.fetchrow(
|
||
"SELECT topic_id FROM learning_topics WHERE level_code = 'A1' AND is_active = TRUE ORDER BY order_number LIMIT 1"
|
||
)
|
||
if not topic_row:
|
||
pytest.skip("Нет тем A1")
|
||
return
|
||
|
||
topic_id = topic_row["topic_id"]
|
||
resp = await client.get(f"/learning/topics/{topic_id}")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
lessons = body.get("lessons", [])
|
||
|
||
passed = ok and "topic" in body
|
||
RESULTS.append(ScenarioResult(
|
||
"learning_topic_detail", "learning", passed,
|
||
f"status={resp.status_code}, topic_id={topic_id}, уроков={len(lessons)}",
|
||
{"status": resp.status_code, "lessons": len(lessons)},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_learning_session_start(smoke_user, smoke_conn):
|
||
"""POST /learning/session/start → session_id в БД."""
|
||
client = smoke_user
|
||
|
||
topic_row = await smoke_conn.fetchrow(
|
||
"SELECT topic_id FROM learning_topics WHERE level_code = 'A1' AND is_active = TRUE ORDER BY order_number LIMIT 1"
|
||
)
|
||
if not topic_row:
|
||
pytest.skip("Нет тем A1")
|
||
return
|
||
|
||
topic_id = topic_row["topic_id"]
|
||
|
||
resp = await client.post(
|
||
"/learning/session/start",
|
||
json={"level_code": "A1", "topic_id": topic_id, "session_type": "lesson"},
|
||
)
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
session_id = body.get("session_id")
|
||
|
||
recorded = False
|
||
if session_id:
|
||
row = await smoke_conn.fetchrow(
|
||
"SELECT id FROM learning_sessions WHERE id = $1 AND user_id = $2",
|
||
session_id, SMOKE_USER_ID,
|
||
)
|
||
recorded = row is not None
|
||
|
||
passed = ok and recorded
|
||
RESULTS.append(ScenarioResult(
|
||
"learning_session_start", "learning", passed,
|
||
f"status={resp.status_code}, session_id={session_id}, в БД={recorded}",
|
||
{"status": resp.status_code, "session_id": session_id, "recorded": recorded},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_learning_session_full_flow(smoke_user, smoke_conn):
|
||
"""Полный цикл: start → answer → complete."""
|
||
client = smoke_user
|
||
|
||
topic_row = await smoke_conn.fetchrow(
|
||
"SELECT topic_id FROM learning_topics WHERE level_code = 'A1' AND is_active = TRUE ORDER BY order_number LIMIT 1"
|
||
)
|
||
if not topic_row:
|
||
pytest.skip("Нет тем A1")
|
||
return
|
||
|
||
topic_id = topic_row["topic_id"]
|
||
|
||
# 1. Start
|
||
resp_start = await client.post(
|
||
"/learning/session/start",
|
||
json={"level_code": "A1", "topic_id": topic_id, "session_type": "lesson"},
|
||
)
|
||
assert resp_start.status_code == 200, f"start вернул {resp_start.status_code}"
|
||
session_id = resp_start.json()["session_id"]
|
||
|
||
# 2. Берём первый вопрос урока
|
||
question_row = await smoke_conn.fetchrow(
|
||
"""
|
||
SELECT q.question_id, q.correct_answer
|
||
FROM learning_questions q
|
||
JOIN learning_lessons l ON q.lesson_id = l.lesson_id
|
||
WHERE l.topic_id = $1 AND q.is_test_question = FALSE
|
||
ORDER BY q.id LIMIT 1
|
||
""",
|
||
topic_id,
|
||
)
|
||
if not question_row:
|
||
pytest.skip("Нет вопросов для темы")
|
||
return
|
||
|
||
question_id = question_row["question_id"]
|
||
correct = question_row["correct_answer"] or ""
|
||
|
||
# 3. Answer
|
||
resp_ans = await client.post(
|
||
"/learning/answer",
|
||
json={
|
||
"session_id": session_id,
|
||
"question_id": question_id,
|
||
"answer": correct,
|
||
"time_taken_ms": 3000,
|
||
"is_final_answer": True,
|
||
"hint_used": False,
|
||
},
|
||
)
|
||
ans_ok = resp_ans.status_code == 200
|
||
ans_body = resp_ans.json() if ans_ok else {}
|
||
|
||
# Проверяем, что ответ записан
|
||
answer_row = await smoke_conn.fetchrow(
|
||
"SELECT id, correct FROM user_learning_answers WHERE session_id = $1 AND question_id = $2",
|
||
session_id, question_id,
|
||
)
|
||
answer_recorded = answer_row is not None
|
||
|
||
# 4. Complete
|
||
resp_complete = await client.post(
|
||
"/learning/session/complete",
|
||
json={"session_id": session_id},
|
||
)
|
||
complete_ok = resp_complete.status_code == 200
|
||
|
||
session_completed = await smoke_conn.fetchval(
|
||
"SELECT is_completed FROM learning_sessions WHERE id = $1",
|
||
session_id,
|
||
)
|
||
|
||
passed = ans_ok and answer_recorded and complete_ok and session_completed is True
|
||
RESULTS.append(ScenarioResult(
|
||
"learning_session_full_flow", "learning", passed,
|
||
f"answer={ans_ok}, recorded={answer_recorded}, complete={complete_ok}, is_completed={session_completed}",
|
||
{
|
||
"answer_ok": ans_ok, "answer_recorded": answer_recorded,
|
||
"complete_ok": complete_ok, "is_completed": session_completed,
|
||
"answer_correct": ans_body.get("correct"),
|
||
},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_learning_progress(smoke_user):
|
||
"""GET /learning/progress → 200 + progress."""
|
||
client = smoke_user
|
||
resp = await client.get("/learning/progress")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
progress = body.get("progress", [])
|
||
|
||
passed = ok and isinstance(progress, list)
|
||
RESULTS.append(ScenarioResult(
|
||
"learning_progress", "learning", passed,
|
||
f"status={resp.status_code}, тем={len(progress)}",
|
||
{"status": resp.status_code, "count": len(progress)},
|
||
))
|
||
assert passed
|
||
|
||
|
||
# 🔧 НОВОЕ (26.09.2026): волна 6 — дополнительные learning-сценарии
|
||
|
||
async def test_learning_lesson_detail(smoke_user, smoke_conn):
|
||
"""GET /learning/lessons/{lesson_id} → урок + вопросы + примеры."""
|
||
client = smoke_user
|
||
|
||
lesson_row = await smoke_conn.fetchrow(
|
||
"SELECT lesson_id FROM learning_lessons WHERE is_active = TRUE LIMIT 1"
|
||
)
|
||
if not lesson_row:
|
||
pytest.skip("Нет активных уроков")
|
||
return
|
||
|
||
lesson_id = lesson_row["lesson_id"]
|
||
resp = await client.get(f"/learning/lessons/{lesson_id}")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
has_lesson = "lesson" in body
|
||
has_questions = isinstance(body.get("questions"), list)
|
||
has_examples = isinstance(body.get("examples"), list)
|
||
|
||
passed = ok and has_lesson and has_questions and has_examples
|
||
RESULTS.append(ScenarioResult(
|
||
"learning_lesson_detail", "learning", passed,
|
||
f"status={resp.status_code}, lesson={has_lesson}, questions={has_questions}, examples={has_examples}",
|
||
{
|
||
"status": resp.status_code,
|
||
"has_lesson": has_lesson,
|
||
"has_questions": has_questions,
|
||
"has_examples": has_examples,
|
||
"questions_count": len(body.get("questions", [])),
|
||
},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_learning_topic_test(smoke_user, smoke_conn):
|
||
"""GET /learning/test/{topic_id} → список вопросов теста."""
|
||
client = smoke_user
|
||
|
||
topic_row = await smoke_conn.fetchrow(
|
||
"SELECT topic_id FROM learning_topics WHERE level_code = 'A1' AND is_active = TRUE LIMIT 1"
|
||
)
|
||
if not topic_row:
|
||
pytest.skip("Нет тем A1")
|
||
return
|
||
|
||
topic_id = topic_row["topic_id"]
|
||
resp = await client.get(f"/learning/test/{topic_id}")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
has_test = isinstance(body.get("test"), list)
|
||
has_total = isinstance(body.get("total"), int)
|
||
|
||
passed = ok and has_test and has_total
|
||
RESULTS.append(ScenarioResult(
|
||
"learning_topic_test", "learning", passed,
|
||
f"status={resp.status_code}, test={has_test}, total={body.get('total')}",
|
||
{"status": resp.status_code, "has_test": has_test, "total": body.get("total")},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_learning_ai_context(smoke_user):
|
||
"""GET /learning/ai/context → 200 + analytics_enabled / context / message."""
|
||
client = smoke_user
|
||
resp = await client.get("/learning/ai/context")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
# Может вернуть: {analytics_enabled: False, message: ...} ИЛИ {context: {...}}
|
||
has_analytics = "analytics_enabled" in body
|
||
has_context = "context" in body
|
||
has_message = "message" in body
|
||
valid = has_analytics or has_context or has_message
|
||
|
||
passed = ok and valid
|
||
RESULTS.append(ScenarioResult(
|
||
"learning_ai_context", "learning", passed,
|
||
f"status={resp.status_code}, analytics={has_analytics}, context={has_context}, message={has_message}",
|
||
{
|
||
"status": resp.status_code,
|
||
"has_analytics": has_analytics,
|
||
"has_context": has_context,
|
||
"has_message": has_message,
|
||
},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_learning_practice_start(smoke_user, smoke_conn):
|
||
"""POST /learning/practice/start → сессия практики (без AI)."""
|
||
client = smoke_user
|
||
|
||
resp = await client.post("/learning/practice/start", json={})
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
has_weak_skills = isinstance(body.get("has_weak_skills"), bool)
|
||
|
||
if has_weak_skills and body.get("has_weak_skills") is True:
|
||
has_session = body.get("session_id") is not None
|
||
has_questions = isinstance(body.get("questions"), list)
|
||
valid = has_session and has_questions
|
||
extra = {"session_id": body.get("session_id"), "questions_count": len(body.get("questions", []))}
|
||
else:
|
||
# has_weak_skills == False → должно быть message
|
||
has_message = isinstance(body.get("message"), str)
|
||
valid = has_message
|
||
extra = {"message": body.get("message")}
|
||
|
||
passed = ok and has_weak_skills and valid
|
||
RESULTS.append(ScenarioResult(
|
||
"learning_practice_start", "learning", passed,
|
||
f"status={resp.status_code}, has_weak_skills={body.get('has_weak_skills')}",
|
||
{"status": resp.status_code, "has_weak_skills": body.get("has_weak_skills"), **extra},
|
||
))
|
||
assert passed
|
||
|
||
|
||
@pytest.mark.skip(reason="AI endpoint — тратит токены, запускать вручную")
|
||
async def test_learning_analytics(smoke_user):
|
||
"""POST /learning/analytics → вызывает AI (MiniMax-M3), может занять 10-90с."""
|
||
client = smoke_user
|
||
|
||
try:
|
||
resp = await client.post("/learning/analytics", json={}, timeout=120.0)
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
has_analytics = "analytics_enabled" in body
|
||
|
||
passed = ok and has_analytics
|
||
RESULTS.append(ScenarioResult(
|
||
"learning_analytics", "learning_ai", passed,
|
||
f"status={resp.status_code}, analytics_enabled={body.get('analytics_enabled')}",
|
||
{"status": resp.status_code, "has_analytics": has_analytics},
|
||
))
|
||
assert passed
|
||
except (httpx.TimeoutException, httpx.ReadTimeout) as e:
|
||
# AI тормозит — не баг, просто пропускаем
|
||
RESULTS.append(ScenarioResult(
|
||
"learning_analytics", "learning_ai", True,
|
||
f"AI timeout — пропущено (не баг): {e}",
|
||
{"error": str(e)},
|
||
))
|
||
pytest.skip(f"AI timeout: {e}")
|
||
|
||
|
||
# ============================================================
|
||
# ВОЛНА 3 — teacher
|
||
# ============================================================
|
||
|
||
async def test_teacher_progress(smoke_user):
|
||
"""GET /teacher/progress → 200 + levels."""
|
||
client = smoke_user
|
||
resp = await client.get("/teacher/progress")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
levels = body.get("levels", [])
|
||
|
||
passed = ok and len(levels) > 0
|
||
RESULTS.append(ScenarioResult(
|
||
"teacher_progress", "teacher", passed,
|
||
f"status={resp.status_code}, уровней={len(levels)}",
|
||
{"status": resp.status_code, "count": len(levels)},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_teacher_phrase_of_day(smoke_user):
|
||
"""GET /teacher/phrase-of-day → 200 + phrase_pl."""
|
||
client = smoke_user
|
||
resp = await client.get("/teacher/phrase-of-day")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
phrase = body.get("phrase_pl")
|
||
|
||
passed = ok and bool(phrase)
|
||
RESULTS.append(ScenarioResult(
|
||
"teacher_phrase_of_day", "teacher", passed,
|
||
f"status={resp.status_code}, phrase={(phrase or '')[:40]}",
|
||
{"status": resp.status_code, "has_phrase": bool(phrase)},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_teacher_start_or_resume(smoke_user, smoke_conn):
|
||
"""POST /teacher/start → lesson_explanation или test_start."""
|
||
client = smoke_user
|
||
|
||
resp = await client.post("/teacher/start")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
msg_type = body.get("message_type")
|
||
|
||
# Может быть: lesson_explanation, test_start, completed, error
|
||
valid = msg_type in ("lesson_explanation", "test_start", "completed")
|
||
passed = ok and valid
|
||
|
||
# Если сессия создана — проверим в БД
|
||
session_id = body.get("session_id")
|
||
session_recorded = False
|
||
if session_id:
|
||
row = await smoke_conn.fetchrow(
|
||
"SELECT id FROM learning_sessions WHERE id = $1 AND user_id = $2",
|
||
session_id, SMOKE_USER_ID,
|
||
)
|
||
session_recorded = row is not None
|
||
|
||
RESULTS.append(ScenarioResult(
|
||
"teacher_start_or_resume", "teacher", passed,
|
||
f"status={resp.status_code}, type={msg_type}, session_recorded={session_recorded}",
|
||
{"status": resp.status_code, "message_type": msg_type, "session_id": session_id},
|
||
))
|
||
assert passed
|
||
|
||
|
||
# 🔧 НОВОЕ (26.09.2026): волна 6 — дополнительные teacher-сценарии
|
||
|
||
async def test_teacher_resume_no_session(smoke_user):
|
||
"""POST /teacher/resume → has_active_session (bool)."""
|
||
client = smoke_user
|
||
resp = await client.post("/teacher/resume")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
has_flag = isinstance(body.get("has_active_session"), bool)
|
||
passed = ok and has_flag
|
||
|
||
RESULTS.append(ScenarioResult(
|
||
"teacher_resume_no_session", "teacher", passed,
|
||
f"status={resp.status_code}, has_active_session={body.get('has_active_session')}",
|
||
{"status": resp.status_code, "has_active_session": body.get("has_active_session")},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_teacher_diagnostic_test(smoke_user, smoke_conn):
|
||
"""POST /teacher/diagnostic-test → session_id + questions, сессия в БД."""
|
||
client = smoke_user
|
||
resp = await client.post("/teacher/diagnostic-test")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
session_id = body.get("session_id")
|
||
questions = body.get("questions", [])
|
||
has_questions = len(questions) > 0
|
||
|
||
# Проверка в БД
|
||
session_type = None
|
||
if session_id:
|
||
session_type = await smoke_conn.fetchval(
|
||
"SELECT session_type FROM learning_sessions WHERE id = $1 AND user_id = $2",
|
||
session_id, SMOKE_USER_ID,
|
||
)
|
||
|
||
passed = ok and session_id is not None and has_questions and session_type == "diagnostic_test"
|
||
RESULTS.append(ScenarioResult(
|
||
"teacher_diagnostic_test", "teacher", passed,
|
||
f"status={resp.status_code}, session_id={session_id}, questions={len(questions)}, type={session_type}",
|
||
{
|
||
"status": resp.status_code,
|
||
"session_id": session_id,
|
||
"questions_count": len(questions),
|
||
"session_type": session_type,
|
||
},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_teacher_answer_flow(smoke_user, smoke_conn):
|
||
"""POST /teacher/start → POST /teacher/answer (правильный ответ)."""
|
||
client = smoke_user
|
||
|
||
# 1. Start
|
||
resp_start = await client.post("/teacher/start")
|
||
assert resp_start.status_code == 200, f"start вернул {resp_start.status_code}"
|
||
body_start = resp_start.json()
|
||
|
||
session_id = body_start.get("session_id")
|
||
question_data = body_start.get("question")
|
||
|
||
if not session_id or not question_data:
|
||
pytest.skip(f"Нет активной сессии: message_type={body_start.get('message_type')}")
|
||
return
|
||
|
||
question_id = question_data.get("question", {}).get("question_id")
|
||
if not question_id:
|
||
pytest.skip("Нет question_id в ответе /teacher/start")
|
||
return
|
||
|
||
# 2. Правильный ответ из БД
|
||
correct = await smoke_conn.fetchval(
|
||
"SELECT correct_answer FROM learning_questions WHERE question_id = $1",
|
||
question_id,
|
||
)
|
||
if not correct:
|
||
pytest.skip("Нет correct_answer в БД")
|
||
return
|
||
|
||
# 3. Answer
|
||
resp_ans = await client.post(
|
||
"/teacher/answer",
|
||
json={
|
||
"session_id": session_id,
|
||
"question_id": question_id,
|
||
"answer": correct,
|
||
"time_taken_ms": 3000,
|
||
},
|
||
)
|
||
ok = resp_ans.status_code == 200
|
||
body_ans = resp_ans.json() if ok else {}
|
||
|
||
has_reaction = "reaction" in body_ans
|
||
has_is_correct = "is_correct" in body_ans
|
||
|
||
# Проверка в БД
|
||
answer_recorded = await smoke_conn.fetchval(
|
||
"SELECT 1 FROM user_learning_answers WHERE session_id = $1 AND question_id = $2",
|
||
session_id, question_id,
|
||
) is not None
|
||
|
||
passed = ok and has_reaction and has_is_correct and answer_recorded
|
||
RESULTS.append(ScenarioResult(
|
||
"teacher_answer_flow", "teacher", passed,
|
||
f"status={resp_ans.status_code}, reaction={has_reaction}, is_correct={body_ans.get('is_correct')}, recorded={answer_recorded}",
|
||
{
|
||
"status": resp_ans.status_code,
|
||
"has_reaction": has_reaction,
|
||
"is_correct": body_ans.get("is_correct"),
|
||
"answer_recorded": answer_recorded,
|
||
},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_teacher_history_save_load(smoke_user):
|
||
"""POST /teacher/history/save → GET /teacher/history/load."""
|
||
client = smoke_user
|
||
|
||
messages = [
|
||
{"role": "user", "content": "smoke test message"},
|
||
{"role": "assistant", "content": "smoke test reply"},
|
||
]
|
||
|
||
resp_save = await client.post("/teacher/history/save", json={"messages": messages})
|
||
save_ok = resp_save.status_code == 200
|
||
|
||
resp_load = await client.get("/teacher/history/load")
|
||
load_ok = resp_load.status_code == 200
|
||
body_load = resp_load.json() if load_ok else {}
|
||
loaded = body_load.get("messages", [])
|
||
|
||
passed = save_ok and load_ok and loaded == messages
|
||
RESULTS.append(ScenarioResult(
|
||
"teacher_history_save_load", "teacher", passed,
|
||
f"save={save_ok}, load={load_ok}, messages_match={loaded == messages}",
|
||
{"save_status": resp_save.status_code, "load_status": resp_load.status_code, "loaded_count": len(loaded)},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_teacher_history_clear(smoke_user, smoke_conn):
|
||
"""POST /teacher/history/clear → история пуста в БД."""
|
||
client = smoke_user
|
||
|
||
resp = await client.post("/teacher/history/clear")
|
||
ok = resp.status_code == 200
|
||
|
||
# Проверка в БД
|
||
remaining = await smoke_conn.fetchval(
|
||
"SELECT COUNT(*) FROM teacher_chat_history WHERE user_id = $1",
|
||
SMOKE_USER_ID,
|
||
) or 0
|
||
|
||
passed = ok and remaining == 0
|
||
RESULTS.append(ScenarioResult(
|
||
"teacher_history_clear", "teacher", passed,
|
||
f"status={resp.status_code}, remaining={remaining}",
|
||
{"status": resp.status_code, "remaining": remaining},
|
||
))
|
||
assert passed
|
||
|
||
|
||
@pytest.mark.skip(reason="AI endpoint — тратит токены, запускать вручную")
|
||
async def test_teacher_free_message_limit(smoke_user):
|
||
"""POST /teacher/free-message → AI ответ или limit_exceeded."""
|
||
client = smoke_user
|
||
try:
|
||
resp = await client.post(
|
||
"/teacher/free-message",
|
||
json={"message": "test"},
|
||
timeout=120.0,
|
||
)
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
has_response = bool(body.get("response"))
|
||
has_limit = body.get("limit_exceeded") is True
|
||
|
||
passed = ok and (has_response or has_limit)
|
||
RESULTS.append(ScenarioResult(
|
||
"teacher_free_message_limit", "teacher_ai", passed,
|
||
f"status={resp.status_code}, response={has_response}, limit={has_limit}",
|
||
{"status": resp.status_code, "has_response": has_response, "limit_exceeded": has_limit},
|
||
))
|
||
assert passed
|
||
except (httpx.TimeoutException, httpx.ReadTimeout) as e:
|
||
RESULTS.append(ScenarioResult(
|
||
"teacher_free_message_limit", "teacher_ai", True,
|
||
f"AI timeout — пропущено (не баг): {e}",
|
||
{"error": str(e)},
|
||
))
|
||
pytest.skip(f"AI timeout: {e}")
|
||
|
||
|
||
@pytest.mark.skip(reason="AI endpoint — тратит токены, запускать вручную")
|
||
async def test_teacher_translate_to_polish(smoke_user):
|
||
"""POST /teacher/translate-to-polish → AI перевод."""
|
||
client = smoke_user
|
||
try:
|
||
resp = await client.post(
|
||
"/teacher/translate-to-polish",
|
||
json={"text": "привет"},
|
||
timeout=120.0,
|
||
)
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
has_response = bool(body.get("response"))
|
||
has_limit = body.get("limit_exceeded") is True
|
||
|
||
passed = ok and (has_response or has_limit)
|
||
RESULTS.append(ScenarioResult(
|
||
"teacher_translate_to_polish", "teacher_ai", passed,
|
||
f"status={resp.status_code}, response={has_response}, limit={has_limit}",
|
||
{"status": resp.status_code, "has_response": has_response, "limit_exceeded": has_limit},
|
||
))
|
||
assert passed
|
||
except (httpx.TimeoutException, httpx.ReadTimeout) as e:
|
||
RESULTS.append(ScenarioResult(
|
||
"teacher_translate_to_polish", "teacher_ai", True,
|
||
f"AI timeout — пропущено (не баг): {e}",
|
||
{"error": str(e)},
|
||
))
|
||
pytest.skip(f"AI timeout: {e}")
|
||
|
||
|
||
@pytest.mark.skip(reason="AI endpoint — тратит токены, запускать вручную")
|
||
async def test_teacher_explain(smoke_user, smoke_conn):
|
||
"""POST /teacher/explain → AI объяснение."""
|
||
client = smoke_user
|
||
|
||
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
|
||
|
||
try:
|
||
resp = await client.post(
|
||
"/teacher/explain",
|
||
json={"lesson_id": lesson_id},
|
||
timeout=120.0,
|
||
)
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
has_response = bool(body.get("response")) or body.get("limit_exceeded") is True
|
||
|
||
passed = ok and has_response
|
||
RESULTS.append(ScenarioResult(
|
||
"teacher_explain", "teacher_ai", passed,
|
||
f"status={resp.status_code}, has_response={bool(body.get('response'))}",
|
||
{"status": resp.status_code, "has_response": bool(body.get("response"))},
|
||
))
|
||
assert passed
|
||
except (httpx.TimeoutException, httpx.ReadTimeout) as e:
|
||
RESULTS.append(ScenarioResult(
|
||
"teacher_explain", "teacher_ai", True,
|
||
f"AI timeout — пропущено (не баг): {e}",
|
||
{"error": str(e)},
|
||
))
|
||
pytest.skip(f"AI timeout: {e}")
|
||
|
||
|
||
# ============================================================
|
||
# ВОЛНА 3 — leaderboard
|
||
# ============================================================
|
||
|
||
async def test_leaderboard_top(smoke_user):
|
||
"""GET /leaderboard/top → 200 + top3."""
|
||
client = smoke_user
|
||
resp = await client.get("/leaderboard/top")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
top3 = body.get("top3", [])
|
||
|
||
passed = ok and isinstance(top3, list)
|
||
RESULTS.append(ScenarioResult(
|
||
"leaderboard_top", "leaderboard", passed,
|
||
f"status={resp.status_code}, top3={len(top3)}",
|
||
{"status": resp.status_code, "count": len(top3)},
|
||
))
|
||
assert passed
|
||
|
||
|
||
# ============================================================
|
||
# ВОЛНА 4 — assistant
|
||
# ============================================================
|
||
|
||
async def test_assistant_limit(smoke_user):
|
||
"""GET /assistant/limit → 200 + daily_limit."""
|
||
client = smoke_user
|
||
resp = await client.get("/assistant/limit")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
has_fields = "is_admin" in body and "used" in body
|
||
passed = ok and has_fields
|
||
RESULTS.append(ScenarioResult(
|
||
"assistant_limit", "assistant", passed,
|
||
f"status={resp.status_code}, is_admin={body.get('is_admin')}, used={body.get('used')}",
|
||
{"status": resp.status_code, "body_keys": list(body.keys())},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_assistant_history(smoke_user):
|
||
"""GET /assistant/history → 200 + history (может быть пустой)."""
|
||
client = smoke_user
|
||
resp = await client.get("/assistant/history")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
history = body.get("history")
|
||
|
||
passed = ok and isinstance(history, list)
|
||
RESULTS.append(ScenarioResult(
|
||
"assistant_history", "assistant", passed,
|
||
f"status={resp.status_code}, сообщений={len(history) if history else 0}",
|
||
{"status": resp.status_code, "count": len(history) if history else 0},
|
||
))
|
||
assert passed
|
||
|
||
|
||
# 🔧 НОВОЕ (26.09.2026): волна 6 — assistant stats
|
||
|
||
async def test_assistant_stats_personal(smoke_user):
|
||
"""GET /assistant/stats/personal → личная статистика."""
|
||
client = smoke_user
|
||
resp = await client.get("/assistant/stats/personal")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
has_current_level = "current_level" in body
|
||
has_total_score = "total_score" in body
|
||
has_achievements = "achievements" in body
|
||
valid = has_current_level and has_total_score and has_achievements
|
||
|
||
passed = ok and valid
|
||
RESULTS.append(ScenarioResult(
|
||
"assistant_stats_personal", "assistant", passed,
|
||
f"status={resp.status_code}, level={body.get('current_level')}, score={body.get('total_score')}",
|
||
{
|
||
"status": resp.status_code,
|
||
"has_current_level": has_current_level,
|
||
"has_total_score": has_total_score,
|
||
"has_achievements": has_achievements,
|
||
},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_assistant_stats_admin_forbidden(smoke_user):
|
||
"""GET /assistant/stats/admin без админ-прав → 403."""
|
||
client = smoke_user
|
||
resp = await client.get("/assistant/stats/admin")
|
||
|
||
passed = resp.status_code == 403
|
||
RESULTS.append(ScenarioResult(
|
||
"assistant_stats_admin_forbidden", "assistant", passed,
|
||
f"status={resp.status_code} (ожидали 403 — тестовый юзер не админ)",
|
||
{"status": resp.status_code},
|
||
))
|
||
assert passed
|
||
|
||
|
||
# ============================================================
|
||
# ВОЛНА 4 — support
|
||
# ============================================================
|
||
|
||
async def test_support_user_tickets(smoke_user):
|
||
"""GET /support/user-tickets → 200 + tickets (может быть пустой)."""
|
||
client = smoke_user
|
||
resp = await client.get("/support/user-tickets")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
tickets = body.get("tickets")
|
||
|
||
passed = ok and isinstance(tickets, list)
|
||
RESULTS.append(ScenarioResult(
|
||
"support_user_tickets", "support", passed,
|
||
f"status={resp.status_code}, тикетов={len(tickets) if tickets else 0}",
|
||
{"status": resp.status_code, "count": len(tickets) if tickets else 0},
|
||
))
|
||
assert passed
|
||
|
||
|
||
# 🔧 НОВОЕ (26.09.2026): волна 6 — support send + unread
|
||
|
||
async def test_support_send(smoke_user, smoke_conn):
|
||
"""POST /support/send → тикет + сообщение в БД."""
|
||
client = smoke_user
|
||
|
||
resp = await client.post("/support/send", json={"message": "smoke test message"})
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
ticket_id = body.get("ticket_id")
|
||
|
||
# Проверка в БД
|
||
ticket_in_db = False
|
||
message_in_db = False
|
||
if ticket_id:
|
||
ticket_in_db = await smoke_conn.fetchval(
|
||
"SELECT 1 FROM support_tickets WHERE id = $1 AND user_id = $2",
|
||
ticket_id, SMOKE_USER_ID,
|
||
) is not None
|
||
message_in_db = await smoke_conn.fetchval(
|
||
"SELECT 1 FROM support_messages WHERE ticket_id = $1 AND sender_id = $2",
|
||
ticket_id, SMOKE_USER_ID,
|
||
) is not None
|
||
|
||
passed = ok and ticket_id is not None and ticket_in_db and message_in_db
|
||
RESULTS.append(ScenarioResult(
|
||
"support_send", "support", passed,
|
||
f"status={resp.status_code}, ticket_id={ticket_id}, ticket_db={ticket_in_db}, msg_db={message_in_db}",
|
||
{
|
||
"status": resp.status_code,
|
||
"ticket_id": ticket_id,
|
||
"ticket_in_db": ticket_in_db,
|
||
"message_in_db": message_in_db,
|
||
},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_support_unread_count(smoke_user):
|
||
"""GET /support/user-unread-count → unread_count (число)."""
|
||
client = smoke_user
|
||
resp = await client.get("/support/user-unread-count")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
has_count = isinstance(body.get("unread_count"), int)
|
||
passed = ok and has_count
|
||
RESULTS.append(ScenarioResult(
|
||
"support_unread_count", "support", passed,
|
||
f"status={resp.status_code}, unread_count={body.get('unread_count')}",
|
||
{"status": resp.status_code, "unread_count": body.get("unread_count")},
|
||
))
|
||
assert passed
|
||
|
||
|
||
# ============================================================
|
||
# ВОЛНА 5 — admin (negative test)
|
||
# ============================================================
|
||
|
||
async def test_admin_dashboard_forbidden(smoke_user):
|
||
"""GET /admin/dashboard без админ-прав → 403.
|
||
|
||
SMOKE_USER_ID НЕ в ADMIN_IDS, поэтому эндпоинт должен вернуть 403.
|
||
Это проверяет, что защита админ-эндпоинтов работает.
|
||
"""
|
||
client = smoke_user
|
||
resp = await client.get("/admin/dashboard")
|
||
|
||
passed = resp.status_code == 403
|
||
RESULTS.append(ScenarioResult(
|
||
"admin_dashboard_forbidden", "admin", passed,
|
||
f"status={resp.status_code} (ожидали 403 — тестовый юзер не админ)",
|
||
{"status": resp.status_code},
|
||
))
|
||
assert passed
|
||
|
||
|
||
# 🔧 НОВОЕ (26.09.2026): волна 6 — admin sentry-errors forbidden
|
||
|
||
async def test_admin_sentry_errors_forbidden(smoke_user):
|
||
"""GET /admin/sentry-errors без админ-прав → 403."""
|
||
client = smoke_user
|
||
resp = await client.get("/admin/sentry-errors")
|
||
|
||
passed = resp.status_code == 403
|
||
RESULTS.append(ScenarioResult(
|
||
"admin_sentry_errors_forbidden", "admin", passed,
|
||
f"status={resp.status_code} (ожидали 403 — тестовый юзер не админ)",
|
||
{"status": resp.status_code},
|
||
))
|
||
assert passed
|
||
|
||
|
||
# ============================================================
|
||
# ВОЛНА 5 — feed
|
||
# ============================================================
|
||
|
||
async def test_feed_news_section(smoke_user):
|
||
"""GET /feed/news → 200 + posts (может быть пустой)."""
|
||
client = smoke_user
|
||
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(
|
||
"feed_news_section", "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
|
||
|
||
|
||
# 🔧 НОВОЕ (26.09.2026): волна 6 — feed post detail
|
||
|
||
async def test_feed_post_detail(smoke_user, smoke_conn):
|
||
"""GET /feed/post/{post_id} → один пост."""
|
||
client = smoke_user
|
||
|
||
post_id = await smoke_conn.fetchval(
|
||
"SELECT id FROM feed_posts WHERE is_published = TRUE LIMIT 1"
|
||
)
|
||
if not post_id:
|
||
pytest.skip("Нет опубликованных постов")
|
||
return
|
||
|
||
resp = await client.get(f"/feed/post/{post_id}")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
id_matches = body.get("id") == post_id
|
||
passed = ok and id_matches
|
||
RESULTS.append(ScenarioResult(
|
||
"feed_post_detail", "feed", passed,
|
||
f"status={resp.status_code}, post_id={post_id}, id_matches={id_matches}",
|
||
{"status": resp.status_code, "post_id": post_id, "id_matches": id_matches},
|
||
))
|
||
assert passed
|
||
|
||
|
||
# 🔧 НОВОЕ (26.09.2026): волна 6 — achievements (8 track + user)
|
||
|
||
async def test_achievements_track_teacher_menu(smoke_user):
|
||
"""POST /achievements/track-teacher-menu → new_achievements (список)."""
|
||
client = smoke_user
|
||
resp = await client.post("/achievements/track-teacher-menu")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
has_new = isinstance(body.get("new_achievements"), list)
|
||
passed = ok and has_new
|
||
RESULTS.append(ScenarioResult(
|
||
"achievements_track_teacher_menu", "achievements", passed,
|
||
f"status={resp.status_code}, new={len(body.get('new_achievements', []))}",
|
||
{"status": resp.status_code, "new_count": len(body.get("new_achievements", []))},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_achievements_track_progress(smoke_user):
|
||
"""POST /achievements/track-progress → new_achievements."""
|
||
client = smoke_user
|
||
resp = await client.post("/achievements/track-progress")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
has_new = isinstance(body.get("new_achievements"), list)
|
||
passed = ok and has_new
|
||
RESULTS.append(ScenarioResult(
|
||
"achievements_track_progress", "achievements", passed,
|
||
f"status={resp.status_code}, new={len(body.get('new_achievements', []))}",
|
||
{"status": resp.status_code, "new_count": len(body.get("new_achievements", []))},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_achievements_track_cheatsheets(smoke_user):
|
||
"""POST /achievements/track-cheatsheets → new_achievements."""
|
||
client = smoke_user
|
||
resp = await client.post("/achievements/track-cheatsheets")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
has_new = isinstance(body.get("new_achievements"), list)
|
||
passed = ok and has_new
|
||
RESULTS.append(ScenarioResult(
|
||
"achievements_track_cheatsheets", "achievements", passed,
|
||
f"status={resp.status_code}, new={len(body.get('new_achievements', []))}",
|
||
{"status": resp.status_code, "new_count": len(body.get("new_achievements", []))},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_achievements_track_pronunciation(smoke_user):
|
||
"""POST /achievements/track-pronunciation → new_achievements."""
|
||
client = smoke_user
|
||
resp = await client.post("/achievements/track-pronunciation")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
has_new = isinstance(body.get("new_achievements"), list)
|
||
passed = ok and has_new
|
||
RESULTS.append(ScenarioResult(
|
||
"achievements_track_pronunciation", "achievements", passed,
|
||
f"status={resp.status_code}, new={len(body.get('new_achievements', []))}",
|
||
{"status": resp.status_code, "new_count": len(body.get("new_achievements", []))},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_achievements_track_ai_assistant(smoke_user):
|
||
"""POST /achievements/track-ai-assistant → new_achievements."""
|
||
client = smoke_user
|
||
resp = await client.post("/achievements/track-ai-assistant")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
has_new = isinstance(body.get("new_achievements"), list)
|
||
passed = ok and has_new
|
||
RESULTS.append(ScenarioResult(
|
||
"achievements_track_ai_assistant", "achievements", passed,
|
||
f"status={resp.status_code}, new={len(body.get('new_achievements', []))}",
|
||
{"status": resp.status_code, "new_count": len(body.get("new_achievements", []))},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_achievements_track_alphabet(smoke_user):
|
||
"""POST /achievements/track-alphabet → new_achievements."""
|
||
client = smoke_user
|
||
resp = await client.post("/achievements/track-alphabet")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
has_new = isinstance(body.get("new_achievements"), list)
|
||
passed = ok and has_new
|
||
RESULTS.append(ScenarioResult(
|
||
"achievements_track_alphabet", "achievements", passed,
|
||
f"status={resp.status_code}, new={len(body.get('new_achievements', []))}",
|
||
{"status": resp.status_code, "new_count": len(body.get("new_achievements", []))},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_achievements_track_rules(smoke_user):
|
||
"""POST /achievements/track-rules → new_achievements."""
|
||
client = smoke_user
|
||
resp = await client.post("/achievements/track-rules")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
has_new = isinstance(body.get("new_achievements"), list)
|
||
passed = ok and has_new
|
||
RESULTS.append(ScenarioResult(
|
||
"achievements_track_rules", "achievements", passed,
|
||
f"status={resp.status_code}, new={len(body.get('new_achievements', []))}",
|
||
{"status": resp.status_code, "new_count": len(body.get("new_achievements", []))},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_achievements_user(smoke_user):
|
||
"""GET /achievements/user → достижения пользователя."""
|
||
client = smoke_user
|
||
resp = await client.get("/achievements/user")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
has_achievements = isinstance(body.get("achievements"), list)
|
||
has_total = "total" in body
|
||
has_unlocked = "unlocked" in body
|
||
has_percent = "progress_percent" in body
|
||
|
||
valid = has_achievements and has_total and has_unlocked and has_percent
|
||
passed = ok and valid
|
||
RESULTS.append(ScenarioResult(
|
||
"achievements_user", "achievements", passed,
|
||
f"status={resp.status_code}, unlocked={body.get('unlocked')}/{body.get('total')}, percent={body.get('progress_percent')}",
|
||
{
|
||
"status": resp.status_code,
|
||
"unlocked": body.get("unlocked"),
|
||
"total": body.get("total"),
|
||
"progress_percent": body.get("progress_percent"),
|
||
},
|
||
))
|
||
assert passed
|
||
|
||
|
||
# 🔧 НОВОЕ (26.09.2026): волна 6 — users (is_admin + set_level)
|
||
|
||
async def test_users_is_admin(smoke_user):
|
||
"""GET /users/me/is-admin → is_admin == False (тестовый юзер не админ)."""
|
||
client = smoke_user
|
||
resp = await client.get("/users/me/is-admin")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
is_admin = body.get("is_admin")
|
||
passed = ok and is_admin is False
|
||
RESULTS.append(ScenarioResult(
|
||
"users_is_admin", "users", passed,
|
||
f"status={resp.status_code}, is_admin={is_admin}",
|
||
{"status": resp.status_code, "is_admin": is_admin},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_users_set_level(smoke_user, smoke_conn):
|
||
"""POST /users/set-level → current_level в БД. Возвращаем A1 после."""
|
||
client = smoke_user
|
||
|
||
before = await smoke_conn.fetchval(
|
||
"SELECT current_level FROM users WHERE telegram_id = $1", SMOKE_USER_ID,
|
||
)
|
||
new_level = "A2" if before != "A2" else "A1"
|
||
|
||
resp = await client.post("/users/set-level", json={"level": new_level})
|
||
ok = resp.status_code == 200
|
||
|
||
after = await smoke_conn.fetchval(
|
||
"SELECT current_level FROM users WHERE telegram_id = $1", SMOKE_USER_ID,
|
||
)
|
||
|
||
passed = ok and after == new_level
|
||
|
||
# 🔧 ФИКС (26.09.2026): возвращаем A1, чтобы не сломать другие тесты
|
||
# (test_learning_* ожидают уровни A1).
|
||
await smoke_conn.execute(
|
||
"UPDATE users SET current_level = 'A1' WHERE telegram_id = $1",
|
||
SMOKE_USER_ID,
|
||
)
|
||
|
||
RESULTS.append(ScenarioResult(
|
||
"users_set_level", "users", passed,
|
||
f"status={resp.status_code}, level {before}→{after} (returned to A1)",
|
||
{"before": before, "after": after, "expected": new_level},
|
||
))
|
||
assert passed
|
||
|
||
|
||
# 🔧 НОВОЕ (26.09.2026): волна 6 — hints (word-list + remaining)
|
||
|
||
async def test_hints_word_list(smoke_user):
|
||
"""GET /hints/word-list/{level_id} → список слов. level_id=1."""
|
||
client = smoke_user
|
||
level_id = 1
|
||
|
||
resp = await client.get(f"/hints/word-list/{level_id}")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
words = body.get("words")
|
||
|
||
passed = ok and isinstance(words, list)
|
||
RESULTS.append(ScenarioResult(
|
||
"hints_word_list", "hints", passed,
|
||
f"status={resp.status_code}, words={len(words) if words else 0}",
|
||
{"status": resp.status_code, "count": len(words) if words else 0},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_hints_remaining(smoke_user):
|
||
"""GET /hints/remaining/{level_id} → max_hints, hints_used, remaining."""
|
||
client = smoke_user
|
||
level_id = 1
|
||
|
||
resp = await client.get(f"/hints/remaining/{level_id}")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
has_max = "max_hints" in body
|
||
has_used = "hints_used" in body
|
||
has_remaining = "remaining" in body
|
||
valid = has_max and has_used and has_remaining
|
||
|
||
passed = ok and valid
|
||
RESULTS.append(ScenarioResult(
|
||
"hints_remaining", "hints", passed,
|
||
f"status={resp.status_code}, used={body.get('hints_used')}/{body.get('max_hints')}, remaining={body.get('remaining')}",
|
||
{
|
||
"status": resp.status_code,
|
||
"max_hints": body.get("max_hints"),
|
||
"hints_used": body.get("hints_used"),
|
||
"remaining": body.get("remaining"),
|
||
},
|
||
))
|
||
assert passed
|
||
|
||
|
||
# 🔧 НОВОЕ (26.09.2026): волна 6 — game (progress + check-word)
|
||
|
||
async def test_game_progress(smoke_user):
|
||
"""GET /game/progress → last_completed_level, total_score, current_level."""
|
||
client = smoke_user
|
||
resp = await client.get("/game/progress")
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
has_last = "last_completed_level" in body
|
||
has_total = "total_score" in body
|
||
has_level = "current_level" in body
|
||
valid = has_last and has_total and has_level
|
||
|
||
passed = ok and valid
|
||
RESULTS.append(ScenarioResult(
|
||
"game_progress", "game", passed,
|
||
f"status={resp.status_code}, last={body.get('last_completed_level')}, score={body.get('total_score')}",
|
||
{
|
||
"status": resp.status_code,
|
||
"last_completed_level": body.get("last_completed_level"),
|
||
"total_score": body.get("total_score"),
|
||
"current_level": body.get("current_level"),
|
||
},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_game_check_word(smoke_user):
|
||
"""POST /game/check-word → found (bool). Координаты могут не совпасть."""
|
||
client = smoke_user
|
||
|
||
resp = await client.post(
|
||
"/game/check-word",
|
||
json={"level_id": 1, "cells": [[0, 0], [0, 1]]},
|
||
)
|
||
ok = resp.status_code == 200
|
||
body = resp.json() if ok else {}
|
||
|
||
has_found = "found" in body
|
||
passed = ok and has_found
|
||
RESULTS.append(ScenarioResult(
|
||
"game_check_word", "game", passed,
|
||
f"status={resp.status_code}, found={body.get('found')} (координаты произвольные)",
|
||
{"status": resp.status_code, "found": body.get("found")},
|
||
))
|
||
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_show_answer_medium(smoke_user, smoke_conn):
|
||
"""POST /sentences/show-answer — Medium: лимит 2 (200, 200, 403)."""
|
||
client = smoke_user
|
||
|
||
await smoke_conn.execute(
|
||
"UPDATE users SET difficulty = 'medium' WHERE telegram_id = $1", SMOKE_USER_ID
|
||
)
|
||
|
||
sentence_id = await smoke_conn.fetchval("SELECT id FROM sentences ORDER BY id LIMIT 1")
|
||
if not sentence_id:
|
||
pytest.skip("Нет предложений для show-answer теста")
|
||
return
|
||
|
||
# Чистим list_opened, чтобы начать с 0
|
||
await smoke_conn.execute(
|
||
"DELETE FROM sentence_progress WHERE user_id = $1 AND sentence_id = $2",
|
||
SMOKE_USER_ID, sentence_id,
|
||
)
|
||
|
||
resp1 = await client.post("/sentences/show-answer", json={"sentence_id": sentence_id})
|
||
resp2 = await client.post("/sentences/show-answer", json={"sentence_id": sentence_id})
|
||
resp3 = await client.post("/sentences/show-answer", json={"sentence_id": sentence_id})
|
||
|
||
passed = resp1.status_code == 200 and resp2.status_code == 200 and resp3.status_code == 403
|
||
RESULTS.append(ScenarioResult(
|
||
"sentences_show_answer_medium", "sentences", passed,
|
||
f"medium: 1={resp1.status_code}, 2={resp2.status_code}, 3={resp3.status_code} (ожидали 200/200/403)",
|
||
{"first": resp1.status_code, "second": resp2.status_code, "third": resp3.status_code},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_sentences_show_answer_hard(smoke_user, smoke_conn):
|
||
"""POST /sentences/show-answer — Hard: сразу 403."""
|
||
client = smoke_user
|
||
|
||
await smoke_conn.execute(
|
||
"UPDATE users SET difficulty = 'hard' WHERE telegram_id = $1", SMOKE_USER_ID
|
||
)
|
||
|
||
sentence_id = await smoke_conn.fetchval("SELECT id FROM sentences ORDER BY id LIMIT 1")
|
||
if not sentence_id:
|
||
pytest.skip("Нет предложений для show-answer теста")
|
||
return
|
||
|
||
resp = await client.post("/sentences/show-answer", json={"sentence_id": sentence_id})
|
||
|
||
passed = resp.status_code == 403
|
||
RESULTS.append(ScenarioResult(
|
||
"sentences_show_answer_hard", "sentences", passed,
|
||
f"hard: status={resp.status_code} (ожидали 403)",
|
||
{"status": resp.status_code},
|
||
))
|
||
assert passed
|
||
|
||
|
||
async def test_sentences_show_answer_easy(smoke_user, smoke_conn):
|
||
"""POST /sentences/show-answer — Easy: без лимита (несколько 200)."""
|
||
client = smoke_user
|
||
|
||
await smoke_conn.execute(
|
||
"UPDATE users SET difficulty = 'easy' WHERE telegram_id = $1", SMOKE_USER_ID
|
||
)
|
||
|
||
sentence_id = await smoke_conn.fetchval("SELECT id FROM sentences ORDER BY id LIMIT 1")
|
||
if not sentence_id:
|
||
pytest.skip("Нет предложений для show-answer теста")
|
||
return
|
||
|
||
statuses = []
|
||
for _ in range(3):
|
||
r = await client.post("/sentences/show-answer", json={"sentence_id": sentence_id})
|
||
statuses.append(r.status_code)
|
||
|
||
passed = all(s == 200 for s in statuses)
|
||
RESULTS.append(ScenarioResult(
|
||
"sentences_show_answer_easy", "sentences", passed,
|
||
f"easy: statuses={statuses} (ожидали все 200)",
|
||
{"statuses": statuses},
|
||
))
|
||
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:
|
||
date_str = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
|
||
passed = [r for r in RESULTS if r.passed]
|
||
failed = [r for r in RESULTS if not r.passed]
|
||
|
||
lines = [
|
||
"# 🧪 Smoke-test отчёт (реальный юзер, реальная БД)",
|
||
"",
|
||
f"**Дата:** {date_str}",
|
||
f"**Итого:** {len(passed)}/{len(RESULTS)} сценариев прошли",
|
||
"",
|
||
]
|
||
|
||
if failed:
|
||
lines += ["## ❌ Не работает — нужно чинить", ""]
|
||
for r in failed:
|
||
lines += [
|
||
f"### {r.name} ({r.section})",
|
||
f"- **Проблема:** {r.message}",
|
||
f"- **Детали:** `{r.details}`",
|
||
"",
|
||
]
|
||
|
||
if passed:
|
||
lines += ["## ✅ Подтверждено рабочим", ""]
|
||
for r in passed:
|
||
lines.append(f"- **{r.name}** ({r.section}) — {r.message}")
|
||
lines.append("")
|
||
|
||
# Группировка по секциям
|
||
lines += ["## 📊 По секциям", ""]
|
||
sections: dict[str, list[ScenarioResult]] = {}
|
||
for r in RESULTS:
|
||
sections.setdefault(r.section, []).append(r)
|
||
for section, items in sorted(sections.items()):
|
||
ok_count = sum(1 for r in items if r.passed)
|
||
lines.append(f"- **{section}**: {ok_count}/{len(items)}")
|
||
lines.append("")
|
||
|
||
Path("smoke_test_report.md").write_text("\n".join(lines), encoding="utf-8") |