Files
mtusi2026lab3/student-tests/integration.py

94 lines
5.2 KiB
Python

#!/usr/bin/env python3
"""Additional black-box checks; public tests/contracts remain untouched."""
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import base64
import json
import sys
import threading
import uuid
from urllib.parse import quote
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, check
def main():
c = Client()
alice, bob, eve, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id']
key = uuid.uuid4().hex
barrier = threading.Barrier(16)
def duplicate(index):
local = Client()
barrier.wait()
body = {'text': 'Конкурентный повтор 👋'}
if index % 2:
body = {'attachment_ids': [], **body}
return local.call('POST', path + '/messages', 201, actor=alice, body=body,
headers={'Idempotency-Key': key}, schema='Message')
with ThreadPoolExecutor(max_workers=16) as pool:
responses = list(pool.map(duplicate, range(16)))
instances = {r['headers']['X-Instance-Id'] for r in responses}
check(len(instances) >= 2, 'concurrent requests must reach >=2 actual replicas')
check(all(r['json'] == responses[0]['json'] for r in responses), 'concurrent replay differs')
page = c.call('GET', path + '/messages', actor=alice, schema='MessagePage')['json']
check(len(page['items']) == 1, 'concurrent key created duplicate rows')
c.call('POST', path + '/messages', 409, actor=alice, body={'text': 'different'},
headers={'Idempotency-Key': key})
# Scope includes both user and chat. Same key is independent in each.
c.message(bob, chat, 'same key, another user', key=key)
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'another', 'member_ids': [alice['id']]}, schema='Chat')['json']
c.message(alice, other, 'same key, another chat', key=key)
c.call('POST', path + '/messages', 404, actor=eve, body={'text': 'hidden'},
headers={'Idempotency-Key': key})
for bad in ({'text': 'ok', 'sender_id': eve['id']}, {'text': ' '}, {'text': 123},
{'text': 'x' * 4001}, {'text': 'ok', 'attachment_ids': None},
{'text': 'ok', 'attachment_ids': [str(uuid.uuid4())]}, {'text': '\x00'}):
c.call('POST', path + '/messages', 400, actor=alice, body=bad,
headers={'Idempotency-Key': uuid.uuid4().hex})
for bad_key in ('', 'white space', 'a' * 129, 'slash/key'):
c.call('POST', path + '/messages', 400, actor=alice, body={'text': 'ok'},
headers={'Idempotency-Key': bad_key})
for raw in (b'{', b'[]', b'{"text":"a","text":"b"}', b'{"text":NaN}', b'\xff'):
c.call('POST', path + '/messages', 400, actor=alice, raw=raw,
headers={'Idempotency-Key': uuid.uuid4().hex, 'Content-Type': 'application/json'})
c.call('POST', path + '/messages', 415, actor=alice, raw=b'x',
headers={'Idempotency-Key': key, 'Content-Type': 'text/plain'})
c.call('POST', path + '/messages', 413, actor=alice, raw=b' ' * 65537,
headers={'Idempotency-Key': key, 'Content-Type': 'application/json'})
c.call('GET', '/api/v1/chats/not-a-uuid', 401)
c.call('GET', '/api/v1/chats/not-a-uuid', 400, actor=alice)
for members in ([alice['id'], alice['id']], [bob['id']], [alice['id'], str(uuid.uuid4())], [], 'bad'):
c.call('POST', '/api/v1/chats', 400, actor=alice, body={'title': 'bad', 'member_ids': members})
for query in ('limit=true', 'limit=-1', 'limit=101', 'limit=1&limit=2', 'cursor=garbage'):
c.call('GET', path + '/messages?' + query, 400, actor=alice)
cursor = c.call('GET', path + '/messages?limit=1', actor=alice, schema='MessagePage')['json']['next_cursor']
c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + quote(cursor), 400, actor=alice)
c.call('GET', path + '/messages?cursor=' + quote(cursor + 'x'), 400, actor=alice)
# Unicode password at the maximum length; colons are part of the password.
username = 'u_' + uuid.uuid4().hex[:20]
password = '🔑:' * 64
user = c.call('POST', '/api/v1/users', 201,
body={'username': username, 'display_name': '👋' * 100, 'password': password}, schema='User')['json']
auth = base64.b64encode((username + ':' + password).encode()).decode()
session = c.call('POST', '/api/v1/auth/sessions', 201,
headers={'Authorization': 'Basic ' + auth}, schema='Session')['json']
unicode_actor = {'id': user['id'], 'token': session['token']}
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=unicode_actor)
c.call('GET', '/api/v1/users/me', 401, actor=unicode_actor)
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
c.call('POST', path + '/messages', 401, actor=alice, body={'text': 'Конкурентный повтор 👋'},
headers={'Idempotency-Key': key})
print(json.dumps({'result': 'PASS', 'concurrent_requests': 16,
'observed_instances': sorted(instances), 'messages_for_shared_key': 1,
'checks': 'scope, access, revocation, strict JSON, limits, signed cursors, Unicode KDF'},
ensure_ascii=False, indent=2))
if __name__ == '__main__':
main()