1779 lines
63 KiB
Python
1779 lines
63 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.
|
||
"""
|
||
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"
|
||
|
||
|
||
# ============ Генерация 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(conn) -> None:
|
||
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(
|
||
"DELETE FROM support_messages WHERE ticket_id IN "
|
||
"(SELECT id FROM support_tickets WHERE user_id = $1)",
|
||
SMOKE_USER_ID,
|
||
)
|
||
await conn.execute("DELETE FROM support_tickets WHERE user_id = $1", SMOKE_USER_ID)
|
||
|
||
await conn.execute("DELETE FROM users WHERE telegram_id = $1", 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()
|
||
|
||
|
||
# ============================================================
|
||
# ВОЛНА 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)
|
||
# Это волна с 8 track-эндпоинтами достижений + один общий.
|
||
|
||
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)
|
||
# Это дополнение к волне 2 (set_language).
|
||
|
||
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)
|
||
# Это дополнение к волне 1 (first-letter).
|
||
|
||
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)
|
||
# Это дополнение к волне 1 (complete-level).
|
||
|
||
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
|
||
|
||
|
||
# ============ Отчёт ============
|
||
|
||
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") |