diff --git a/tests/test_smoke.py b/tests/test_smoke.py index 5caeb86..78c1a58 100644 --- a/tests/test_smoke.py +++ b/tests/test_smoke.py @@ -23,6 +23,11 @@ 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 @@ -679,6 +684,156 @@ async def test_learning_progress(smoke_user): 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 # ============================================================ @@ -748,6 +903,273 @@ async def test_teacher_start_or_resume(smoke_user, smoke_conn): 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 # ============================================================ @@ -780,9 +1202,7 @@ async def test_assistant_limit(smoke_user): ok = resp.status_code == 200 body = resp.json() if ok else {} - # Ожидаем поля: is_admin, daily_limit, used, remaining has_fields = "is_admin" in body and "used" in body - passed = ok and has_fields RESULTS.append(ScenarioResult( "assistant_limit", "assistant", passed, @@ -809,6 +1229,48 @@ async def test_assistant_history(smoke_user): 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 # ============================================================ @@ -830,6 +1292,61 @@ async def test_support_user_tickets(smoke_user): 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) # ============================================================ @@ -852,6 +1369,22 @@ async def test_admin_dashboard_forbidden(smoke_user): 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 # ============================================================ @@ -873,6 +1406,335 @@ async def test_feed_news_section(smoke_user): 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: