178 lines
11 KiB
Python
178 lines
11 KiB
Python
"""Extra black-box tests, without changing the course's public tests."""
|
|
import concurrent.futures
|
|
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 as PublicClient, LAB
|
|
|
|
|
|
class Client(PublicClient):
|
|
def call(self, method, path, *args, headers=None, **kwargs):
|
|
headers = dict(headers or {})
|
|
if method == 'POST' and path.endswith('/messages'):
|
|
headers.setdefault('Idempotency-Key', uuid.uuid4().hex)
|
|
return super().call(method, path, *args, headers=headers, **kwargs)
|
|
|
|
|
|
class APIContract(unittest.TestCase):
|
|
def setUp(self):
|
|
self.client = Client()
|
|
self.alice, self.bob, self.eve, self.chat = self.client.bootstrap()
|
|
self.path = '/api/v1/chats/' + self.chat['id']
|
|
|
|
def test_malformed_json_and_extra_fields(self):
|
|
for raw in (b'{', b'[]', b'{"text":"x","text":"y"}', b'{"text":NaN}', b'{"text":"\\ud800"}'):
|
|
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, raw=raw, headers={'Content-Type': 'application/json'})
|
|
for body in ({'text': 'ok', 'sender_id': self.eve['id']}, {'text': True}, {'text': ' '}, {'text': ''}, {'text': None}):
|
|
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, body=body)
|
|
deep = b'{"text":' + b'[' * 1200 + b'0' + b']' * 1200 + b'}'
|
|
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, raw=deep, headers={'Content-Type': 'application/json'})
|
|
|
|
def test_unicode_limits(self):
|
|
result = self.client.message(self.alice, self.chat, '👩' * 4000)['json']
|
|
self.assertEqual(result['text'], '👩' * 4000)
|
|
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, body={'text': '👩' * 4001})
|
|
|
|
def test_unicode_nul_round_trip(self):
|
|
import base64
|
|
value = 'A\x00B\\u0000👩'
|
|
registration = dict(self.alice['registration'], username='nul_' + uuid.uuid4().hex[:20], display_name=value)
|
|
user = self.client.call('POST', '/api/v1/users', 201, body=registration, schema='User')['json']
|
|
self.assertEqual(user['display_name'], value)
|
|
credential = base64.b64encode((registration['username'] + ':' + registration['password']).encode()).decode()
|
|
session = self.client.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': 'Basic ' + credential}, schema='Session')['json']
|
|
self.assertEqual(session['user'], user)
|
|
actor = {'id': user['id'], 'token': session['token']}
|
|
# Exercise the database path and then the Redis profile cache.
|
|
for _ in range(2):
|
|
self.assertEqual(self.client.call('GET', '/api/v1/users/me', actor=actor, schema='User')['json'], user)
|
|
chat = self.client.call('POST', '/api/v1/chats', 201, actor=actor, body={'title': value, 'member_ids': [actor['id']]}, schema='Chat')['json']
|
|
self.assertEqual(chat['title'], value)
|
|
self.assertEqual(self.client.call('GET', '/api/v1/chats/' + chat['id'], actor=actor, schema='Chat')['json'], chat)
|
|
contents = [value, '\x00' * 4000, '👩' * 3999 + '\x00']
|
|
for content in contents:
|
|
self.assertEqual(self.client.message(actor, chat, content)['json']['text'], content)
|
|
history = self.client.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=actor, schema='MessagePage')['json']
|
|
self.assertEqual([message['text'] for message in history['items']], contents)
|
|
|
|
def test_foreign_chat(self):
|
|
for suffix in ('', '/messages'):
|
|
self.client.call('GET', self.path + suffix, 404, actor=self.eve)
|
|
self.client.call('POST', self.path + '/messages', 404, actor=self.eve, body={'text': 'hidden'})
|
|
self.client.call('GET', '/api/v1/chats/' + str(uuid.uuid4()), 404, actor=self.alice)
|
|
|
|
def test_registration_race(self):
|
|
body = dict(self.alice['registration'], username='race_' + uuid.uuid4().hex[:20])
|
|
def register(_):
|
|
return Client().call('POST', '/api/v1/users', [201, 409], body=body)['status']
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
|
|
statuses = list(executor.map(register, range(10)))
|
|
self.assertEqual(statuses.count(201), 1)
|
|
self.assertEqual(statuses.count(409), 9)
|
|
|
|
def test_invalid_chat_creation(self):
|
|
members = ([self.alice['id'], self.alice['id']], [self.bob['id']], [self.alice['id'], str(uuid.uuid4())], [], [True])
|
|
for member_ids in members:
|
|
self.client.call('POST', '/api/v1/chats', 400, actor=self.alice, body={'title': 'rollback', 'member_ids': member_ids})
|
|
|
|
def test_cursor_scope_and_validation(self):
|
|
for i in range(3):
|
|
self.client.message(self.alice, self.chat, str(i))
|
|
cursor = self.client.call('GET', self.path + '/messages?limit=1', actor=self.alice, schema='MessagePage')['json']['next_cursor']
|
|
other = self.client.call('POST', '/api/v1/chats', 201, actor=self.alice, body={'title': 'other', 'member_ids': [self.alice['id']]}, schema='Chat')['json']
|
|
self.client.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + quote(cursor), 400, actor=self.alice)
|
|
for query in ('limit=0', 'limit=101', 'limit=' + '9' * 5000, 'limit=true', 'limit=1&limit=2', 'cursor=', 'cursor=bad', 'cursor=e30=', 'offset=1'):
|
|
self.client.call('GET', self.path + '/messages?' + query, 400, actor=self.alice)
|
|
|
|
def test_concurrent_messages_and_pagination(self):
|
|
def send(i):
|
|
return Client().message(self.alice if i % 2 else self.bob, self.chat, 'parallel-' + str(i))['json']
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
|
|
sent = list(executor.map(send, range(100)))
|
|
found = []
|
|
cursor = None
|
|
while True:
|
|
url = self.path + '/messages?limit=7' + ('&cursor=' + quote(cursor) if cursor else '')
|
|
page = self.client.call('GET', url, actor=self.alice, schema='MessagePage')['json']
|
|
found.extend(page['items'])
|
|
cursor = page['next_cursor']
|
|
if cursor is None:
|
|
break
|
|
self.assertEqual(len(found), 100)
|
|
self.assertEqual(len({v['id'] for v in found}), 100)
|
|
self.assertEqual({v['id'] for v in found}, {v['id'] for v in sent})
|
|
self.assertEqual(found, sorted(found, key=lambda v: (v['created_at'], v['id'])))
|
|
|
|
def test_idempotency_concurrent_replicas(self):
|
|
key = uuid.uuid4().hex
|
|
def send(_):
|
|
return Client().message(self.alice, self.chat, 'Один раз\x00👩', key=key)
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
|
|
replies = list(executor.map(send, range(32)))
|
|
self.assertGreaterEqual(len({v['headers']['X-Instance-Id'] for v in replies}), 2)
|
|
self.assertTrue(all(v['json'] == replies[0]['json'] for v in replies))
|
|
page = self.client.call('GET', self.path + '/messages', actor=self.bob, schema='MessagePage')['json']
|
|
self.assertEqual(page['items'], [replies[0]['json']])
|
|
self.client.call('POST', self.path + '/messages', 409, actor=self.alice, body={'text': 'different'}, headers={'Idempotency-Key': key})
|
|
self.client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=self.alice)
|
|
self.client.call('POST', self.path + '/messages', 401, actor=self.alice, body={'text': 'Один раз\x00👩'}, headers={'Idempotency-Key': key})
|
|
|
|
def test_protocol_error_headers(self):
|
|
self.client.call('TRACE', '/api/v1/users/me', 400, actor=self.alice)
|
|
|
|
def test_idempotency_scope(self):
|
|
key = uuid.uuid4().hex
|
|
one = self.client.message(self.alice, self.chat, 'same', key=key)['json']
|
|
two = self.client.message(self.bob, self.chat, 'same', key=key)['json']
|
|
other = self.client.call('POST', '/api/v1/chats', 201, actor=self.alice, body={'title': 'scope', 'member_ids': [self.alice['id']]}, schema='Chat')['json']
|
|
three = self.client.message(self.alice, other, 'same', key=key)['json']
|
|
self.assertEqual(len({one['id'], two['id'], three['id']}), 3)
|
|
|
|
def test_idempotency_semantic_body(self):
|
|
key = uuid.uuid4().hex
|
|
one = self.client.message(self.alice, self.chat, 'semantic', key=key)['json']
|
|
two = self.client.call('POST', self.path + '/messages', 201, actor=self.alice, body={'attachment_ids': [], 'text': 'semantic'}, headers={'Idempotency-Key': key}, schema='Message')['json']
|
|
self.assertEqual(one, two)
|
|
|
|
def test_idempotency_invalid_keys(self):
|
|
for key in (None, '', 'x' * 129, 'space key', 'bad,key', 'slash/key'):
|
|
headers = {} if key is None else {'Idempotency-Key': key}
|
|
PublicClient().call('POST', self.path + '/messages', 400, actor=self.alice, body={'text': 'valid'}, headers=headers)
|
|
for raw in (b'{"text":true}', b'{"text":"ok","extra":1}', b'{"text":"ok","attachment_ids":false}'):
|
|
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, raw=raw, headers={'Content-Type': 'application/json'})
|
|
|
|
def test_idempotency_conflicting_race(self):
|
|
key = uuid.uuid4().hex
|
|
def send(i):
|
|
return Client().call('POST', self.path + '/messages', [201, 409], actor=self.alice, body={'text': str(i % 2)}, headers={'Idempotency-Key': key}, schema=None)
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
|
|
replies = list(executor.map(send, range(32)))
|
|
self.assertEqual(sum(v['status'] == 201 for v in replies), 16)
|
|
self.assertEqual(sum(v['status'] == 409 for v in replies), 16)
|
|
page = self.client.call('GET', self.path + '/messages', actor=self.alice, schema='MessagePage')['json']
|
|
self.assertEqual(len(page['items']), 1)
|
|
|
|
@unittest.skipUnless(LAB >= 2, 'sessions start in lab2')
|
|
def test_unicode_password_basic_and_logout(self):
|
|
import base64
|
|
registration = {'username': 'unicode_' + uuid.uuid4().hex[:16], 'display_name': 'Софья', 'password': '🔐' * 127 + ':'}
|
|
self.client.call('POST', '/api/v1/users', 201, body=registration)
|
|
encoded = base64.b64encode((registration['username'] + ':' + registration['password']).encode()).decode()
|
|
headers = {'Authorization': 'Basic ' + encoded}
|
|
session = self.client.call('POST', '/api/v1/auth/sessions', 201, headers=headers, schema='Session')['json']
|
|
actor = {'id': session['user']['id'], 'token': session['token']}
|
|
self.client.call('GET', '/api/v1/users/me', actor=actor)
|
|
self.client.call('GET', '/api/v1/users/me', 401, headers=headers)
|
|
for authorization in ('Basic !!!', 'Bearer wrong', '', 'Basic Zm9v'):
|
|
self.client.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': authorization})
|
|
self.client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=actor)
|
|
self.client.call('GET', '/api/v1/users/me', 401, actor=actor)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main(verbosity=2)
|