"""Integration checks against a disposable PostgreSQL database.""" import os import subprocess import sys import unittest from concurrent.futures import ThreadPoolExecutor from contextlib import contextmanager from unittest.mock import patch from uuid import uuid4 import psycopg from src.db import database_url from src.store import Store, connection 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,), (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"], "первое") second = self.store.create_message(bob["id"], chat["id"], "второе") 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) def test_membership_failure_rolls_back_inserted_chat(self): alice, bob = self.user(), self.user() title = "rollback-" + uuid4().hex class FailingConnection: def __init__(self, wrapped): self.wrapped = wrapped self.memberships = 0 def execute(self, query, params=None): if query.startswith("INSERT INTO memberships"): self.memberships += 1 if self.memberships == 2: raise RuntimeError("synthetic second membership failure") return self.wrapped.execute(query, params) @contextmanager def failing_connection(): with connection() as conn: yield FailingConnection(conn) with patch("src.store.connection", failing_connection): with self.assertRaisesRegex(RuntimeError, "synthetic second membership failure"): self.store.create_chat(alice["id"], title, [alice["id"], bob["id"]]) with psycopg.connect(URL) as conn: self.assertEqual(conn.execute("SELECT count(*) FROM chats WHERE title=%s", (title,)).fetchone()[0], 0) self.assertEqual(conn.execute( "SELECT count(*) FROM memberships WHERE user_id IN (%s,%s)", (alice["id"], bob["id"]), ).fetchone()[0], 0) if __name__ == "__main__": unittest.main()