solution
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
"""Транзакции, пул соединений и таймауты."""
|
||||
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy.exc import OperationalError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.main import create_app
|
||||
from app.models import ChatMember
|
||||
from conftest import assert_error, make_settings, register_and_login, run_sql
|
||||
|
||||
|
||||
def test_failure_after_chat_insert_rolls_back_whole_operation(client, alice, bob, monkeypatch):
|
||||
"""Сбой после вставки чата откатывает всю операцию."""
|
||||
real_execute = AsyncSession.execute
|
||||
|
||||
async def failing_execute(self, statement, *args, **kwargs):
|
||||
if getattr(getattr(statement, "table", None), "name", None) == ChatMember.__tablename__:
|
||||
raise OperationalError("INSERT INTO chat_members", {}, Exception("injected"))
|
||||
return await real_execute(self, statement, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(AsyncSession, "execute", failing_execute)
|
||||
title = "rollback-" + uuid.uuid4().hex
|
||||
reply = client.post(
|
||||
"/api/v1/chats", json={"title": title, "member_ids": [alice.id, bob.id]},
|
||||
headers=alice.headers,
|
||||
)
|
||||
monkeypatch.undo()
|
||||
|
||||
assert_error(reply, 503, "unavailable")
|
||||
assert "injected" not in reply.text and "chat_members" not in reply.text
|
||||
assert run_sql("SELECT count(*) AS n FROM chats WHERE title = $1", title)[0]["n"] == 0
|
||||
assert run_sql(
|
||||
"SELECT count(*) AS n FROM chat_members m JOIN chats c ON c.id = m.chat_id"
|
||||
" WHERE c.title = $1", title,
|
||||
)[0]["n"] == 0
|
||||
|
||||
|
||||
def test_pool_is_bounded_by_settings():
|
||||
settings = make_settings(db_pool_size=3, db_max_overflow=2, db_pool_timeout=4)
|
||||
with TestClient(create_app(settings), raise_server_exceptions=False) as app_client:
|
||||
pool = app_client.app.state.engine.pool
|
||||
assert pool.size() == 3
|
||||
assert pool._max_overflow == 2
|
||||
assert pool._timeout == 4
|
||||
|
||||
|
||||
def test_exhausted_pool_gives_fast_503():
|
||||
"""Занятый пул даёт 503 за время DB_POOL_TIMEOUT."""
|
||||
settings = make_settings(db_pool_size=1, db_max_overflow=0, db_pool_timeout=1, cache_url="")
|
||||
with TestClient(create_app(settings), raise_server_exceptions=False) as app_client:
|
||||
person = register_and_login(app_client, "pool")
|
||||
app = app_client.app
|
||||
|
||||
async def scenario():
|
||||
async with app.state.engine.connect():
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://t") as http:
|
||||
started = time.monotonic()
|
||||
reply = await http.get("/api/v1/users/me", headers=person.headers)
|
||||
return reply, time.monotonic() - started
|
||||
|
||||
reply, elapsed = app_client.portal.call(scenario)
|
||||
assert_error(reply, 503, "unavailable")
|
||||
assert elapsed < 3
|
||||
assert app_client.get("/api/v1/users/me", headers=person.headers).status_code == 200
|
||||
Reference in New Issue
Block a user