99 lines
5.6 KiB
Python
99 lines
5.6 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, LAB
|
|
|
|
|
|
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_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'])))
|
|
|
|
@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)
|