Files
mtusi2026lab2/student-tests/test_api.py
T

90 lines
4.8 KiB
Python

"""Own black-box tests; synthetic data, standard library, no tokens in output."""
import base64
from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
import sys
import unittest
from urllib.parse import quote
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client
class API(unittest.TestCase):
def setUp(self):
self.c = Client()
def test_registration_race(self):
body = dict(username='race_' + uuid.uuid4().hex[:20], display_name='Гонка', password='Unicode:пароль🔑123')
def register(_):
return self.c.call('POST', '/api/v1/users', [201, 409], body=body)['status']
with ThreadPoolExecutor(max_workers=10) as pool:
statuses = list(pool.map(register, range(10)))
self.assertEqual(statuses.count(201), 1)
self.assertEqual(statuses.count(409), 9)
def test_validation_access_and_pagination(self):
self.c.call('POST', '/api/v1/users', 400,
body=dict(username='spaces_' + uuid.uuid4().hex[:20], display_name='Invalid', password=' ' * 12))
alice, bob, eve, chat = self.c.bootstrap()
path = '/api/v1/chats/' + chat['id']
for raw in (b'{', b'{"text":NaN}', b'{"text":"a","text":"b"}', b'[]'):
self.c.call('POST', path + '/messages', 400, actor=alice, raw=raw,
headers={'Content-Type': 'application/json'})
for body in ({'text': ' '}, {'text': 'hi', 'sender_id': eve['id']}, {'text': 2}, {'text': '\x00'}):
self.c.call('POST', path + '/messages', 400, actor=alice, body=body)
self.c.call('POST', path + '/messages', 404, actor=eve, body={'text': 'нет доступа'})
self.c.call('POST', '/api/v1/users', 409, body=alice['registration'])
for members in ([alice['id'], str(uuid.uuid4())], [bob['id']], [alice['id'], alice['id']]):
self.c.call('POST', '/api/v1/chats', 400, actor=alice,
body={'title': 'Invalid membership', 'member_ids': members})
sent = [self.c.message(alice, chat, 'Страница ' + str(i))['json'] for i in range(7)]
read, cursor = [], None
while True:
query = '?limit=2' + ('&cursor=' + quote(cursor, safe='') if cursor else '')
page = self.c.call('GET', path + '/messages' + query, actor=bob, schema='MessagePage')['json']
read.extend(page['items'])
cursor = page['next_cursor']
if cursor is None:
break
self.assertEqual(read, sorted(sent, key=lambda x: (x['created_at'], x['id'])))
first = self.c.call('GET', path + '/messages?limit=1', actor=alice, schema='MessagePage')['json']
other = self.c.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Другой чат', 'member_ids': [alice['id']]}, schema='Chat')['json']
self.c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + first['next_cursor'], 400, actor=alice)
self.c.call('GET', path + '/messages?cursor=broken', 400, actor=alice)
def test_concurrent_messages(self):
alice, _, _, chat = self.c.bootstrap()
def send(i):
return self.c.message(alice, chat, 'Concurrent ' + str(i))['json']['id']
with ThreadPoolExecutor(max_workers=10) as pool:
ids = list(pool.map(send, range(100)))
page = self.c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100',
actor=alice, schema='MessagePage')['json']
self.assertEqual(len(set(ids)), 100)
self.assertEqual({x['id'] for x in page['items']}, set(ids))
self.assertIsNone(page['next_cursor'])
def test_unicode_password_and_logout(self):
username = 'utf_' + uuid.uuid4().hex[:20]
password = '🔑:пароль' * 16 # 128 code points, far more than bcrypt's 72 bytes
self.assertEqual(len(password), 128)
self.c.call('POST', '/api/v1/users', 201,
body=dict(username=username, display_name='Unicode', password=password), schema='User')
def login(value, expected):
auth = base64.b64encode((username + ':' + value).encode()).decode()
return self.c.call('POST', '/api/v1/auth/sessions', expected,
headers={'Authorization': 'Basic ' + auth}, schema='Session' if expected == 201 else None)
actor = {'token': login(password, 201)['json']['token']}
login('incorrect-password', 401)
self.c.call('GET', '/api/v1/users/me', actor=actor, schema='User')
self.c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=actor)
self.c.call('GET', '/api/v1/users/me', 401, actor=actor)
if __name__ == '__main__':
unittest.main(verbosity=2)