"""Race, rollback and pool tests against the real PostgreSQL stand. These are the checks a code reviewer would ask for on top of the smoke test: concurrent writers must not lose or duplicate messages, the username uniqueness must be decided by the database (not by a read-then-write check in Python), and a failed composite operation must leave nothing behind. """ from __future__ import annotations import threading import time import unittest import uuid import common class ConcurrentWrites(unittest.TestCase): def test_100_messages_from_10_clients_are_exactly_100(self) -> None: alice = common.actor("cwalice") bob = common.actor("cwbob") chat = common.create_chat(alice.token, [alice.id, bob.id], "Гонка сообщений") writers = 10 per_writer = 10 barrier = threading.Barrier(writers) errors: list[str] = [] sent: list[str] = [] lock = threading.Lock() def writer(index: int) -> None: token = alice.token if index % 2 else bob.token barrier.wait() for number in range(per_writer): text = "race-%d-%d" % (index, number) try: common.send(token, chat["id"], text) with lock: sent.append(text) except AssertionError as error: # pragma: no cover - failure detail with lock: errors.append(str(error)) threads = [threading.Thread(target=writer, args=(index,)) for index in range(writers)] started = time.monotonic() for thread in threads: thread.start() for thread in threads: thread.join(timeout=120) elapsed = time.monotonic() - started self.assertEqual(errors, []) self.assertEqual(len(sent), writers * per_writer) messages = common.history(alice.token, chat["id"], limit=100) self.assertEqual(len(messages), writers * per_writer) self.assertEqual(len({message["id"] for message in messages}), len(messages)) self.assertEqual(sorted(message["text"] for message in messages), sorted(sent)) print("\n concurrent writes: %d messages from %d clients in %.2fs" % (len(messages), writers, elapsed)) def test_duplicate_username_race_creates_one_user(self) -> None: registration = common.new_registration("race") attempts = 12 barrier = threading.Barrier(attempts) statuses: list[int] = [] lock = threading.Lock() def attempt() -> None: barrier.wait() response = common.register(dict(registration)) with lock: statuses.append(response.status) threads = [threading.Thread(target=attempt) for _ in range(attempts)] for thread in threads: thread.start() for thread in threads: thread.join(timeout=60) self.assertEqual(statuses.count(201), 1, statuses) self.assertEqual(statuses.count(409), attempts - 1, statuses) # The single winner is usable, so exactly one row exists. session = common.login(registration["username"], registration["password"]) self.assertEqual(session.status, 201) self.assertEqual(session.json["user"]["username"], registration["username"]) def test_chat_creation_rolls_back_on_unknown_member(self) -> None: alice = common.actor("rollback") before = self._chat_titles(alice.token) response = common.request( "POST", "/api/v1/chats", body={"title": "Атомарный чат", "member_ids": [alice.id, str(uuid.uuid4())]}, token=alice.token, ) common.expect_error(self, response, 400, "invalid_request") after = self._chat_titles(alice.token) # The chat row inserted before the failing membership step is gone. self.assertEqual(before, after) self.assertNotIn("Атомарный чат", after) def _chat_titles(self, token: str) -> list[str]: titles: list[str] = [] cursor = None for _ in range(50): path = "/api/v1/chats?limit=100" if cursor: path += "&cursor=" + cursor response = common.request("GET", path, token=token) self.assertEqual(response.status, 200) titles.extend(item["title"] for item in response.json["items"]) cursor = response.json["next_cursor"] if cursor is None: return titles self.fail("chat pagination did not terminate") def test_bounded_pool_serves_parallel_reads(self) -> None: alice = common.actor("pool") parallel = 50 barrier = threading.Barrier(parallel) statuses: list[int] = [] lock = threading.Lock() def read() -> None: barrier.wait() # Chat lists are not cached, so this exercises the bounded SQL pool. response = common.request( "GET", "/api/v1/chats?limit=100", token=alice.token, timeout=10 ) with lock: statuses.append(response.status) threads = [threading.Thread(target=read) for _ in range(parallel)] for thread in threads: thread.start() for thread in threads: thread.join(timeout=60) self.assertEqual(len(statuses), parallel) self.assertEqual(statuses, [200] * parallel) if __name__ == "__main__": unittest.main()