ЛР 2: мессенджер на PostgreSQL и сессии в Redis

This commit is contained in:
2026-10-23 12:16:56 +03:00
parent 65003b6119
commit 1dd701be2b
69 changed files with 2163 additions and 30 deletions
View File
+15
View File
@@ -0,0 +1,15 @@
import os
import pytest
from tests.client import Client
@pytest.fixture
def client():
return Client(os.environ.get('BASE_URL'), os.environ.get('CA_FILE') or None)
@pytest.fixture
def actors(client):
return (client,) + client.bootstrap()
+9
View File
@@ -0,0 +1,9 @@
def create_chat(client, actor, title):
return client.call(
'POST',
'/api/v1/chats',
201,
actor=actor,
body={'title': title, 'member_ids': [actor['id']]},
schema='Chat',
)['json']
+39
View File
@@ -0,0 +1,39 @@
import base64
from uuid import uuid4
def test_rejects_incorrect_basic_password(client):
actor = client.user('wrong_password')
credentials = base64.b64encode(
(actor['registration']['username'] + ':definitely-wrong-password').encode('utf-8')
).decode('ascii')
client.call(
'POST',
'/api/v1/auth/sessions',
401,
headers={'Authorization': 'Basic ' + credentials},
)
def test_chat_creation_rolls_back_when_a_member_does_not_exist(client):
actor = client.user('chat_rollback')
title = 'Не должен сохраниться ' + uuid4().hex
client.call(
'POST',
'/api/v1/chats',
400,
actor=actor,
body={
'title': title,
'member_ids': [actor['id'], str(uuid4())],
},
)
chats = client.call(
'GET',
'/api/v1/chats?limit=100',
actor=actor,
schema='ChatPage',
)['json']['items']
assert all(chat['title'] != title for chat in chats)
+36
View File
@@ -0,0 +1,36 @@
import os
from concurrent.futures import ThreadPoolExecutor
from threading import Barrier
from tests.client import Client
from tests.helpers import create_chat
def test_keeps_100_concurrent_messages(actors):
_, alice, _, _, _ = actors
base_url = os.environ.get('BASE_URL')
ca_file = os.environ.get('CA_FILE') or None
seed = Client(base_url, ca_file)
chat = create_chat(seed, alice, 'Конкурентная отправка')
start = Barrier(10)
def worker(worker_number):
client = Client(base_url, ca_file)
start.wait()
return [
client.message(alice, chat, 'worker=' + str(worker_number) + '; message=' + str(index))['json']['id']
for index in range(10)
]
with ThreadPoolExecutor(max_workers=10) as pool:
sent = [message_id for batch in pool.map(worker, range(10)) for message_id in batch]
page = seed.call(
'GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100',
actor=alice, schema='MessagePage',
)['json']
received = [item['id'] for item in page['items']]
assert len(sent) == len(set(sent)) == 100
assert page['next_cursor'] is None
assert len(received) == len(set(received)) == 100
assert set(received) == set(sent)
+42
View File
@@ -0,0 +1,42 @@
from urllib.parse import quote
from tests.helpers import create_chat
def test_walks_all_pages_without_duplicates(actors):
client, alice, _, _, _ = actors
chat = create_chat(client, alice, 'Пагинация')
sent = [client.message(alice, chat, 'страница ' + str(i))['json']['id'] for i in range(5)]
received, cursor = [], None
while True:
suffix = '?limit=2'
if cursor:
suffix += '&cursor=' + quote(cursor, safe='')
page = client.call(
'GET', '/api/v1/chats/' + chat['id'] + '/messages' + suffix,
actor=alice, schema='MessagePage',
)['json']
received.extend(item['id'] for item in page['items'])
cursor = page['next_cursor']
if cursor is None:
break
assert len(received) == 5
assert len(set(received)) == 5
assert set(received) == set(sent)
def test_rejects_cursor_from_another_chat(actors):
client, alice, _, _, _ = actors
first = create_chat(client, alice, 'Первый чат')
second = create_chat(client, alice, 'Второй чат')
client.message(alice, first, 'первое')
client.message(alice, first, 'второе')
page = client.call(
'GET', '/api/v1/chats/' + first['id'] + '/messages?limit=1',
actor=alice, schema='MessagePage',
)['json']
assert page['next_cursor'] is not None
client.call(
'GET', '/api/v1/chats/' + second['id'] + '/messages?cursor=' + quote(page['next_cursor'], safe=''),
400, actor=alice,
)
+26
View File
@@ -0,0 +1,26 @@
from concurrent.futures import ThreadPoolExecutor
from threading import Barrier
from uuid import uuid4
from tests.client import Client
def test_only_one_concurrent_registration_succeeds():
username = 'race_' + uuid4().hex[:16]
body = {
'username': username,
'display_name': 'Race user',
'password': 'Race-password-' + uuid4().hex,
}
barrier = Barrier(8)
def register_once(_: int) -> int:
client = Client()
barrier.wait()
return client.call('POST', '/api/v1/users', expected=[201, 409], body=body)['status']
with ThreadPoolExecutor(max_workers=8) as pool:
statuses = list(pool.map(register_once, range(8)))
assert statuses.count(201) == 1
assert statuses.count(409) == 7
+20
View File
@@ -0,0 +1,20 @@
import os
import time
import pytest
def test_logout_revokes_current_token(client):
actor = client.user('logout')
client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=actor)
client.call('GET', '/api/v1/users/me', 401, actor=actor)
@pytest.mark.skipif(
int(os.getenv('SESSION_TTL_SECONDS', '3600')) > 2,
reason='run with SESSION_TTL_SECONDS=1 to check automatic session expiry',
)
def test_session_expires_with_short_ttl(client):
actor = client.user('expiry')
time.sleep(int(os.environ['SESSION_TTL_SECONDS']) + 0.25)
client.call('GET', '/api/v1/users/me', 401, actor=actor)
+82
View File
@@ -0,0 +1,82 @@
def test_rejects_malformed_json(client):
client.call(
'POST', '/api/v1/users', 400, raw=b'{"username":',
headers={'Content-Type': 'application/json'},
)
def test_rejects_duplicate_username(actors):
client, alice, _, _, _ = actors
client.call('POST', '/api/v1/users', 409, body=alice['registration'])
def test_hides_chat_from_outsider(actors):
client, _, _, eve, chat = actors
client.call('GET', '/api/v1/chats/' + chat['id'], 404, actor=eve)
def test_rejects_blank_message(actors):
client, alice, _, _, chat = actors
client.call(
'POST', '/api/v1/chats/' + chat['id'] + '/messages', 400,
actor=alice, body={'text': ' \t\n '},
)
def test_requires_user_header(client):
client.call('GET', '/api/v1/users/me', 401)
def test_rejects_invalid_chat_uuid(actors):
client, alice, _, _, _ = actors
client.call('GET', '/api/v1/chats/not-a-uuid', 400, actor=alice)
def test_rejects_title_longer_than_100(actors):
client, alice, _, _, _ = actors
client.call(
'POST', '/api/v1/chats', 400, actor=alice,
body={'title': 'x' * 101, 'member_ids': [alice['id']]},
)
def test_rejects_display_name_longer_than_100(client):
client.call(
'POST', '/api/v1/users', 400,
body={'username': 'long_display_name', 'display_name': 'x' * 101},
)
def test_rejects_chat_without_creator(actors):
client, alice, _, eve, _ = actors
client.call(
'POST', '/api/v1/chats', 400, actor=alice,
body={'title': 'Без создателя', 'member_ids': [eve['id']]},
)
def test_rejects_duplicate_chat_members(actors):
client, alice, _, _, _ = actors
client.call(
'POST', '/api/v1/chats', 400, actor=alice,
body={'title': 'Дубликат', 'member_ids': [alice['id'], alice['id']]},
)
def test_rejects_unexpected_json_field(client):
client.call(
'POST', '/api/v1/users', 400,
body={'username': 'extra_field', 'display_name': 'Extra field', 'role': 'admin'},
)
def test_rejects_zero_page_limit(actors):
client, alice, _, _, chat = actors
client.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=0', 400, actor=alice)
def test_rejects_invalid_cursor(actors):
client, alice, _, _, chat = actors
client.call(
'GET', '/api/v1/chats/' + chat['id'] + '/messages?cursor=not-a-cursor', 400, actor=alice,
)