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)
87 lines
4.2 KiB
Python
87 lines
4.2 KiB
Python
"""Integration checks against a disposable PostgreSQL database."""
|
|
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import unittest
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from uuid import uuid4
|
|
|
|
import psycopg
|
|
|
|
from src.db import database_url
|
|
from src.store import Store
|
|
|
|
|
|
URL = database_url() if os.environ.get("DATABASE_URL") or os.environ.get("DATABASE_URL_FILE") else None
|
|
|
|
|
|
@unittest.skipUnless(URL, "set DATABASE_URL or DATABASE_URL_FILE to a disposable PostgreSQL database")
|
|
class DatabaseTests(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
for _ in range(2):
|
|
subprocess.run([sys.executable, "scripts/migrate.py"], check=True)
|
|
cls.store = Store()
|
|
|
|
def user(self):
|
|
name = "u_" + uuid4().hex[:16]
|
|
return self.store.register(name, "Студент", "Test-password-123")
|
|
|
|
def test_migration_and_unique_username_race(self):
|
|
with psycopg.connect(URL) as conn:
|
|
versions = conn.execute("SELECT version FROM schema_migrations").fetchall()
|
|
self.assertEqual(versions, [(1,), (2,), (3,), (4,), (5,), (9,)])
|
|
name = "u_" + uuid4().hex[:16]
|
|
|
|
def register(_):
|
|
try:
|
|
return self.store.register(name, "Студент", "Test-password-123")
|
|
except Exception as exc:
|
|
return exc
|
|
|
|
with ThreadPoolExecutor(max_workers=2) as pool:
|
|
results = list(pool.map(register, range(2)))
|
|
self.assertEqual(sum(isinstance(result, dict) for result in results), 1)
|
|
self.assertEqual([result.status_code for result in results if not isinstance(result, dict)], [409])
|
|
with psycopg.connect(URL) as conn:
|
|
self.assertEqual(conn.execute("SELECT count(*) FROM users WHERE username=%s", (name,)).fetchone()[0], 1)
|
|
password_hash = conn.execute("SELECT password_hash FROM users WHERE username=%s", (name,)).fetchone()[0]
|
|
self.assertTrue(password_hash.startswith("$argon2id$"))
|
|
self.assertNotIn("password", str(next(result for result in results if isinstance(result, dict))))
|
|
subprocess.run([sys.executable, "scripts/migrate.py"], check=True)
|
|
with psycopg.connect(URL) as conn:
|
|
self.assertEqual(conn.execute("SELECT count(*) FROM users WHERE username=%s", (name,)).fetchone()[0], 1)
|
|
|
|
def test_chat_rollback_and_keyset_history(self):
|
|
alice, bob, eve = self.user(), self.user(), self.user()
|
|
with psycopg.connect(URL) as conn:
|
|
before = conn.execute("SELECT count(*) FROM chats").fetchone()[0]
|
|
with self.assertRaises(Exception) as failure:
|
|
self.store.create_chat(alice["id"], "invalid", [alice["id"], str(uuid4())])
|
|
self.assertEqual(failure.exception.status_code, 400)
|
|
with psycopg.connect(URL) as conn:
|
|
self.assertEqual(conn.execute("SELECT count(*) FROM chats").fetchone()[0], before)
|
|
|
|
chat = self.store.create_chat(alice["id"], "Valid", [alice["id"], bob["id"]])
|
|
chat2 = self.store.create_chat(alice["id"], "Second", [alice["id"]])
|
|
chat_page = self.store.list_chats(alice["id"], 1, None)
|
|
self.assertEqual(chat_page["items"], [chat])
|
|
self.assertEqual(self.store.list_chats(alice["id"], 1, chat_page["next_cursor"]), {"items": [chat2], "next_cursor": None})
|
|
first = self.store.create_message(alice["id"], chat["id"], "первое", uuid4().hex)
|
|
second = self.store.create_message(bob["id"], chat["id"], "второе", uuid4().hex)
|
|
page = self.store.list_messages(alice["id"], chat["id"], 1, None)
|
|
self.assertEqual(page["items"], [first])
|
|
self.assertEqual(self.store.list_messages(bob["id"], chat["id"], 1, page["next_cursor"]), {"items": [second], "next_cursor": None})
|
|
self.assertEqual(Store().chat(bob["id"], chat["id"]), chat)
|
|
with self.assertRaises(Exception) as wrong_cursor:
|
|
self.store.list_messages(alice["id"], chat2["id"], 1, page["next_cursor"])
|
|
self.assertEqual(wrong_cursor.exception.status_code, 400)
|
|
with self.assertRaises(Exception) as hidden:
|
|
self.store.chat(eve["id"], chat["id"])
|
|
self.assertEqual(hidden.exception.status_code, 404)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|