forked from mtusi2026/mtusi2026lab3
132 lines
6.6 KiB
Python
132 lines
6.6 KiB
Python
"""Integration tests: real PostgreSQL and Redis, isolated synthetic identities."""
|
|
import base64
|
|
import json
|
|
import time
|
|
import uuid
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
|
|
import pytest
|
|
from fastapi.testclient import TestClient
|
|
from messenger.app import create_app
|
|
|
|
PASSWORD = 'Тестовый:пароль🔐' * 8
|
|
|
|
@pytest.fixture
|
|
def client():
|
|
with TestClient(create_app()) as c:
|
|
yield c
|
|
|
|
def user(c):
|
|
body = dict(username='u_' + uuid.uuid4().hex[:24], display_name='Алиса 👋', password=PASSWORD)
|
|
r = c.post('/api/v1/users', json=body)
|
|
assert r.status_code == 201, r.text
|
|
return r.json(), body
|
|
|
|
def login(c, body):
|
|
credentials = base64.b64encode((body['username'] + ':' + body['password']).encode()).decode()
|
|
r = c.post('/api/v1/auth/sessions', headers={'Authorization': 'Basic ' + credentials})
|
|
assert r.status_code == 201, r.text
|
|
return {'Authorization': 'Bearer ' + r.json()['token']}, r.json()
|
|
|
|
def test_auth_unicode_logout_and_cache(client):
|
|
u, body = user(client)
|
|
h, session = login(client, body)
|
|
assert session['user'] == u
|
|
assert len(session['token']) >= 43
|
|
key = 'user:' + u['id']
|
|
client.app.state.db.cache.delete(key)
|
|
for _ in range(2):
|
|
assert client.get('/api/v1/users/me', headers=h).json() == u
|
|
cached = json.loads(client.app.state.db.cache.get(key))
|
|
assert cached == u
|
|
assert 0 < client.app.state.db.cache.ttl(key) <= 60
|
|
assert client.delete('/api/v1/auth/sessions/current', headers=h).status_code == 204
|
|
r = client.get('/api/v1/users/me', headers=h)
|
|
assert r.status_code == 401
|
|
assert r.headers['www-authenticate'] == 'Bearer realm="messenger"'
|
|
assert r.json()['error']['request_id'] == r.headers['x-request-id']
|
|
|
|
def test_session_expiry(monkeypatch):
|
|
monkeypatch.setenv('SESSION_TTL_SECONDS', '2')
|
|
with TestClient(create_app()) as client:
|
|
_, body = user(client)
|
|
h, _ = login(client, body)
|
|
assert client.get('/api/v1/users/me', headers=h).status_code == 200
|
|
time.sleep(2.1)
|
|
assert client.get('/api/v1/users/me', headers=h).status_code == 401
|
|
|
|
def test_registration_race(client):
|
|
body = dict(username='race_' + uuid.uuid4().hex[:22], display_name='Race', password=PASSWORD)
|
|
with ThreadPoolExecutor(max_workers=6) as executor:
|
|
codes = list(executor.map(lambda _: client.post('/api/v1/users', json=body).status_code, range(6)))
|
|
assert sorted(codes) == [201, 409, 409, 409, 409, 409]
|
|
|
|
def test_chat_rollback_after_insert(client):
|
|
u, body = user(client)
|
|
h, _ = login(client, body)
|
|
title = 'rollback_' + uuid.uuid4().hex
|
|
r = client.post('/api/v1/chats', headers=h, json={'title': title, 'member_ids': [u['id'], str(uuid.uuid4())]})
|
|
assert r.status_code == 400
|
|
with client.app.state.db.pool.connection() as conn:
|
|
assert conn.execute('SELECT count(*) AS n FROM chats WHERE title=%s', (title,)).fetchone()['n'] == 0
|
|
assert conn.execute('SELECT count(*) AS n FROM chat_members m LEFT JOIN chats c ON c.id=m.chat_id WHERE c.id IS NULL').fetchone()['n'] == 0
|
|
|
|
def test_cursor_access_and_strict_validation(client):
|
|
a, ab = user(client)
|
|
b, bb = user(client)
|
|
ah, _ = login(client, ab)
|
|
bh, _ = login(client, bb)
|
|
chats = [client.post('/api/v1/chats', headers=ah, json={'title':'Чат','member_ids':[a['id']]}).json() for _ in range(2)]
|
|
path = '/api/v1/chats/' + chats[0]['id']
|
|
for text in ['Один 👋', 'Два', 'Три']:
|
|
assert client.post(path+'/messages', headers={**ah,'Idempotency-Key':uuid.uuid4().hex}, json={'text':text}).status_code == 201
|
|
p = client.get(path+'/messages?limit=2', headers=ah).json()
|
|
assert [m['text'] for m in p['items']] == ['Один 👋','Два']
|
|
tail = client.get(path+'/messages', headers=ah, params={'cursor':p['next_cursor'],'limit':1}).json()
|
|
assert [m['text'] for m in tail['items']] == ['Три']
|
|
assert tail['next_cursor'] is None
|
|
r = client.get('/api/v1/chats/'+chats[1]['id']+'/messages',headers=ah, params={'cursor':p['next_cursor']})
|
|
assert r.status_code == 400
|
|
assert client.get(path, headers=bh).status_code == 404
|
|
for payload in [{'text':123}, {'text':' '}, {'text':'ok','sender_id':b['id']}, {'text':'x'*4001}]:
|
|
assert client.post(path+'/messages',headers={**ah,'Idempotency-Key':uuid.uuid4().hex},json=payload).status_code == 400
|
|
for query in ['limit=0','limit=101','limit=1.0','cursor=bad','cursor=']:
|
|
assert client.get(path+'/messages?'+query,headers=ah).status_code == 400
|
|
for payload in [{'username':123,'display_name':'a','password':PASSWORD}, {'username':'valid','display_name':' ','password':PASSWORD}]:
|
|
assert client.post('/api/v1/users',json=payload).status_code == 400
|
|
assert client.post('/api/v1/users',content='{',headers={'Content-Type':'application/json'}).status_code == 400
|
|
|
|
def test_session_storage_and_migrations(client):
|
|
from messenger.migrate import main as migrate
|
|
u, body = user(client)
|
|
_, session = login(client, body)
|
|
db = client.app.state.db
|
|
def snapshot():
|
|
with db.pool.connection() as conn:
|
|
return {table: conn.execute('SELECT count(*) AS n FROM '+table).fetchone()['n']
|
|
for table in ['users','chats','chat_members','messages','sessions','schema_migrations','idempotency_records']}
|
|
before = snapshot()
|
|
migrate()
|
|
migrate()
|
|
assert snapshot() == before
|
|
with db.pool.connection() as conn:
|
|
row = conn.execute('SELECT token_hash,expires_at FROM sessions WHERE user_id=%s', (u['id'],)).fetchone()
|
|
assert row['token_hash'] != session['token']
|
|
assert len(row['token_hash']) == 64
|
|
stored = conn.execute('SELECT password_hash FROM users WHERE id=%s', (u['id'],)).fetchone()['password_hash']
|
|
assert stored.startswith('$argon2id$')
|
|
assert stored != body['password']
|
|
|
|
def test_json_media_type_and_utf8(client):
|
|
body = dict(username='media_' + uuid.uuid4().hex[:24], display_name='UTF8', password=PASSWORD)
|
|
raw = json.dumps(body).encode()
|
|
for headers in [{}, {'Content-Type':'text/plain'}, {'Content-Type':'application/xml'}]:
|
|
r = client.post('/api/v1/users',content=raw,headers=headers)
|
|
assert r.status_code == 415
|
|
assert r.json()['error']['code'] == 'unsupported_media_type'
|
|
for encoding in ['utf-16', 'utf-16-le', 'utf-16-be', 'utf-32-le', 'utf-32-be']:
|
|
r = client.post('/api/v1/users',content=json.dumps(body).encode(encoding),headers={'Content-Type':'application/json'})
|
|
assert r.status_code == 400, encoding
|
|
r = client.post('/api/v1/chats',content=b'{}',headers={'Content-Type':'text/plain'})
|
|
assert r.status_code == 401
|