59 lines
3.1 KiB
Python
59 lines
3.1 KiB
Python
import hashlib
|
||
import time
|
||
import unittest
|
||
import uuid
|
||
|
||
from helpers import call, compose, new_chat, new_user, sql
|
||
|
||
|
||
class DatabaseTest(unittest.TestCase):
|
||
def test_chat_creation_is_rolled_back(self):
|
||
"""Неизвестный участник: INSERT chats выполнен, INSERT chat_members упал по FK, всё откатано"""
|
||
alice = new_user('alice')
|
||
chats_before = int(sql('SELECT count(*) FROM chats'))
|
||
members_before = int(sql('SELECT count(*) FROM chat_members'))
|
||
ghost = str(uuid.uuid4())
|
||
since = sql("SELECT to_char(now() - interval '1 second', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"')")
|
||
status, _, body = call('POST', '/api/v1/chats', {'title': 'Откат', 'member_ids': [alice['id'], ghost]},
|
||
alice['token'])
|
||
self.assertEqual(status, 400, body)
|
||
time.sleep(0.5)
|
||
log = compose('logs', '--no-log-prefix', '--since', since, 'postgres')
|
||
self.assertIn('violates foreign key constraint', log)
|
||
self.assertIn(ghost, log)
|
||
self.assertEqual(int(sql('SELECT count(*) FROM chats')), chats_before)
|
||
self.assertEqual(int(sql('SELECT count(*) FROM chat_members')), members_before)
|
||
|
||
def test_secrets_are_not_stored_in_plaintext(self):
|
||
"""В users лежит argon2id-хеш, в sessions — sha256 токена, не сам токен"""
|
||
alice = new_user('alice')
|
||
password_hash = sql("SELECT password_hash FROM users WHERE id = '%s'" % alice['id'])
|
||
self.assertTrue(password_hash.startswith('$argon2id$'), password_hash[:10])
|
||
self.assertNotIn(alice['password'], password_hash)
|
||
digest = hashlib.sha256(alice['token'].encode()).hexdigest()
|
||
self.assertEqual(sql("SELECT count(*) FROM sessions WHERE token_hash = '\\x%s'" % digest), '1')
|
||
dump = sql("SELECT string_agg(encode(token_hash, 'escape'), '') FROM sessions WHERE user_id = '%s'" % alice['id'])
|
||
self.assertNotIn(alice['token'], dump)
|
||
|
||
def test_migrations_are_idempotent(self):
|
||
"""Повторный запуск миграций ничего не меняет и завершается успешно"""
|
||
before = sql('SELECT version, applied_at FROM schema_migrations ORDER BY version')
|
||
users = sql('SELECT count(*) FROM users')
|
||
output = compose('run', '--rm', '--no-deps', 'migrate')
|
||
self.assertIn('skip 0001_init: already applied', output)
|
||
self.assertEqual(sql('SELECT version, applied_at FROM schema_migrations ORDER BY version'), before)
|
||
self.assertEqual(sql('SELECT count(*) FROM users'), users)
|
||
|
||
def test_history_query_uses_index(self):
|
||
"""Запрос страницы истории идёт по индексу (chat_id, created_at, id), без Sort"""
|
||
alice = new_user('alice')
|
||
chat = new_chat(alice)
|
||
plan = sql("SET enable_seqscan = off; SET enable_bitmapscan = off; EXPLAIN SELECT id FROM messages WHERE chat_id = '%s' "
|
||
"ORDER BY created_at, id LIMIT 51" % chat['id'])
|
||
self.assertIn('messages_chat_history_idx', plan)
|
||
self.assertNotIn('Sort', plan)
|
||
|
||
|
||
if __name__ == '__main__':
|
||
unittest.main()
|