forked from mtusi2026/mtusi2026lab2
153 lines
8.9 KiB
Python
153 lines
8.9 KiB
Python
"""Independent HTTP checks against the real PostgreSQL/Valkey Compose stack."""
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import base64
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import sys
|
|
import threading
|
|
import unittest
|
|
from urllib.parse import quote
|
|
import uuid
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / 'tests'))
|
|
from client import Client
|
|
|
|
|
|
def basic(username,password):
|
|
return 'Basic ' + base64.b64encode((username + ':' + password).encode()).decode()
|
|
|
|
|
|
class APItests(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.base = os.environ.get('BASE_URL','http://localhost:8082')
|
|
cls.c = Client(cls.base)
|
|
cls.c.call('GET','/health/ready',schema='Health')
|
|
|
|
def setUp(self):
|
|
self.alice,self.bob,self.eve,self.chat = self.c.bootstrap()
|
|
self.path = '/api/v1/chats/' + self.chat['id']
|
|
|
|
def test_malformed_json_and_types(self):
|
|
for raw in (b'{',b'null',b'[]',b'{} {}',b'\xff',b'{"username":NaN}',b'{"username":"one","username":"two"}'):
|
|
self.c.call('POST','/api/v1/users',400,raw=raw,headers={'Content-Type':'application/json'})
|
|
valid = dict(self.alice['registration'])
|
|
for field, value in [('username',True),('username','ab'),('display_name',None),('display_name',123),('password',False),('password','a'*11),('password','a'*129)]:
|
|
self.c.call('POST','/api/v1/users',400,body={**valid,field:value})
|
|
self.c.call('POST','/api/v1/users',400,body={**valid,'unexpected':'x'})
|
|
self.c.call('POST','/api/v1/users',415,raw=b'{}',headers={'Content-Type':'text/plain'})
|
|
self.c.call('POST','/api/v1/users',413,raw=b'x'*65537,headers={'Content-Type':'application/json'})
|
|
raw=json.dumps({**valid,'display_name':'\ud800'}).encode()
|
|
self.c.call('POST','/api/v1/users',400,raw=raw,headers={'Content-Type':'application/json'})
|
|
|
|
def test_empty_message_unicode_and_sender(self):
|
|
for body in ({'text':''},{'text':'\t\n\u2003'},{'text':None},{'text':123},{'text':'🐍'*4001},{'text':'x','sender_id':self.eve['id']}):
|
|
self.c.call('POST',self.path+'/messages',400,body=body,actor=self.alice)
|
|
message=self.c.message(self.alice,self.chat,'🐍'*4000)['json']
|
|
self.assertEqual(message['sender_id'],self.alice['id'])
|
|
self.assertEqual(message['text'],'🐍'*4000)
|
|
|
|
def test_authentication_before_access_and_foreign_chat(self):
|
|
for suffix in ('','/messages'):
|
|
self.c.call('GET',self.path+suffix,404,actor=self.eve)
|
|
self.c.call('POST',self.path+'/messages',404,body={'text':'x'},actor=self.eve)
|
|
self.c.call('GET','/api/v1/chats/not-a-uuid?limit=0',401)
|
|
self.c.call('GET','/api/v1/users/me',401,headers={'X-User-Id':self.alice['id']})
|
|
me=self.c.call('GET','/api/v1/users/me',actor=self.alice,headers={'X-User-Id':self.eve['id']},schema='User')['json']
|
|
self.assertEqual(me,self.alice['user'])
|
|
|
|
def test_bad_password_unknown_username_and_basic_only_for_login(self):
|
|
known=self.alice['registration']
|
|
for authorization in ('Basic not-base64','Bearer '+self.alice['token'],basic(known['username'],'Wrong-password-123'),basic('unknown_'+uuid.uuid4().hex[:10],'Wrong-password-123')):
|
|
response=self.c.call('POST','/api/v1/auth/sessions',401,headers={'Authorization':authorization})
|
|
self.assertEqual(response['headers']['WWW-Authenticate'],'Basic realm="messenger", charset="UTF-8"')
|
|
self.assertEqual(response['json']['error']['message'],'Неверные или отсутствующие учётные данные')
|
|
self.c.call('GET','/api/v1/users/me',401,headers={'Authorization':basic(known['username'],known['password'])})
|
|
self.c.call('POST','/api/v1/auth/sessions',400,body={},headers={'Authorization':basic(known['username'],known['password'])})
|
|
|
|
def test_unicode_password_128_codepoints_and_colon(self):
|
|
username='unicode_'+uuid.uuid4().hex[:12]
|
|
password='😀'*126+':я'
|
|
user=self.c.call('POST','/api/v1/users',201,body={'username':username,'display_name':'🐍'*100,'password':password},schema='User')['json']
|
|
session=self.c.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':basic(username,password)},schema='Session')['json']
|
|
self.assertEqual(session['user'],user)
|
|
self.assertNotIn('password',user)
|
|
self.assertNotIn('password_hash',user)
|
|
self.assertGreaterEqual(len(base64.urlsafe_b64decode(session['token']+'=')),32)
|
|
|
|
def test_logout_revokes_only_current_session(self):
|
|
credentials=self.alice['registration']
|
|
session=self.c.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':basic(credentials['username'],credentials['password'])},schema='Session')['json']
|
|
other={'id':self.alice['id'],'token':session['token']}
|
|
self.c.call('DELETE','/api/v1/auth/sessions/current',204,actor=self.alice)
|
|
self.c.call('GET','/api/v1/users/me',401,actor=self.alice)
|
|
self.c.call('DELETE','/api/v1/auth/sessions/current',401,actor=self.alice)
|
|
self.c.call('GET','/api/v1/users/me',actor=other,schema='User')
|
|
|
|
def test_chat_rollback_and_membership_validation(self):
|
|
before=self.c.call('GET','/api/v1/chats',actor=self.alice,schema='ChatPage')['json']
|
|
for members in ([],[self.alice['id'],self.alice['id']],[self.bob['id']],[self.alice['id'],self.bob['id'],str(uuid.uuid4())],None,[self.alice['id'],1]):
|
|
self.c.call('POST','/api/v1/chats',400,body={'title':'ROLLBACK','member_ids':members},actor=self.alice)
|
|
self.assertEqual(before,self.c.call('GET','/api/v1/chats',actor=self.alice,schema='ChatPage')['json'])
|
|
|
|
def test_multiple_pages_bad_limits_and_cross_resource_cursor(self):
|
|
expected=[self.c.message(self.alice,self.chat,str(i))['json'] for i in range(13)]
|
|
found=[]
|
|
cursor=saved=None
|
|
while True:
|
|
path=self.path+'/messages?limit='+('2' if cursor is None else '3')
|
|
if cursor:
|
|
path+='&cursor='+quote(cursor,safe='')
|
|
page=self.c.call('GET',path,actor=self.bob,schema='MessagePage')['json']
|
|
found.extend(page['items'])
|
|
cursor=page['next_cursor']
|
|
saved=saved or cursor
|
|
if cursor is None:
|
|
break
|
|
self.assertEqual(found,expected)
|
|
other=self.c.call('POST','/api/v1/chats',201,body={'title':'Other','member_ids':[self.alice['id']]},actor=self.alice,schema='Chat')['json']
|
|
self.c.call('GET','/api/v1/chats/'+other['id']+'/messages?cursor='+quote(saved,safe=''),400,actor=self.alice)
|
|
for query in ('limit=0','limit=101','limit=1.5','limit=true','limit=-1','limit=1&limit=2','cursor=','cursor=bad'):
|
|
self.c.call('GET',self.path+'/messages?'+query,400,actor=self.alice)
|
|
|
|
def test_read_after_write_during_pagination(self):
|
|
expected=[self.c.message(self.alice,self.chat,str(i))['json'] for i in range(3)]
|
|
first=self.c.call('GET',self.path+'/messages?limit=2',actor=self.alice,schema='MessagePage')['json']
|
|
late=self.c.message(self.bob,self.chat,'late')['json']
|
|
rest=self.c.call('GET',self.path+'/messages?cursor='+quote(first['next_cursor'],safe=''),actor=self.alice,schema='MessagePage')['json']
|
|
self.assertEqual(first['items']+rest['items'],expected+[late])
|
|
|
|
def test_100_messages_10_clients(self):
|
|
actors=[self.alice,self.bob]+[self.c.user('writer') for _ in range(8)]
|
|
chat=self.c.call('POST','/api/v1/chats',201,body={'title':'Concurrency','member_ids':[a['id'] for a in actors]},actor=self.alice,schema='Chat')['json']
|
|
barrier=threading.Barrier(10)
|
|
def worker(index):
|
|
local=Client(self.base)
|
|
barrier.wait()
|
|
return [local.message(actors[index],chat,f'{index}:{i}')['json'] for i in range(10)]
|
|
with ThreadPoolExecutor(max_workers=10) as pool:
|
|
sent=[m for values in pool.map(worker,range(10)) for m in values]
|
|
page=self.c.call('GET','/api/v1/chats/'+chat['id']+'/messages?limit=100',actor=self.alice,schema='MessagePage')['json']
|
|
self.assertEqual(len(page['items']),100)
|
|
self.assertEqual(len({m['id'] for m in page['items']}),100)
|
|
self.assertEqual({m['id'] for m in sent},{m['id'] for m in page['items']})
|
|
self.assertIsNone(page['next_cursor'])
|
|
|
|
def test_racing_registration(self):
|
|
username='race_'+uuid.uuid4().hex[:12]
|
|
barrier=threading.Barrier(10)
|
|
def register(_):
|
|
local=Client(self.base)
|
|
barrier.wait()
|
|
return local.call('POST','/api/v1/users',[201,409],body={'username':username,'display_name':'Concurrent','password':'Long-password-123'},schema='User')['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)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|