Files
mtusi2026lab2/student-tests/test_database.py
T
glebossokin ef96551b7d
Lab 2 application / application (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
ЛР 2: PostgreSQL, Redis-сессии и проверки на оценку 4
2026-10-26 23:25:37 +03:00

60 lines
2.7 KiB
Python

"""Run inside API container: directly observe rollback and stored password KDF."""
from pathlib import Path
import sys
import subprocess
import unittest
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
from messenger.core import APIError, Config, Store, password_matches
class Database(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.store = Store(Config.from_env())
@classmethod
def tearDownClass(cls):
cls.store.close()
def test_rollback_after_chat_insert(self):
actor = self.store.create_user(dict(username='rollback_' + uuid.uuid4().hex[:16],
display_name='Rollback', password='rollback-password'))['id']
with self.store.pool.connection() as conn:
before = conn.execute('SELECT count(*) AS n FROM chats').fetchone()['n']
members_before = conn.execute('SELECT count(*) AS n FROM chat_members').fetchone()['n']
# First membership succeeds, second violates FK after the chat was inserted.
with self.assertRaises(APIError) as raised:
self.store.create_chat(actor, dict(title='Must rollback', member_ids=[actor, str(uuid.uuid4())]))
self.assertEqual(raised.exception.status, 400)
with self.store.pool.connection() as conn:
self.assertEqual(conn.execute('SELECT count(*) AS n FROM chats').fetchone()['n'], before)
self.assertEqual(conn.execute('SELECT count(*) AS n FROM chat_members').fetchone()['n'], members_before)
def test_password_salted_kdf(self):
password = 'identical-password'
ids = [self.store.create_user(dict(username='salt_' + uuid.uuid4().hex[:20],
display_name='Salt', password=password))['id'] for _ in range(2)]
with self.store.pool.connection() as conn:
hashes = [conn.execute('SELECT password_hash FROM users WHERE id=%s', (i,)).fetchone()['password_hash'] for i in ids]
self.assertNotEqual(*hashes)
for value in hashes:
self.assertTrue(value.startswith('scrypt$16384$8$1$'))
self.assertTrue(password_matches(password, value))
self.assertNotEqual(value, password)
def test_repeat_migrations(self):
def counts():
with self.store.pool.connection() as conn:
return [conn.execute('SELECT count(*) AS n FROM ' + table).fetchone()['n']
for table in ('users', 'chats', 'chat_members', 'messages', 'schema_migrations')]
before = counts()
for _ in range(2):
subprocess.run([sys.executable, '-m', 'messenger.migrate'], check=True)
self.assertEqual(counts(), before)
if __name__ == '__main__':
unittest.main(verbosity=2)