Files
mtusi2026lab4/student-tests/test_idempotency.py
Самохвалов Андрей Ремович f2e074d9f2 fix: preserve NUL characters in persisted messages
Store message text as UTF-8 bytes and migrate existing rows without loss.
Cover HTTP round trips, restart persistence, Unicode limits and idempotent retries.
Adapt direct database tools to the binary storage format.

(cherry picked from commit 386276532730b8758298080b49db63738ca300a4)
2026-11-07 09:53:49 +03:00

54 lines
2.0 KiB
Python

"""Concurrent PostgreSQL-backed message retries create one row."""
import os
import subprocess
import sys
import unittest
from concurrent.futures import ThreadPoolExecutor
from uuid import uuid4
import psycopg
from src.store import Store
URL = os.environ.get("DATABASE_URL")
@unittest.skipUnless(URL, "set DATABASE_URL to a disposable PostgreSQL database")
class IdempotencyTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
subprocess.run([sys.executable, "scripts/migrate.py"], check=True)
cls.store = Store()
def test_parallel_replay_conflict_and_scope(self):
alice = self.store.register("u_" + uuid4().hex[:16], "Алиса", "Test-password-123")
bob = self.store.register("u_" + uuid4().hex[:16], "Боб", "Test-password-123")
chat = self.store.create_chat(alice["id"], "Test", [alice["id"], bob["id"]])
other_chat = self.store.create_chat(alice["id"], "Other", [alice["id"]])
key = uuid4().hex
def send(_):
return Store().create_message(alice["id"], chat["id"], "same body", key, [] if _ else None)
with ThreadPoolExecutor(max_workers=2) as pool:
first, replay = list(pool.map(send, range(2)))
self.assertEqual(first, replay)
with psycopg.connect(URL) as conn:
count = conn.execute(
"SELECT count(*) FROM messages WHERE chat_id=%s AND sender_id=%s AND text=%s",
(chat["id"], alice["id"], b"same body"),
).fetchone()[0]
self.assertEqual(count, 1)
with self.assertRaises(Exception) as conflict:
self.store.create_message(alice["id"], chat["id"], "different body", key)
self.assertEqual(conflict.exception.status_code, 409)
self.assertNotEqual(self.store.create_message(bob["id"], chat["id"], "same body", key)["id"], first["id"])
self.assertNotEqual(self.store.create_message(alice["id"], other_chat["id"], "same body", key)["id"], first["id"])
if __name__ == "__main__":
unittest.main()