from uuid import uuid4 import asyncpg import pytest from conftest import DATABASE, scalar from messenger.migrate import MigrationChangedError, migrate, migrations COUNTS = """ SELECT (SELECT count(*) FROM users), (SELECT count(*) FROM sessions), (SELECT count(*) FROM chats), (SELECT count(*) FROM chat_members), (SELECT count(*) FROM messages), (SELECT count(*) FROM idempotency_keys), (SELECT count(*) FROM attachments), (SELECT count(*) FROM message_attachments) """ async def counts() -> list[int]: connection = await asyncpg.connect(DATABASE["url"]) try: return list(await connection.fetchrow(COUNTS)) finally: await connection.close() async def test_migrations_are_ordered_and_versioned() -> None: versions = [version for version, _ in migrations()] assert versions == sorted(versions) assert versions == [ "0001_init", "0002_idempotency_keys", "0003_attachments", "0004_attachment_quarantine", ] applied = await scalar("SELECT array_agg(version ORDER BY version) FROM schema_migrations") assert applied == versions async def test_rerun_changes_nothing() -> None: before = await counts() assert await migrate(DATABASE["url"]) == [] assert await counts() == before async def test_changed_migration_is_refused() -> None: connection = await asyncpg.connect(DATABASE["url"]) try: original = await connection.fetchval( "SELECT checksum FROM schema_migrations WHERE version = '0001_init'" ) await connection.execute( "UPDATE schema_migrations SET checksum = 'tampered' WHERE version = '0001_init'" ) with pytest.raises(MigrationChangedError): await migrate(DATABASE["url"]) await connection.execute( "UPDATE schema_migrations SET checksum = $1 WHERE version = '0001_init'", original ) finally: await connection.close() async def test_sender_must_be_member_even_bypassing_api() -> None: connection = await asyncpg.connect(DATABASE["url"]) try: with pytest.raises(asyncpg.ForeignKeyViolationError): await connection.execute( "INSERT INTO messages (id, chat_id, sender_id, text, created_at) " "VALUES (gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), 'x', now())" ) finally: await connection.close() async def test_key_needs_a_member_and_a_message() -> None: connection = await asyncpg.connect(DATABASE["url"]) try: with pytest.raises(asyncpg.ForeignKeyViolationError): await connection.execute( "INSERT INTO idempotency_keys " "(chat_id, user_id, key, fingerprint, message_id, created_at) " "VALUES (gen_random_uuid(), gen_random_uuid(), 'k-1', " "sha256('x'), gen_random_uuid(), now())" ) finally: await connection.close() async def test_attachment_owner_must_be_member() -> None: connection = await asyncpg.connect(DATABASE["url"]) try: with pytest.raises(asyncpg.ForeignKeyViolationError, match="attachments_owner_fkey"): await connection.execute( "INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, " "size_bytes, sha256, width, height, object_key, status, created_at, updated_at) " "VALUES (gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), 'a.png', " "'image/png', 1, repeat('0', 64), 1, 1, 'attachments/x', 'pending', now(), now())" ) finally: await connection.close() async def test_message_links_only_attachments_of_its_chat() -> None: user, chat_a, chat_b, attachment, message = (uuid4() for _ in range(5)) seed = [ ( "INSERT INTO users (id, username, display_name, password_hash, created_at) " "VALUES ($1, $2, 'A', '$argon2id$x', now())", user, f"u_{user.hex[:12]}", ), ("INSERT INTO chats (id, title, created_at) VALUES ($1, 'A', now())", chat_a), ("INSERT INTO chats (id, title, created_at) VALUES ($1, 'B', now())", chat_b), ( "INSERT INTO chat_members (chat_id, user_id, position, chat_created_at) " "VALUES ($1, $3, 1, now()), ($2, $3, 1, now())", chat_a, chat_b, user, ), ( "INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, " "sha256, width, height, object_key, status, created_at, updated_at) VALUES ($1, $2, " "$3, 'a.png', 'image/png', 1, repeat('0', 64), 1, 1, $4, 'ready', now(), now())", attachment, chat_a, user, f"attachments/{attachment}", ), ( "INSERT INTO messages (id, chat_id, sender_id, text, created_at) " "VALUES ($1, $2, $3, '', now())", message, chat_b, user, ), ] connection = await asyncpg.connect(DATABASE["url"]) transaction = connection.transaction() await transaction.start() try: for sql, *arguments in seed: await connection.execute(sql, *arguments) assert await connection.fetchval("SELECT text FROM messages WHERE id = $1", message) == "" with pytest.raises( asyncpg.ForeignKeyViolationError, match="message_attachments_attachment_fkey" ): await connection.execute( "INSERT INTO message_attachments (message_id, position, chat_id, attachment_id) " "VALUES ($1, 0, $2, $3)", message, chat_b, attachment, ) finally: await transaction.rollback() await connection.close()