добавлена обработка отказов зависимостей и тесты транзакций

This commit is contained in:
2026-10-08 01:10:50 +03:00
parent 4922e68dca
commit c1200032b5
5 changed files with 316 additions and 9 deletions
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
import json
import threading
import urllib.error
import urllib.request
import uuid
BASE_URL = "http://localhost:8080"
def register(username: str, barrier: threading.Barrier) -> tuple[int, dict]:
body = json.dumps(
{
"username": username,
"display_name": "Race User",
"password": "correct-password-123",
}
).encode("utf-8")
request = urllib.request.Request(
BASE_URL + "/api/v1/users",
data=body,
headers={"Content-Type": "application/json"},
method="POST",
)
# Оба потока доходят сюда и только потом одновременно продолжают.
barrier.wait()
try:
with urllib.request.urlopen(request, timeout=10) as response:
return response.status, json.loads(response.read())
except urllib.error.HTTPError as error:
return error.code, json.loads(error.read())
def main() -> None:
username = "race_" + uuid.uuid4().hex[:16]
barrier = threading.Barrier(2)
results: list[tuple[int, dict] | None] = [None, None]
def worker(index: int) -> None:
results[index] = register(username, barrier)
threads = [
threading.Thread(target=worker, args=(0,)),
threading.Thread(target=worker, args=(1,)),
]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
statuses = sorted(result[0] for result in results if result is not None)
if statuses != [201, 409]:
raise AssertionError(
f"expected exactly one 201 and one 409, got {statuses}"
)
created = [
result
for result in results
if result is not None and result[0] == 201
]
conflicts = [
result
for result in results
if result is not None and result[0] == 409
]
if len(created) != 1 or created[0][1]["username"] != username:
raise AssertionError("unexpected successful registration response")
if (
len(conflicts) != 1
or conflicts[0][1]["error"]["code"] != "conflict"
):
raise AssertionError("unexpected conflict response")
print(
"PASS: concurrent registration produced exactly "
"one 201 and one 409."
)
if __name__ == "__main__":
main()
+124
View File
@@ -0,0 +1,124 @@
#!/usr/bin/env python3
import asyncio
from uuid import uuid4
from sqlalchemy import text
from sqlalchemy.exc import IntegrityError
from src.database import SessionFactory
async def main() -> None:
chat_id = uuid4()
async with SessionFactory() as session:
# Берём реального существующего пользователя.
result = await session.execute(
text(
"""
SELECT id
FROM users
ORDER BY created_at
LIMIT 1
"""
)
)
user_id = result.scalar_one_or_none()
if user_id is None:
raise AssertionError("test requires at least one existing user")
try:
# Шаг 1: успешно создаём чат.
await session.execute(
text(
"""
INSERT INTO chats (id, title)
VALUES (:chat_id, :title)
"""
),
{
"chat_id": chat_id,
"title": "Rollback automated test",
},
)
# Шаг 2: успешно добавляем реального участника.
await session.execute(
text(
"""
INSERT INTO chat_members (chat_id, user_id)
VALUES (:chat_id, :user_id)
"""
),
{
"chat_id": chat_id,
"user_id": user_id,
},
)
# Шаг 3: намеренно нарушаем внешний ключ.
await session.execute(
text(
"""
INSERT INTO chat_members (chat_id, user_id)
VALUES (:chat_id, :user_id)
"""
),
{
"chat_id": chat_id,
"user_id": uuid4(),
},
)
raise AssertionError("expected foreign key violation")
except IntegrityError:
await session.rollback()
# После rollback начинаем новую транзакцию и проверяем БД.
chat_result = await session.execute(
text(
"""
SELECT COUNT(*)
FROM chats
WHERE id = :chat_id
"""
),
{"chat_id": chat_id},
)
chat_count = chat_result.scalar_one()
member_result = await session.execute(
text(
"""
SELECT COUNT(*)
FROM chat_members
WHERE chat_id = :chat_id
"""
),
{"chat_id": chat_id},
)
member_count = member_result.scalar_one()
if chat_count != 0:
raise AssertionError(
f"chat survived rollback: count={chat_count}"
)
if member_count != 0:
raise AssertionError(
f"chat members survived rollback: count={member_count}"
)
print(
"PASS: failed compound transaction rolled back "
"chat and membership inserts."
)
if __name__ == "__main__":
asyncio.run(main())