124 lines
3.5 KiB
Python
124 lines
3.5 KiB
Python
#!/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()) |