Add first lab code

This commit is contained in:
2026-10-09 14:57:52 +03:00
parent 65003b6119
commit d9fe67a8ce
24 changed files with 1040 additions and 9 deletions
+201
View File
@@ -0,0 +1,201 @@
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()
+45
View File
@@ -0,0 +1,45 @@
import asyncio
import json
import unittest
from unittest.mock import patch
from src.main import app
class ErrorTests(unittest.TestCase):
def test_unexpected_error_has_request_id(self):
async def request():
sent = []
received = False
async def receive():
nonlocal received
if not received:
received = True
return {'type': 'http.request', 'body': b'', 'more_body': False}
await asyncio.Event().wait()
async def send(message):
sent.append(message)
scope = {
'type': 'http', 'asgi': {'version': '3.0'}, 'http_version': '1.1',
'method': 'GET', 'scheme': 'http', 'path': '/api/v1/users/me',
'raw_path': b'/api/v1/users/me', 'query_string': b'',
'headers': [(b'x-user-id', b'test'), (b'x-request-id', b'failure-test')],
'server': ('localhost', 8080), 'client': ('localhost', 1234),
}
with patch('src.dependencies.store.require_user', side_effect=RuntimeError('private detail')):
try:
await app(scope, receive, send)
except RuntimeError:
pass
return sent
sent = asyncio.run(request())
start = next(item for item in sent if item['type'] == 'http.response.start')
body = b''.join(item.get('body', b'') for item in sent if item['type'] == 'http.response.body')
self.assertEqual(start['status'], 500)
self.assertEqual(dict(start['headers'])[b'x-request-id'], b'failure-test')
self.assertEqual(json.loads(body)['error']['request_id'], 'failure-test')
self.assertNotIn(b'private detail', body)
+106
View File
@@ -0,0 +1,106 @@
import asyncio
import json
import unittest
from concurrent.futures import ThreadPoolExecutor
from dataclasses import replace
from unittest.mock import patch
from src.errors import APIError
from src.limits import Limits, ResourceLimitMiddleware
from src.store import InMemoryStore
class StoreLimitTests(unittest.TestCase):
def make_store(self, **values):
store = InMemoryStore(replace(Limits(), **values))
actor = store.create_user('alice', 'Alice')['id']
chat = store.create_chat(actor, 'Chat', [actor])['id']
return store, actor, chat
def test_capacity_is_atomic_and_does_not_evict(self):
store, actor, chat = self.make_store(max_messages=20)
def send(i):
try:
return store.create_message(chat, actor, str(i))
except APIError as exc:
self.assertEqual(exc.status_code, 503)
return None
with ThreadPoolExecutor(max_workers=10) as pool:
accepted = [item for item in pool.map(send, range(100)) if item]
self.assertEqual(len(accepted), 20)
page = store.list_messages(chat, actor, 100, None)
self.assertEqual({item['id'] for item in page['items']}, {item['id'] for item in accepted})
def test_byte_limit_counts_utf8_and_other_objects_are_bounded(self):
store, actor, chat = self.make_store(max_text_bytes=4, max_users=1, max_chats=1)
saved = store.create_message(chat, actor, '🙂')
for operation in [lambda: store.create_message(chat, actor, 'a'),
lambda: store.create_user('bob', 'Bob'),
lambda: store.create_chat(actor, 'Other', [actor])]:
with self.assertRaises(APIError) as error:
operation()
self.assertEqual(error.exception.status_code, 503)
self.assertEqual(store.list_messages(chat, actor, 100, None)['items'], [saved])
def test_rate_recovers_without_losing_messages(self):
with patch('src.store.time.monotonic', return_value=0) as clock:
store, actor, chat = self.make_store(message_rate=2, message_burst=1)
first = store.create_message(chat, actor, 'one')
with self.assertRaises(APIError) as error:
store.create_message(chat, actor, 'rejected')
self.assertEqual(error.exception.status_code, 429)
clock.return_value = 0.5
second = store.create_message(chat, actor, 'two')
self.assertEqual(store.list_messages(chat, actor, 100, None)['items'],
sorted([first, second], key=lambda item: (item['created_at'], item['id'])))
class MiddlewareLimitTests(unittest.IsolatedAsyncioTestCase):
async def call(self, app, chunks, headers=()):
messages = iter(chunks)
output = []
async def receive():
return next(messages)
async def send(message):
output.append(message)
scope = {'type': 'http', 'path': '/api/v1/users', 'method': 'POST',
'headers': headers, 'state': {'request_id': 'limit-test'}}
await app(scope, receive, send)
return output
async def test_body_limit_with_and_without_content_length(self):
async def should_not_run(scope, receive, send):
self.fail('Oversized body reached the API')
app = ResourceLimitMiddleware(should_not_run, replace(Limits(), max_request_bytes=4))
for headers, chunks in [([(b'content-length', b'5')], []), ([], [
{'type': 'http.request', 'body': b'123', 'more_body': True},
{'type': 'http.request', 'body': b'45', 'more_body': False}])]:
result = await self.call(app, chunks, headers)
self.assertEqual(result[0]['status'], 413)
self.assertEqual(json.loads(result[1]['body'])['error']['request_id'], 'limit-test')
self.assertEqual(app.active, 0)
async def test_admission_recovers_after_inflight_request_finishes(self):
entered, release = asyncio.Event(), asyncio.Event()
async def slow_app(scope, receive, send):
entered.set()
await release.wait()
await send({'type': 'http.response.start', 'status': 200, 'headers': []})
app = ResourceLimitMiddleware(slow_app, replace(Limits(), max_inflight=1))
body = [{'type': 'http.request', 'body': b'', 'more_body': False}]
first = asyncio.create_task(self.call(app, body))
await entered.wait()
overloaded = await self.call(app, body)
self.assertEqual(overloaded[0]['status'], 503)
release.set()
await first
self.assertEqual((await self.call(app, body))[0]['status'], 200)
self.assertEqual(app.active, 0)
async def test_exception_releases_slot(self):
async def broken_app(scope, receive, send):
raise RuntimeError('test')
app = ResourceLimitMiddleware(broken_app)
with self.assertRaises(RuntimeError):
await self.call(app, [{'type': 'http.request', 'body': b''}])
self.assertEqual(app.active, 0)