Files
2026-10-09 14:57:52 +03:00

202 lines
9.3 KiB
Python

import json
import os
import socket
import subprocess
import sys
import time
import unittest
import base64
from concurrent.futures import ThreadPoolExecutor
from unittest.mock import patch
from pathlib import Path
from urllib.error import HTTPError
from urllib.request import Request, urlopen
from uuid import uuid4
from urllib.parse import urlencode
ROOT = Path(__file__).resolve().parents[1]
class APITests(unittest.TestCase):
@classmethod
def setUpClass(cls):
with socket.socket() as sock:
sock.bind(('127.0.0.1', 0))
port = sock.getsockname()[1]
cls.base_url = f'http://127.0.0.1:{port}'
cls.server = subprocess.Popen(
[sys.executable, '-m', 'src'], cwd=ROOT,
env={**os.environ, 'APP_HOST': '127.0.0.1', 'APP_PORT': str(port)},
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
cls.addClassCleanup(cls.stop_server)
for _ in range(100):
try:
with urlopen(cls.base_url + '/health/ready', timeout=1):
return
except OSError:
if cls.server.poll() is not None:
raise RuntimeError('Server stopped before startup')
time.sleep(0.1)
raise RuntimeError('Server startup timed out')
@classmethod
def stop_server(cls):
cls.server.terminate()
try:
cls.server.wait(timeout=10)
except subprocess.TimeoutExpired:
cls.server.kill()
cls.server.wait()
def call(self, method, path, status=200, body=None, actor=None, raw=None, content_type='application/json'):
headers = {'Content-Type': content_type}
if actor:
headers['X-User-Id'] = actor
data = json.dumps(body, ensure_ascii=False).encode() if body is not None else raw
request = Request(self.base_url + path, data=data, headers=headers, method=method)
try:
response = urlopen(request, timeout=10)
except HTTPError as error:
response = error
with response:
result = json.load(response)
self.assertEqual(response.status, status, result)
self.assertTrue(response.headers.get('X-Request-Id'))
if status >= 400:
self.assertEqual(result['error']['request_id'], response.headers['X-Request-Id'])
return result
def user(self):
return self.call('POST', '/api/v1/users', 201,
{'username': 'u_' + uuid4().hex[:20], 'display_name': 'Алиса 👋'})['id']
def test_users(self):
body = {'username': 'u_' + uuid4().hex[:20], 'display_name': 'Боб 👋'}
user = self.call('POST', '/api/v1/users', 201, body)
self.assertEqual(user['display_name'], body['display_name'])
self.assertTrue(user['created_at'].endswith('Z'))
self.assertEqual(self.call('GET', '/api/v1/users/me', actor=user['id']), user)
self.call('POST', '/api/v1/users', 409, body)
for actor in [None, 'bad-uuid', str(uuid4())]:
self.call('GET', '/api/v1/users/me', 401, actor=actor)
def test_validation_and_health(self):
for path in ['/health/live', '/health/ready']:
self.assertEqual(self.call('GET', path), {'status': 'ok'})
self.call('POST', '/api/v1/users', 400, raw=b'{broken')
self.call('POST', '/api/v1/users', 415, raw=b'{}', content_type='text/plain')
for body in [None, {}, {'username': 123, 'display_name': 'Name'},
{'username': 'valid', 'display_name': ' '},
{'username': 'UPPER', 'display_name': 'Name'},
{'username': 'valid', 'display_name': 'Name', 'extra': True}]:
self.call('POST', '/api/v1/users', 400, body)
self.call('GET', '/missing', 404)
def chat(self, actor, members=None):
return self.call('POST', '/api/v1/chats', 201,
{'title': 'Учебный чат', 'member_ids': members or [actor]}, actor)
def test_chats(self):
alice, bob, eve = self.user(), self.user(), self.user()
chat = self.chat(alice, [alice, bob])
path = '/api/v1/chats/' + chat['id']
self.assertEqual(self.call('GET', path, actor=bob), chat)
self.call('GET', path, 404, actor=eve)
self.call('GET', path, 401)
self.call('GET', '/api/v1/chats/not-a-uuid', 400, actor=alice)
self.call('GET', '/api/v1/chats/not-a-uuid', 401)
self.assertEqual(self.call('GET', '/api/v1/chats', actor=eve)['items'], [])
for members in [[alice, alice], [bob], [alice, str(uuid4())], [], [alice, 42]]:
self.call('POST', '/api/v1/chats', 400,
{'title': 'Чат', 'member_ids': members}, alice)
self.assertEqual(len(self.call('GET', '/api/v1/chats', actor=alice)['items']), 1)
def test_chat_pages(self):
actor = self.user()
expected = [self.chat(actor) for _ in range(4)]
expected.sort(key=lambda item: (item['created_at'], item['id']))
page = self.call('GET', '/api/v1/chats?limit=1', actor=actor)
self.assertEqual(page['items'], expected[:1])
query = urlencode({'limit': 100, 'cursor': page['next_cursor']})
last = self.call('GET', '/api/v1/chats?' + query, actor=actor)
self.assertEqual(last['items'], expected[1:])
self.assertIsNone(last['next_cursor'])
self.call('GET', '/api/v1/chats?' + query, 400, actor=self.user())
for query in ['limit=0', 'limit=101', 'limit=1.0', 'limit=true', 'cursor=', 'cursor=bad']:
self.call('GET', '/api/v1/chats?' + query, 400, actor=actor)
def test_messages_and_cursors(self):
alice, bob, eve = self.user(), self.user(), self.user()
chat = self.chat(alice, [alice, bob])
path = '/api/v1/chats/' + chat['id'] + '/messages'
self.assertEqual(self.call('GET', path, actor=alice), {'items': [], 'next_cursor': None})
messages = [self.call('POST', path, 201, {'text': text}, alice)
for text in ['Привет 👋', 'Second', '🙂' * 4000]]
self.assertEqual(messages[0]['sender_id'], alice)
self.assertEqual(messages[-1]['text'], '🙂' * 4000)
messages.sort(key=lambda item: (item['created_at'], item['id']))
first = self.call('GET', path + '?limit=1', actor=bob)
query = urlencode({'limit': 2, 'cursor': first['next_cursor']})
last = self.call('GET', path + '?' + query, actor=bob)
self.assertEqual(first['items'] + last['items'], messages)
self.assertIsNone(last['next_cursor'])
other = '/api/v1/chats/' + self.chat(alice)['id'] + '/messages'
self.call('GET', other + '?' + query, 400, actor=alice)
for body in [{'text': ''}, {'text': ' \n\t'}, {'text': 'a' * 4001},
{'text': 123}, {'text': 'Hi', 'sender_id': bob}]:
self.call('POST', path, 400, body, alice)
for method, body in [('GET', None), ('POST', {'text': 'No access'})]:
self.call(method, path, 404, body, eve)
self.call(method, path, 401, body)
for payload in [{}, {'resource': 'messages', 'owner_id': chat['id'],
'id': None, 'created_at': 'bad'},
{'resource': 'messages', 'owner_id': chat['id'],
'id': messages[0]['id'], 'created_at': 'bad'}]:
cursor = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode()
self.call('GET', path + '?' + urlencode({'cursor': cursor}), 400, actor=alice)
def test_concurrent_messages(self):
actor = self.user()
chat = self.chat(actor)
path = '/api/v1/chats/' + chat['id'] + '/messages'
def send(number):
return self.call('POST', path, 201, {'text': str(number)}, actor)['id']
with ThreadPoolExecutor(max_workers=10) as pool:
sent = list(pool.map(send, range(100)))
page = self.call('GET', path + '?limit=100', actor=actor)
self.assertEqual(len(page['items']), 100)
self.assertEqual(len(set(sent)), 100)
self.assertEqual({item['id'] for item in page['items']}, set(sent))
self.assertIsNone(page['next_cursor'])
def test_same_timestamp_order(self):
from src.store import InMemoryStore
store = InMemoryStore()
actor = store.create_user('alice', 'Alice')['id']
chat = store.create_chat(actor, 'Chat', [actor])['id']
with patch('src.store.utc_now', return_value='2026-09-01T12:00:00.000000Z'):
sent = [store.create_message(chat, actor, str(i)) for i in range(5)]
received, cursor = [], None
while True:
page = store.list_messages(chat, actor, 2, cursor)
received.extend(page['items'])
cursor = page['next_cursor']
if cursor is None:
break
self.assertEqual(received, sorted(sent, key=lambda item: item['id']))
def test_restart_clears_data(self):
actor = self.user()
chat = self.chat(actor)
path = '/api/v1/chats/' + chat['id'] + '/messages'
message = self.call('POST', path, 201, {'text': 'Before restart'}, actor)
self.assertEqual(self.call('GET', path, actor=actor)['items'], [message])
self.stop_server()
self.setUpClass()
self.call('GET', '/api/v1/users/me', 401, actor=actor)
if __name__ == '__main__':
unittest.main()