72 lines
2.5 KiB
Python
72 lines
2.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Запуск: docker compose exec -T api python < scripts/check_transactions.py.
|
|
|
|
Принудительная ошибка после записи первого участника доказывает rollback
|
|
всего чата. Созданный синтетический пользователь остаётся в базе.
|
|
"""
|
|
from contextlib import contextmanager
|
|
from unittest.mock import patch
|
|
from uuid import uuid4
|
|
|
|
from src import chat_repository
|
|
from src.auth import hash_password
|
|
from src.database import get_connection, open_database, close_database
|
|
from src.user_repository import create_user
|
|
|
|
|
|
open_database()
|
|
try:
|
|
user = create_user('rollback_' + uuid4().hex[:12], 'Rollback check',
|
|
hash_password('SyntheticPassword123!'))
|
|
title = 'rollback-' + uuid4().hex
|
|
|
|
class FailingCursor:
|
|
def __init__(self, cursor):
|
|
self.cursor = cursor
|
|
|
|
def execute(self, *args):
|
|
return self.cursor.execute(*args)
|
|
|
|
def fetchall(self):
|
|
return self.cursor.fetchall()
|
|
|
|
def fetchone(self):
|
|
return self.cursor.fetchone()
|
|
|
|
def executemany(self, query, rows):
|
|
self.cursor.execute(query, rows[0])
|
|
raise RuntimeError('injected membership failure')
|
|
|
|
class Connection:
|
|
def __init__(self, conn):
|
|
self.conn = conn
|
|
|
|
def transaction(self):
|
|
return self.conn.transaction()
|
|
|
|
@contextmanager
|
|
def cursor(self):
|
|
with self.conn.cursor() as cur:
|
|
yield FailingCursor(cur)
|
|
|
|
@contextmanager
|
|
def failing_connection():
|
|
with get_connection() as conn:
|
|
yield Connection(conn)
|
|
|
|
with patch.object(chat_repository, 'get_connection', failing_connection):
|
|
try:
|
|
chat_repository.create_chat(user['id'], title, [user['id']])
|
|
except RuntimeError as exc:
|
|
assert str(exc) == 'injected membership failure'
|
|
else:
|
|
raise AssertionError('injected error was not raised')
|
|
with get_connection() as conn:
|
|
assert conn.execute('SELECT count(*) AS n FROM chats WHERE title = %s',
|
|
(title,)).fetchone()['n'] == 0
|
|
assert conn.execute('SELECT count(*) AS n FROM chat_members WHERE user_id = %s',
|
|
(user['id'],)).fetchone()['n'] == 0
|
|
print('PASS: failure after first member insert rolls back chat and membership')
|
|
finally:
|
|
close_database()
|