Files
mtusi2026lab4/student-tests/test_lab2.py
T
2026-10-24 01:03:18 +03:00

128 lines
5.8 KiB
Python

"""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()