Add third lab code

This commit is contained in:
2026-10-24 01:03:18 +03:00
parent ec540a1a72
commit 4c7a796795
41 changed files with 1581 additions and 0 deletions
+55
View File
@@ -0,0 +1,55 @@
"""Database atomicity and concurrent conflict checks, using isolated synthetic data."""
import unittest
from concurrent.futures import ThreadPoolExecutor
from unittest.mock import patch
from uuid import uuid4
from sqlalchemy import func, select
from sqlalchemy.orm import Session, sessionmaker
from src.database import create_db_engine
from src.errors import APIError
from src.models import Chat, IdempotencyRecord, Message
from src.store import PostgresStore
class IdempotencyTests(unittest.TestCase):
def setUp(self):
self.engine = create_db_engine()
self.store = PostgresStore()
self.store.sessions = sessionmaker(self.engine, expire_on_commit=False)
self.user = self.store.create_user('idem_' + uuid4().hex[:16], 'Idempotency', 'Synthetic-password-123')
self.chat = self.store.create_chat(self.user['id'], 'Atomic', [self.user['id']])
def tearDown(self):
self.engine.dispose()
def test_record_and_message_rollback_together(self):
real_add = Session.add
def fail_record(session, instance, *args, **kwargs):
if isinstance(instance, IdempotencyRecord):
raise RuntimeError('Simulate failure after message INSERT, before COMMIT')
return real_add(session, instance, *args, **kwargs)
args = (self.chat['id'], self.user['id'], 'atomic', 'same-key')
with patch.object(Session, 'add', fail_record):
with self.assertRaises(RuntimeError):
self.store.create_message(*args)
with Session(self.engine) as session:
self.assertEqual(session.scalar(select(func.count()).select_from(Message).where(Message.chat_id == self.chat['id'])), 0)
self.assertIsNone(session.get(IdempotencyRecord, (self.user['id'], self.chat['id'], 'same-key')))
self.assertEqual(session.get(Chat, self.chat['id']).history_version, 0)
first = self.store.create_message(*args)
self.assertEqual(self.store.create_message(*args), first)
def test_concurrent_different_payloads_have_one_winner(self):
def send(index):
try:
return self.store.create_message(self.chat['id'], self.user['id'], str(index), 'conflict'), 201
except APIError as exc:
return None, exc.status_code
with ThreadPoolExecutor(max_workers=8) as executor:
results = list(executor.map(send, range(8)))
self.assertEqual(sorted(code for _, code in results), [201] + [409] * 7)
with Session(self.engine) as session:
self.assertEqual(session.scalar(select(func.count()).select_from(Message).where(Message.chat_id == self.chat['id'])), 1)
self.assertEqual(session.get(Chat, self.chat['id']).history_version, 1)
+127
View File
@@ -0,0 +1,127 @@
"""Run inside the API container: python -m unittest discover -s student-tests -v."""
import base64
import os
import subprocess
import sys
import time
import unittest
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from uuid import uuid4
from sqlalchemy import func, select
from sqlalchemy.orm import sessionmaker
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client
from src.auth import sessions
from src.database import create_db_engine, migrate
from src.models import User, Chat, ChatMember, SchemaMigration
class Lab2Tests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.engine = create_db_engine()
cls.sessions = sessionmaker(cls.engine)
@classmethod
def tearDownClass(cls):
cls.engine.dispose()
def setUp(self):
self.client = Client('http://127.0.0.1:8080')
def test_registration_race(self):
body = {'username': 'race_' + uuid4().hex[:12], 'display_name': 'Race',
'password': 'Synthetic-password-123'}
def register(_):
return Client().call('POST', '/api/v1/users', [201, 409], body=body)['status']
with ThreadPoolExecutor(max_workers=4) as executor:
codes = list(executor.map(register, range(4)))
self.assertEqual(sorted(codes), [201, 409, 409, 409])
with self.sessions() as session:
count = session.scalar(select(func.count()).select_from(User).where(User.username == body['username']))
self.assertEqual(count, 1)
def test_chat_rollback(self):
actor = self.client.user('rollback')
title = 'rollback_' + uuid4().hex
self.client.call('POST', '/api/v1/chats', 400, actor=actor,
body={'title': title, 'member_ids': [actor['id'], str(uuid4())]})
with self.sessions() as session:
self.assertEqual(session.scalar(select(func.count()).select_from(Chat).where(Chat.title == title)), 0)
self.assertEqual(session.scalar(select(func.count()).select_from(ChatMember).where(
ChatMember.user_id == actor['id'])), 0)
def test_password_logout_and_identity(self):
actor = self.client.user('auth')
credential = base64.b64encode((actor['user']['username'] + ':Wrong-password-123').encode()).decode()
self.client.call('POST', '/api/v1/auth/sessions', 401,
headers={'Authorization': 'Basic ' + credential})
self.client.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'Basic ' + credential})
self.client.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': actor['id']})
me = self.client.call('GET', '/api/v1/users/me', actor=actor,
headers={'X-User-Id': str(uuid4())}, schema='User')['json']
self.assertEqual(me['id'], actor['id'])
ttl = sessions.client.ttl(sessions.key(actor['token']))
self.assertGreater(ttl, 0)
self.assertLessEqual(ttl, 3600)
self.client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=actor)
self.client.call('GET', '/api/v1/users/me', 401, actor=actor)
self.client.call('DELETE', '/api/v1/auth/sessions/current', 401, actor=actor)
self.assertIsNone(sessions.client.get(sessions.key(actor['token'])))
with self.sessions() as session:
encoded = session.get(User, actor['id']).password_hash
self.assertTrue(encoded.startswith('$argon2id$'))
self.assertNotIn(actor['registration']['password'], encoded)
def test_unicode_password(self):
username = 'unicode_' + uuid4().hex[:12]
password = '🙂:я' * 40
self.client.call('POST', '/api/v1/users', 201,
body={'username': username, 'display_name': 'Unicode', 'password': password})
credential = base64.b64encode((username + ':' + password).encode()).decode()
result = self.client.call('POST', '/api/v1/auth/sessions', 201,
headers={'Authorization': 'Basic ' + credential}, schema='Session')['json']
self.assertEqual(result['user']['username'], username)
def test_migrations_repeat(self):
with self.sessions() as session:
before = session.scalar(select(func.count()).select_from(User))
migrate(self.engine)
migrate(self.engine)
with self.sessions() as session:
self.assertEqual(session.scalar(select(func.count()).select_from(User)), before)
versions = set(session.scalars(select(SchemaMigration.version)))
expected = {path.name for path in (Path(__file__).resolve().parents[1] / 'migrations').glob('*.sql')}
self.assertEqual(versions, expected)
def test_expiry_short_ttl(self):
process = subprocess.Popen(
[sys.executable, '-m', 'src'],
env={**os.environ, 'SESSION_TTL_SECONDS': '2', 'APP_PORT': '8081', 'APP_HOST': '127.0.0.1'},
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
try:
client = Client('http://127.0.0.1:8081')
for _ in range(100):
try:
client.call('GET', '/health/ready')
break
except AssertionError:
self.assertIsNone(process.poll(), 'Short-TTL API exited')
time.sleep(0.1)
else:
self.fail('Short-TTL API did not become ready')
actor = client.user('expiry')
client.call('GET', '/api/v1/users/me', actor=actor, schema='User')
time.sleep(2.2)
client.call('GET', '/api/v1/users/me', 401, actor=actor)
self.assertIsNone(sessions.client.get(sessions.key(actor['token'])))
finally:
process.terminate()
process.wait(timeout=10)
if __name__ == '__main__':
unittest.main()