🧪 Smoke-test: TestClient → httpx.AsyncClient (fix asyncpg loop conflict)
Root cause: TestClient (starlette) создаёт свой event loop для каждого запроса, а asyncpg-пул привязан к тому event loop, в котором создан. Второй запрос падал с InterfaceError: cannot perform operation: another operation is in progress. - Заменён TestClient на httpx.AsyncClient + ASGITransport - Все client.get/post теперь с await - Все запросы идут в том же event loop, что и asyncpg-пул
This commit is contained in:
+30
-14
@@ -14,6 +14,13 @@ TEST_USER_ID = 999999999 (9 девяток) из conftest.py. Это два ра
|
||||
специально: TEST_USER_ID уже используется другими тестами через фикстуру
|
||||
test_user, которая чистит более короткий список таблиц. Смешивать их —
|
||||
риск ложных срабатываний в обоих наборах тестов.
|
||||
|
||||
ФИКС (26.09.2026): testclient_asyncpg_conflict —
|
||||
TestClient (starlette) создаёт свой event loop для каждого запроса,
|
||||
а asyncpg-пул привязан к event loop, в котором создан. Второй запрос
|
||||
падал с InterfaceError: cannot perform operation: another operation
|
||||
is in progress. Решение: httpx.AsyncClient с ASGITransport — все
|
||||
запросы идут в том же event loop, что и pool, конфликта нет.
|
||||
"""
|
||||
import hashlib
|
||||
import hmac
|
||||
@@ -25,8 +32,8 @@ from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from main import app
|
||||
from database import get_pool
|
||||
@@ -119,19 +126,28 @@ async def smoke_conn():
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
async def smoke_user(smoke_conn):
|
||||
"""Цикл на всю сессию: удалить → зарегистрировать → (тесты) → удалить → отчёт."""
|
||||
"""Цикл на всю сессию: удалить → зарегистрировать → (тесты) → удалить → отчёт.
|
||||
|
||||
ФИКС (26.09.2026): testclient_asyncpg_conflict — вместо TestClient
|
||||
используется httpx.AsyncClient с ASGITransport. Все запросы идут
|
||||
в том же event loop, что и asyncpg-пул (smoke_conn), поэтому
|
||||
соединение не «зависает» между запросами.
|
||||
"""
|
||||
await _cleanup(smoke_conn)
|
||||
|
||||
client = TestClient(app)
|
||||
init_data = _build_init_data(SMOKE_USER_ID, SMOKE_USER_FIRST_NAME, BOT_TOKEN)
|
||||
client.headers.update({"Authorization": f"tma {init_data}"})
|
||||
|
||||
resp = client.post("/users/register")
|
||||
assert resp.status_code == 200, (
|
||||
f"Не удалось зарегистрировать тестового юзера: {resp.status_code} {resp.text[:200]}"
|
||||
)
|
||||
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
|
||||
yield client
|
||||
|
||||
await _cleanup(smoke_conn)
|
||||
_write_report()
|
||||
@@ -150,7 +166,7 @@ async def test_pronunciation_pool_stress(smoke_user):
|
||||
failures = 0
|
||||
|
||||
for _ in range(N):
|
||||
resp = client.get("/pronunciation/next")
|
||||
resp = await client.get("/pronunciation/next")
|
||||
if resp.status_code != 200:
|
||||
failures += 1
|
||||
continue
|
||||
@@ -183,7 +199,7 @@ async def test_hints_first_letter(smoke_user, smoke_conn):
|
||||
)
|
||||
before_count = before["hints_used"] if before else 0
|
||||
|
||||
resp = client.get(f"/hints/first-letter/{level_id}")
|
||||
resp = await client.get(f"/hints/first-letter/{level_id}")
|
||||
ok = resp.status_code == 200
|
||||
|
||||
after = await smoke_conn.fetchrow(
|
||||
@@ -213,15 +229,15 @@ async def test_game_complete_level_flow(smoke_user, smoke_conn):
|
||||
client = smoke_user
|
||||
level_number = 1
|
||||
|
||||
resp_level = client.get(f"/game/level/{level_number}")
|
||||
resp_level = await client.get(f"/game/level/{level_number}")
|
||||
assert resp_level.status_code == 200, f"GET /game/level/{level_number} вернул {resp_level.status_code}"
|
||||
level_id = resp_level.json().get("level", {}).get("id")
|
||||
|
||||
resp1 = client.post("/game/complete-level", json={"level_id": level_id, "hints_used": 0})
|
||||
resp1 = await client.post("/game/complete-level", json={"level_id": level_id, "hints_used": 0})
|
||||
assert resp1.status_code == 200, f"POST /game/complete-level (1-й раз) вернул {resp1.status_code}"
|
||||
body1 = resp1.json()
|
||||
|
||||
resp2 = client.post("/game/complete-level", json={"level_id": level_id, "hints_used": 0})
|
||||
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"))
|
||||
|
||||
|
||||
Reference in New Issue
Block a user