🧪 Smoke-test: волна 2 — +7 сценариев (wordquiz, bubblewords, sentences, typing, users, achievements)
Добавлено: - wordquiz_correct_answer — total_score растёт при правильном ответе - wordquiz_wrong_answer — current_mistakes растёт при неверном - bubblewords_complete_flow — levels_completed + total_score растут - sentences_check_wrong — неверный ответ НЕ начисляет очки - typing_progress_flow — typing_progress.completed_at записан - users_set_language — app_language меняется - achievements_track_login — daily_logins.login_date записан Покрытие: 10 сценариев (3 базовых + 7 новых)
This commit is contained in:
+309
-7
@@ -21,6 +21,15 @@ TestClient (starlette) создаёт свой event loop для каждого
|
|||||||
падал с InterfaceError: cannot perform operation: another operation
|
падал с InterfaceError: cannot perform operation: another operation
|
||||||
is in progress. Решение: httpx.AsyncClient с ASGITransport — все
|
is in progress. Решение: httpx.AsyncClient с ASGITransport — все
|
||||||
запросы идут в том же event loop, что и pool, конфликта нет.
|
запросы идут в том же event loop, что и pool, конфликта нет.
|
||||||
|
|
||||||
|
РАСШИРЕНО (26.09.2026, вечер): волна 2 —
|
||||||
|
+ wordquiz_check_flow (правильный ответ → total_score растёт)
|
||||||
|
+ wordquiz_wrong_answer (неверный ответ → current_mistakes растёт)
|
||||||
|
+ bubblewords_complete_flow (levels_completed и total_score растут)
|
||||||
|
+ sentences_check_wrong (неверный ответ → score НЕ растёт)
|
||||||
|
+ typing_progress_flow (check → typing_progress.completed_at записан)
|
||||||
|
+ users_set_language (app_language меняется)
|
||||||
|
+ achievements_track_login (daily_logins.login_date записан)
|
||||||
"""
|
"""
|
||||||
import hashlib
|
import hashlib
|
||||||
import hmac
|
import hmac
|
||||||
@@ -94,7 +103,7 @@ NON_FK_TABLES = [
|
|||||||
# не нужно, снесутся при DELETE FROM users: user_progress, sentence_progress,
|
# не нужно, снесутся при DELETE FROM users: user_progress, sentence_progress,
|
||||||
# typing_progress, chat_history, chat_usage, user_achievements, daily_logins,
|
# typing_progress, chat_history, chat_usage, user_achievements, daily_logins,
|
||||||
# word_quiz_progress, bubble_words_progress, sentence_hints_used,
|
# word_quiz_progress, bubble_words_progress, sentence_hints_used,
|
||||||
# typing_hints_used.
|
# typing_hints_used, voice_usage.
|
||||||
|
|
||||||
|
|
||||||
async def _cleanup(conn) -> None:
|
async def _cleanup(conn) -> None:
|
||||||
@@ -153,7 +162,9 @@ async def smoke_user(smoke_conn):
|
|||||||
_write_report()
|
_write_report()
|
||||||
|
|
||||||
|
|
||||||
# ============ Сценарий 1: Произношение (утечка пула) ============
|
# ============================================================
|
||||||
|
# ВОЛНА 1 — игры (базовые, уже работают)
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
async def test_pronunciation_pool_stress(smoke_user):
|
async def test_pronunciation_pool_stress(smoke_user):
|
||||||
"""В routers/pronunciation.py нет persistence-вызова — только get_next_word.
|
"""В routers/pronunciation.py нет persistence-вызова — только get_next_word.
|
||||||
@@ -184,14 +195,12 @@ async def test_pronunciation_pool_stress(smoke_user):
|
|||||||
assert passed, f"{failures}/{N} запросов к /pronunciation/next упали — похоже на утечку conn/пула"
|
assert passed, f"{failures}/{N} запросов к /pronunciation/next упали — похоже на утечку conn/пула"
|
||||||
|
|
||||||
|
|
||||||
# ============ Сценарий 2: Подсказки (DB-инкремент) ============
|
|
||||||
|
|
||||||
async def test_hints_first_letter(smoke_user, smoke_conn):
|
async def test_hints_first_letter(smoke_user, smoke_conn):
|
||||||
"""GET /hints/first-letter/{levelId} — читаем hints_used в user_progress
|
"""GET /hints/first-letter/{levelId} — читаем hints_used в user_progress
|
||||||
до и после. 200 без реального инкремента = баг.
|
до и после. 200 без реального инкремента = баг.
|
||||||
"""
|
"""
|
||||||
client = smoke_user
|
client = smoke_user
|
||||||
level_id = 1 # TODO: свериться, что level_id=1 гарантированно существует
|
level_id = 1 # подтверждено: level_id=1 существует
|
||||||
|
|
||||||
before = await smoke_conn.fetchrow(
|
before = await smoke_conn.fetchrow(
|
||||||
"SELECT hints_used FROM user_progress WHERE user_id = $1 AND level_id = $2",
|
"SELECT hints_used FROM user_progress WHERE user_id = $1 AND level_id = $2",
|
||||||
@@ -218,8 +227,6 @@ async def test_hints_first_letter(smoke_user, smoke_conn):
|
|||||||
assert after_count > before_count, f"hints_used не вырос: {before_count} → {after_count}"
|
assert after_count > before_count, f"hints_used не вырос: {before_count} → {after_count}"
|
||||||
|
|
||||||
|
|
||||||
# ============ Сценарий 3: Игра — complete-level (идемпотентность + DB) ============
|
|
||||||
|
|
||||||
async def test_game_complete_level_flow(smoke_user, smoke_conn):
|
async def test_game_complete_level_flow(smoke_user, smoke_conn):
|
||||||
"""GET /game/level/{n} → POST /game/complete-level (дважды).
|
"""GET /game/level/{n} → POST /game/complete-level (дважды).
|
||||||
Проверяем: (1) повторный вызов даёт already_completed=True, а не
|
Проверяем: (1) повторный вызов даёт already_completed=True, а не
|
||||||
@@ -258,6 +265,301 @@ async def test_game_complete_level_flow(smoke_user, smoke_conn):
|
|||||||
assert score_matches, f"API score={body1.get('score')}, но в БД score={db_score}"
|
assert score_matches, f"API score={body1.get('score')}, но в БД score={db_score}"
|
||||||
|
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# ВОЛНА 2 — остальные игры
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
|
async def test_wordquiz_correct_answer(smoke_user, smoke_conn):
|
||||||
|
"""POST /wordquiz/check с правильным ответом → total_score растёт.
|
||||||
|
|
||||||
|
ВАЖНО: wordquiz.check доверяет клиенту (correct_polish приходит в body).
|
||||||
|
Это by design (см. AI-находку wordquiz_check_trusts_client_correct_polish).
|
||||||
|
Здесь проверяем только ФАКТ начисления очков в БД.
|
||||||
|
"""
|
||||||
|
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}, total_score {before} → {after}",
|
||||||
|
{"before": before, "after": after, "correct": correct_flag, "status": resp.status_code},
|
||||||
|
))
|
||||||
|
assert ok, f"POST /wordquiz/check вернул {resp.status_code}"
|
||||||
|
assert correct_flag, f"API вернул correct=False на правильный ответ: {body}"
|
||||||
|
assert score_grew, f"total_score не вырос: {before} → {after}"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_wordquiz_wrong_answer(smoke_user, smoke_conn):
|
||||||
|
"""POST /wordquiz/check с неверным ответом → current_mistakes растёт."""
|
||||||
|
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
|
||||||
|
|
||||||
|
mistakes_grew = after > before
|
||||||
|
passed = ok and mistakes_grew
|
||||||
|
|
||||||
|
RESULTS.append(ScenarioResult(
|
||||||
|
"wordquiz_wrong_answer", "wordquiz", passed,
|
||||||
|
f"status={resp.status_code}, current_mistakes {before} → {after}",
|
||||||
|
{"before": before, "after": after, "status": resp.status_code},
|
||||||
|
))
|
||||||
|
assert ok, f"POST /wordquiz/check вернул {resp.status_code}"
|
||||||
|
assert mistakes_grew, f"current_mistakes не вырос: {before} → {after}"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_bubblewords_complete_flow(smoke_user, smoke_conn):
|
||||||
|
"""POST /bubblewords/complete → levels_completed и total_score растут.
|
||||||
|
|
||||||
|
ВАЖНО: complete_bubble_level НЕ принимает hints_used от клиента —
|
||||||
|
читает current_hints_used из БД (см. AI-фикс
|
||||||
|
client_controlled_hints_bubblewords).
|
||||||
|
"""
|
||||||
|
client = smoke_user
|
||||||
|
|
||||||
|
before = await smoke_conn.fetchrow(
|
||||||
|
"SELECT levels_completed, total_score FROM bubble_words_progress WHERE user_id = $1",
|
||||||
|
SMOKE_USER_ID,
|
||||||
|
)
|
||||||
|
before_levels = before["levels_completed"] if before else 0
|
||||||
|
before_score = 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
|
||||||
|
body = resp.json() if ok else {}
|
||||||
|
|
||||||
|
after = await smoke_conn.fetchrow(
|
||||||
|
"SELECT levels_completed, total_score FROM bubble_words_progress WHERE user_id = $1",
|
||||||
|
SMOKE_USER_ID,
|
||||||
|
)
|
||||||
|
after_levels = after["levels_completed"] if after else 0
|
||||||
|
after_score = after["total_score"] if after else 0
|
||||||
|
|
||||||
|
levels_grew = after_levels > before_levels
|
||||||
|
score_grew = after_score > before_score
|
||||||
|
passed = ok and levels_grew and score_grew
|
||||||
|
|
||||||
|
RESULTS.append(ScenarioResult(
|
||||||
|
"bubblewords_complete_flow", "bubblewords", passed,
|
||||||
|
f"status={resp.status_code}, levels {before_levels}→{after_levels}, score {before_score}→{after_score}",
|
||||||
|
{
|
||||||
|
"before_levels": before_levels, "after_levels": after_levels,
|
||||||
|
"before_score": before_score, "after_score": after_score,
|
||||||
|
"status": resp.status_code,
|
||||||
|
},
|
||||||
|
))
|
||||||
|
assert ok, f"POST /bubblewords/complete вернул {resp.status_code}"
|
||||||
|
assert levels_grew, f"levels_completed не вырос: {before_levels} → {after_levels}"
|
||||||
|
assert score_grew, f"total_score не вырос: {before_score} → {after_score}"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_sentences_check_wrong(smoke_user, smoke_conn):
|
||||||
|
"""POST /sentences/check с неверными словами → score НЕ растёт.
|
||||||
|
|
||||||
|
Сложность: правильный порядок слов угадать нельзя. Проверяем
|
||||||
|
негативный сценарий: неверный ответ не должен начислять очки.
|
||||||
|
"""
|
||||||
|
client = smoke_user
|
||||||
|
|
||||||
|
# Берём первое предложение из базы
|
||||||
|
sentence_row = await smoke_conn.fetchrow(
|
||||||
|
"SELECT id, sentence_pl FROM sentences ORDER BY id LIMIT 1"
|
||||||
|
)
|
||||||
|
if not sentence_row:
|
||||||
|
RESULTS.append(ScenarioResult(
|
||||||
|
"sentences_check_wrong", "sentences", False,
|
||||||
|
"В таблице sentences нет ни одного предложения",
|
||||||
|
{},
|
||||||
|
))
|
||||||
|
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
|
||||||
|
|
||||||
|
score_unchanged = after == before
|
||||||
|
passed = ok and score_unchanged
|
||||||
|
|
||||||
|
RESULTS.append(ScenarioResult(
|
||||||
|
"sentences_check_wrong", "sentences", passed,
|
||||||
|
f"status={resp.status_code}, score {before} → {after} (неверный ответ)",
|
||||||
|
{"before": before, "after": after, "status": resp.status_code},
|
||||||
|
))
|
||||||
|
assert ok, f"POST /sentences/check вернул {resp.status_code}"
|
||||||
|
assert score_unchanged, f"Очки начислены за неверный ответ: {before} → {after}"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_typing_progress_flow(smoke_user, smoke_conn):
|
||||||
|
"""GET /typing/next → POST /typing/check → typing_progress.completed_at записан."""
|
||||||
|
client = smoke_user
|
||||||
|
|
||||||
|
resp_next = await client.get("/typing/next")
|
||||||
|
if resp_next.status_code != 200:
|
||||||
|
RESULTS.append(ScenarioResult(
|
||||||
|
"typing_progress_flow", "typing", False,
|
||||||
|
f"GET /typing/next вернул {resp_next.status_code}",
|
||||||
|
{"status": resp_next.status_code},
|
||||||
|
))
|
||||||
|
pytest.skip(f"GET /typing/next вернул {resp_next.status_code}")
|
||||||
|
return
|
||||||
|
|
||||||
|
body = resp_next.json()
|
||||||
|
sentence_id = body.get("id") or body.get("sentence_id")
|
||||||
|
sentence_pl = body.get("sentence_pl", "")
|
||||||
|
|
||||||
|
if not sentence_id or not sentence_pl:
|
||||||
|
RESULTS.append(ScenarioResult(
|
||||||
|
"typing_progress_flow", "typing", False,
|
||||||
|
f"GET /typing/next не вернул id/sentence_pl: {body}",
|
||||||
|
{"body": body},
|
||||||
|
))
|
||||||
|
pytest.skip("Нет данных для typing check")
|
||||||
|
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}, typing_progress записан={recorded}",
|
||||||
|
{"status": resp_check.status_code, "recorded": recorded},
|
||||||
|
))
|
||||||
|
assert ok, f"POST /typing/check вернул {resp_check.status_code}"
|
||||||
|
assert recorded, "typing_progress.completed_at не записан в БД"
|
||||||
|
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# ВОЛНА 2 — пользователь и достижения
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
|
async def test_users_set_language(smoke_user, smoke_conn):
|
||||||
|
"""POST /users/set-language → users.app_language меняется."""
|
||||||
|
client = smoke_user
|
||||||
|
|
||||||
|
before = await smoke_conn.fetchval(
|
||||||
|
"SELECT app_language FROM users WHERE telegram_id = $1",
|
||||||
|
SMOKE_USER_ID,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Меняем на 'ru' (не 'pl', чтобы гарантированно отличалось)
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
|
||||||
|
lang_changed = after == new_lang
|
||||||
|
passed = ok and lang_changed
|
||||||
|
|
||||||
|
RESULTS.append(ScenarioResult(
|
||||||
|
"users_set_language", "users", passed,
|
||||||
|
f"status={resp.status_code}, app_language {before} → {after} (ожидали {new_lang})",
|
||||||
|
{"before": before, "after": after, "expected": new_lang, "status": resp.status_code},
|
||||||
|
))
|
||||||
|
assert ok, f"POST /users/set-language вернул {resp.status_code}"
|
||||||
|
assert lang_changed, f"app_language не изменился: {before} → {after}"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_achievements_track_login(smoke_user, smoke_conn):
|
||||||
|
"""POST /achievements/track-login → daily_logins.login_date записан."""
|
||||||
|
client = smoke_user
|
||||||
|
|
||||||
|
before_count = 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_count = await smoke_conn.fetchval(
|
||||||
|
"SELECT COUNT(*) FROM daily_logins WHERE user_id = $1",
|
||||||
|
SMOKE_USER_ID,
|
||||||
|
) or 0
|
||||||
|
|
||||||
|
logins_grew = after_count > before_count
|
||||||
|
passed = ok and logins_grew
|
||||||
|
|
||||||
|
RESULTS.append(ScenarioResult(
|
||||||
|
"achievements_track_login", "achievements", passed,
|
||||||
|
f"status={resp.status_code}, daily_logins {before_count} → {after_count}",
|
||||||
|
{"before": before_count, "after": after_count, "status": resp.status_code},
|
||||||
|
))
|
||||||
|
assert ok, f"POST /achievements/track-login вернул {resp.status_code}"
|
||||||
|
assert logins_grew, f"daily_logins не вырос: {before_count} → {after_count}"
|
||||||
|
|
||||||
|
|
||||||
# ============ Отчёт ============
|
# ============ Отчёт ============
|
||||||
|
|
||||||
def _write_report() -> None:
|
def _write_report() -> None:
|
||||||
|
|||||||
Reference in New Issue
Block a user