forked from mtusi2026/mtusi2026lab2
101 lines
5.6 KiB
Python
101 lines
5.6 KiB
Python
"""Run inside the API container against the real PostgreSQL stack."""
|
|
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]))
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
|
import psycopg
|
|
from client import Client
|
|
from app.config import secret
|
|
from app.migrate import migrate
|
|
from app.storage import token_hash
|
|
|
|
|
|
class IntegrationTests(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.c = Client('http://127.0.0.1:8080')
|
|
cls.alice, cls.bob, cls.eve, cls.chat = cls.c.bootstrap()
|
|
|
|
def test_registration_race_and_password_storage(self):
|
|
body = {'username': 'race_' + uuid.uuid4().hex[:16], 'display_name': 'Гонка', 'password': 'пароль:🔑' * 16}
|
|
def register(_):
|
|
return Client('http://127.0.0.1:8080').call('POST', '/api/v1/users', [201,409], body=body)['status']
|
|
with ThreadPoolExecutor(max_workers=4) as pool:
|
|
codes = list(pool.map(register, range(4)))
|
|
self.assertEqual(sorted(codes), [201,409,409,409])
|
|
credential = base64.b64encode((body['username'] + ':' + body['password']).encode()).decode()
|
|
session = self.c.call('POST','/api/v1/auth/sessions',201,headers={'Authorization': 'Basic ' + credential},schema='Session')['json']
|
|
with psycopg.connect(secret('DATABASE_URL')) as conn:
|
|
hashed = conn.execute('SELECT password_hash FROM users WHERE username=%s', (body['username'],)).fetchone()[0]
|
|
self.assertTrue(hashed.startswith('$argon2id$'))
|
|
self.assertNotEqual(hashed, body['password'])
|
|
self.assertEqual(len(base64.urlsafe_b64decode(session['token'] + '=')), 32)
|
|
stored = conn.execute('SELECT token_hash FROM sessions WHERE token_hash=%s', (token_hash(session['token']),)).fetchone()[0]
|
|
self.assertNotEqual(stored, session['token'])
|
|
|
|
def test_rollback_after_partial_chat_insert(self):
|
|
title = 'rollback_' + uuid.uuid4().hex
|
|
self.c.call('POST','/api/v1/chats',400,actor=self.alice,
|
|
body={'title':title,'member_ids':[self.alice['id'],str(uuid.uuid4())]})
|
|
with psycopg.connect(secret('DATABASE_URL')) as conn:
|
|
count = conn.execute('SELECT count(*) FROM chats WHERE title=%s',(title,)).fetchone()[0]
|
|
self.assertEqual(count,0, 'failed chat creation must roll back inserted chat')
|
|
|
|
def test_logout_revokes_session(self):
|
|
actor = self.c.user('logout')
|
|
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)
|
|
self.c.call('DELETE','/api/v1/auth/sessions/current',401,actor=actor)
|
|
|
|
def test_history_and_cross_chat_cursor(self):
|
|
chat = self.c.call('POST','/api/v1/chats',201,actor=self.alice,
|
|
body={'title':'Cursor','member_ids':[self.alice['id']]},schema='Chat')['json']
|
|
sent = [self.c.message(self.alice,chat,'Строка ' + str(i))['json'] for i in range(5)]
|
|
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
|
page = self.c.call('GET',path+'?limit=2',actor=self.alice,schema='MessagePage')['json']
|
|
received = page['items'][:]
|
|
foreign = '/api/v1/chats/' + self.chat['id'] + '/messages?cursor=' + quote(page['next_cursor'],safe='')
|
|
self.c.call('GET',foreign,400,actor=self.alice)
|
|
while page['next_cursor']:
|
|
page = self.c.call('GET',path+'?limit=1&cursor='+quote(page['next_cursor'],safe=''),actor=self.alice,schema='MessagePage')['json']
|
|
received.extend(page['items'])
|
|
self.assertEqual(sent,received)
|
|
for query in ('cursor=broken','cursor=','limit=','limit=101','limit=1.5'):
|
|
self.c.call('GET',path+'?'+query,400,actor=self.alice)
|
|
self.c.call('GET',path,404,actor=self.eve)
|
|
self.c.call('GET','/api/v1/chats/not-a-uuid/messages',401)
|
|
|
|
def test_migrations_are_repeatable(self):
|
|
def counts():
|
|
with psycopg.connect(secret('DATABASE_URL')) as conn:
|
|
return conn.execute('SELECT (SELECT count(*) FROM schema_migrations), (SELECT count(*) FROM users), (SELECT count(*) FROM chats)').fetchone()
|
|
before = counts()
|
|
migrate()
|
|
migrate()
|
|
self.assertEqual(counts(),before)
|
|
|
|
def test_bad_credentials_and_validation(self):
|
|
actor = self.c.user('negative')
|
|
for credential in ('!!!',base64.b64encode((actor['registration']['username']+':wrong-password').encode()).decode(),
|
|
base64.b64encode(b'unknown_user:wrong-password').decode()):
|
|
response = self.c.call('POST','/api/v1/auth/sessions',401,headers={'Authorization':'Basic '+credential})
|
|
self.assertEqual(response['json']['error']['message'],'Invalid credentials')
|
|
self.c.call('GET','/api/v1/users/me',401,headers={'Authorization':'Bearer not-a-session'})
|
|
self.c.call('POST','/api/v1/users',400,raw=b'{broken',headers={'Content-Type':'application/json'})
|
|
self.c.call('POST','/api/v1/users',400,body={**actor['registration'],'extra':True})
|
|
self.c.call('POST','/api/v1/users',400,body={**actor['registration'],'password':'short'})
|
|
self.c.call('POST','/api/v1/users',400,body={**actor['registration'],'username':'bad\n'})
|
|
self.c.call('POST','/api/v1/users',400,raw=json.dumps({**actor['registration'],'display_name':'\ud800'}).encode(),headers={'Content-Type':'application/json'})
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main(verbosity=2)
|