forked from mtusi2026/mtusi2026lab2
162 lines
9.8 KiB
Python
162 lines
9.8 KiB
Python
#!/usr/bin/env python3
|
|
"""Independent black-box tests: python student-tests/acceptance.py [--base-url URL]."""
|
|
import argparse
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import json
|
|
from pathlib import Path
|
|
import sys
|
|
import unittest
|
|
import uuid
|
|
from urllib.parse import quote
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
|
from client import Client
|
|
|
|
BASE = 'http://127.0.0.1:8080'
|
|
|
|
|
|
class Acceptance(unittest.TestCase):
|
|
def setUp(self):
|
|
self.c = Client(BASE)
|
|
self.alice, self.bob, self.eve, self.chat = self.c.bootstrap()
|
|
self.path = '/api/v1/chats/' + self.chat['id']
|
|
|
|
def error(self, method, path, status, code, **kwargs):
|
|
result = self.c.call(method, path, status, **kwargs)
|
|
self.assertEqual(result['json']['error']['code'], code)
|
|
|
|
def test_invalid_json(self):
|
|
for body in (b'{', b'{}{}', b'null', b'[]', b'{"text":null}',
|
|
b'{"text":1}', b'{"Text":"x"}', b'{"text":"x","extra":0}',
|
|
b'{"text":"x","text":"y"}', b'{"text":"\xff"}',
|
|
b'{"text":"\\ud800"}', b'{"text":"\\udc00"}'):
|
|
with self.subTest(body=body):
|
|
self.error('POST', self.path+'/messages', 400, 'invalid_request',
|
|
actor=self.alice, raw=body, headers={'Content-Type': 'application/json'})
|
|
self.error('POST', self.path+'/messages', 415, 'unsupported_media_type',
|
|
actor=self.alice, raw=b'{"text":"x"}', headers={'Content-Type':'text/plain'})
|
|
|
|
def test_foreign_chat_and_authentication(self):
|
|
for path in (self.path, self.path+'/messages'):
|
|
self.error('GET', path, 404, 'not_found', actor=self.eve)
|
|
self.error('GET', path, 401, 'unauthorized')
|
|
self.error('POST', self.path+'/messages', 404, 'not_found', actor=self.eve, raw=b'{')
|
|
self.error('GET', '/api/v1/users/me', 401, 'unauthorized', headers={'X-User-Id':self.alice['id']})
|
|
self.error('GET', '/api/v1/users/me', 401, 'unauthorized', headers={'X-User-Id':'broken'})
|
|
for actor in (self.alice, self.bob):
|
|
me = self.c.call('GET', '/api/v1/users/me', actor=actor, schema='User')['json']
|
|
self.assertEqual(me, actor['user'])
|
|
msg = self.c.message(actor, self.chat, 'identity')['json']
|
|
self.assertEqual(msg['sender_id'], actor['id'])
|
|
self.error('POST', self.path+'/messages', 400, 'invalid_request', actor=self.alice,
|
|
body={'text':'forged','sender_id':self.bob['id']})
|
|
|
|
def test_empty_and_unicode_message(self):
|
|
for text in ('', ' \t\n', '\u2003\u00a0', '😀'*4001):
|
|
self.error('POST', self.path+'/messages', 400, 'invalid_request', actor=self.alice, body={'text':text})
|
|
for text in ('Привет, 世界 👋 e\u0301', '😀'*4000, '\ufffd', 'literal \\ud800', '\u0000'*4000):
|
|
sent = self.c.message(self.alice, self.chat, text)['json']
|
|
self.assertEqual(sent['text'], text)
|
|
escaped = self.c.call('POST', self.path+'/messages', 201, actor=self.alice,
|
|
raw=b'{"text":"\\ud83d\\ude00"}',
|
|
headers={'Content-Type':'application/json'}, schema='Message')['json']
|
|
self.assertEqual(escaped['text'], '😀')
|
|
history = self.c.call('GET', self.path+'/messages', actor=self.bob, schema='MessagePage')['json']
|
|
self.assertEqual(len(history['items']), 6)
|
|
|
|
def test_duplicate_username_and_user_validation(self):
|
|
self.error('POST', '/api/v1/users', 409, 'conflict', body=self.alice['registration'])
|
|
for name in ('ab', 'Upper', 'русский', 'a'*33, 'a b'):
|
|
self.error('POST', '/api/v1/users', 400, 'invalid_request', body={'username':name,'display_name':'X','password':'test-password-123'})
|
|
for display in (' ', '😀'*101, None, 1):
|
|
self.error('POST', '/api/v1/users', 400, 'invalid_request', body={'username':'valid_name','display_name':display,'password':'test-password-123'})
|
|
self.c.call('POST', '/api/v1/users', 201, body={'username':'u_'+uuid.uuid4().hex[:20], 'display_name':'😀'*100,'password':'test-password-123'}, schema='User')
|
|
|
|
def test_membership_validation(self):
|
|
for ids in ([], [self.bob['id']], [self.alice['id']]*2, [str(uuid.uuid4()),self.alice['id']],
|
|
[self.alice['id'],'bad'], None, [None], [self.alice['id'].upper(), self.alice['id']]):
|
|
self.error('POST', '/api/v1/chats', 400, 'invalid_request', actor=self.alice, body={'title':'chat','member_ids':ids})
|
|
for title in (' ', '😀'*101, None):
|
|
self.error('POST', '/api/v1/chats', 400, 'invalid_request', actor=self.alice, body={'title':title,'member_ids':[self.alice['id']]})
|
|
listed = self.c.call('GET', '/api/v1/chats', actor=self.alice, schema='ChatPage')['json']
|
|
self.assertEqual(len(listed['items']), 1)
|
|
|
|
def pages(self, path, actor, schema, sizes=(3, 7, 2)):
|
|
items, cursor, page_number = [], None, 0
|
|
while True:
|
|
query = '?limit='+str(sizes[page_number % len(sizes)])
|
|
if cursor:
|
|
query += '&cursor='+quote(cursor, safe='')
|
|
result = self.c.call('GET', path+query, actor=actor, schema=schema)['json']
|
|
items.extend(result['items'])
|
|
cursor = result['next_cursor']
|
|
page_number += 1
|
|
self.assertLess(page_number, 1000)
|
|
if cursor is None:
|
|
break
|
|
self.assertEqual(len(items), len({item['id'] for item in items}))
|
|
self.assertEqual(items, sorted(items, key=lambda item:(item['created_at'], item['id'])))
|
|
return items
|
|
|
|
def test_multiple_pages_and_cursor_scope(self):
|
|
sent = [self.c.message(self.alice, self.chat, 'page '+str(i))['json'] for i in range(23)]
|
|
self.assertEqual(self.pages(self.path+'/messages', self.bob, 'MessagePage'), sent)
|
|
for _ in range(11):
|
|
self.c.call('POST', '/api/v1/chats', 201, actor=self.alice,
|
|
body={'title':'page','member_ids':[self.alice['id']]}, schema='Chat')
|
|
self.assertEqual(len(self.pages('/api/v1/chats',self.alice,'ChatPage')),12)
|
|
self.assertEqual(len(self.pages('/api/v1/chats',self.bob,'ChatPage')),1)
|
|
cursor = self.c.call('GET', self.path+'/messages?limit=1',actor=self.alice,schema='MessagePage')['json']['next_cursor']
|
|
other = self.c.call('POST','/api/v1/chats',201,actor=self.alice,body={'title':'other','member_ids':[self.alice['id']]},schema='Chat')['json']
|
|
self.error('GET','/api/v1/chats/'+other['id']+'/messages?cursor='+quote(cursor),400,'invalid_request',actor=self.alice)
|
|
for query in ('limit=0','limit=101','limit=1.5','limit=true','limit=','limit=1&limit=2','cursor=', 'cursor=bad', 'cursor='+quote(cursor[:-3]+'xxx')):
|
|
self.error('GET',self.path+'/messages?'+query,400,'invalid_request',actor=self.alice)
|
|
first = self.c.call('GET', self.path+'/messages?limit=23', actor=self.alice, schema='MessagePage')['json']
|
|
self.assertIsNone(first['next_cursor'])
|
|
|
|
def test_empty_history_default_limit_and_concurrent_append(self):
|
|
empty = self.c.call('GET', self.path+'/messages', actor=self.alice, schema='MessagePage')['json']
|
|
self.assertEqual(empty, {'items':[], 'next_cursor':None})
|
|
sent = [self.c.message(self.alice,self.chat,'initial '+str(i))['json'] for i in range(51)]
|
|
first = self.c.call('GET', self.path+'/messages', actor=self.bob, schema='MessagePage')['json']
|
|
self.assertEqual(first['items'], sent[:50])
|
|
self.assertIsNotNone(first['next_cursor'])
|
|
appended = self.c.message(self.bob,self.chat,'after page one')['json']
|
|
second = self.c.call('GET', self.path+'/messages?limit=100&cursor='+quote(first['next_cursor'],safe=''),
|
|
actor=self.alice, schema='MessagePage')['json']
|
|
self.assertEqual(second['items'], [sent[-1], appended])
|
|
self.assertIsNone(second['next_cursor'])
|
|
|
|
def test_chat_cursor_bound_to_current_user(self):
|
|
self.c.call('POST','/api/v1/chats',201,actor=self.alice,
|
|
body={'title':'second shared chat','member_ids':[self.alice['id'],self.bob['id']]},schema='Chat')
|
|
first = self.c.call('GET','/api/v1/chats?limit=1',actor=self.alice,schema='ChatPage')['json']
|
|
cursor = quote(first['next_cursor'],safe='')
|
|
self.error('GET','/api/v1/chats?cursor='+cursor,400,'invalid_request',actor=self.bob)
|
|
last = self.c.call('GET','/api/v1/chats?limit=100&cursor='+cursor,actor=self.alice,schema='ChatPage')['json']
|
|
self.assertEqual(len(last['items']),1)
|
|
self.assertIsNone(last['next_cursor'])
|
|
|
|
def test_100_messages_from_10_clients(self):
|
|
actors = [self.c.user('worker') for _ in range(10)]
|
|
chat = self.c.call('POST','/api/v1/chats',201,actor=actors[0],
|
|
body={'title':'concurrency','member_ids':[a['id'] for a in actors]},schema='Chat')['json']
|
|
def worker(index):
|
|
client = Client(BASE)
|
|
return [client.message(actors[index],chat,'client %d message %d' % (index,j))['json'] for j in range(10)]
|
|
with ThreadPoolExecutor(max_workers=10) as pool:
|
|
sent = [message for batch in pool.map(worker, range(10)) for message in batch]
|
|
read = self.pages('/api/v1/chats/'+chat['id']+'/messages',actors[0],'MessagePage',(17,))
|
|
self.assertEqual(len(read),100)
|
|
self.assertEqual({m['id'] for m in read},{m['id'] for m in sent})
|
|
self.assertEqual({m['text'] for m in read},{m['text'] for m in sent})
|
|
print('CONCURRENCY: 10 clients x 10 writes = 100 acknowledged, 100 read, 100 unique',flush=True)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('--base-url', default=BASE)
|
|
args, remaining = parser.parse_known_args()
|
|
BASE = args.base_url
|
|
unittest.main(argv=[sys.argv[0]]+remaining, verbosity=2)
|