Files
mtusi2026lab4/student-tests/failures/test_transactions.py
T

91 lines
4.5 KiB
Python

"""Проверки на уровне БД: откат составной операции, гонка регистрации, повторный запуск миграций."""
import threading
import unittest
import uuid
from concurrent.futures import ThreadPoolExecutor
from stand import call, compose, sql, wait_ready
from api import new_chat, new_key, new_user, send, user_body
class TransactionTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
wait_ready()
cls.alice, cls.bob = new_user("alice"), new_user("bob")
def create_chat(self, title, member_ids):
return call("POST", "/api/v1/chats", {"title": title, "member_ids": member_ids}, user=self.alice)
def test_chat_with_unknown_member_is_rolled_back(self):
title = "rollback-" + uuid.uuid4().hex
# Алиса и Боб существуют, третьего участника нет: вставка чата и двух участников уже выполнена,
# на третьем срабатывает внешний ключ, и транзакция должна откатить всё
status, body, _ = self.create_chat(title, [self.alice["id"], self.bob["id"], str(uuid.uuid4())])
self.assertEqual(status, 400)
self.assertEqual(body["error"]["code"], "invalid_request")
self.assertEqual(sql("SELECT count(*) FROM chats WHERE title = '%s'" % title), "0")
self.assertEqual(sql("SELECT count(*) FROM chat_members m LEFT JOIN chats c ON c.id = m.chat_id WHERE c.id IS NULL"), "0")
def test_valid_chat_is_committed_whole(self):
title = "commit-" + uuid.uuid4().hex
status, chat, _ = self.create_chat(title, [self.alice["id"], self.bob["id"]])
self.assertEqual(status, 201)
self.assertEqual(sql("SELECT count(*) FROM chats WHERE title = '%s'" % title), "1")
self.assertEqual(sql("SELECT count(*) FROM chat_members WHERE chat_id = '%s'" % chat["id"]), "2")
def test_username_race_creates_one_row(self):
body = user_body(username="race_" + uuid.uuid4().hex[:8])
barrier = threading.Barrier(10)
def register(_):
barrier.wait()
return call("POST", "/api/v1/users", body)[0]
with ThreadPoolExecutor(max_workers=10) as pool:
statuses = sorted(pool.map(register, range(10)))
self.assertEqual(statuses, [201] + [409] * 9)
self.assertEqual(sql("SELECT count(*) FROM users WHERE username = '%s'" % body["username"]), "1")
def test_same_key_in_parallel_creates_one_row(self):
chat = new_chat(self.alice)
key = new_key()
barrier = threading.Barrier(20)
def post(_):
barrier.wait()
return send(self.alice, chat, "один раз", key=key)
with ThreadPoolExecutor(max_workers=20) as pool:
results = list(pool.map(post, range(20)))
self.assertEqual({status for status, _, _ in results}, {201})
self.assertEqual(len({message["id"] for _, message, _ in results}), 1)
self.assertEqual(sql("SELECT count(*) FROM messages WHERE chat_id = '%s'" % chat["id"]), "1")
self.assertEqual(sql("SELECT count(*) FROM idempotency_keys WHERE chat_id = '%s'" % chat["id"]), "1")
def test_failed_message_leaves_no_key(self):
# чужой чат: сообщение не создано, и ключ тоже не занят
eve = new_user("eve")
chat = new_chat(self.alice)
key = new_key()
self.assertEqual(send(eve, chat, "чужое", key=key)[0], 404)
self.assertEqual(sql("SELECT count(*) FROM idempotency_keys WHERE chat_id = '%s'" % chat["id"]), "0")
def test_password_is_stored_as_argon2id_hash(self):
stored = sql("SELECT password_hash FROM users WHERE id = '%s'" % self.alice["id"])
self.assertTrue(stored.startswith("$argon2id$"), stored[:12])
self.assertNotIn(self.alice["password"], stored)
def test_migrations_can_be_repeated(self):
before = sql("SELECT (SELECT count(*) FROM users), (SELECT count(*) FROM chats), (SELECT count(*) FROM messages)")
output = compose("run", "--rm", "migrate")
self.assertIn("уже применена: 0001_init.sql", output)
self.assertIn("уже применена: 0003_attachments.sql", output)
self.assertEqual(sql("SELECT count(*) FROM schema_migrations"), "3")
after = sql("SELECT (SELECT count(*) FROM users), (SELECT count(*) FROM chats), (SELECT count(*) FROM messages)")
self.assertEqual(before, after)
if __name__ == "__main__":
unittest.main()