54 lines
2.0 KiB
Python
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)
|
|
|
|
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"], "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()
|