Files
mtusi2026lab4/student-tests/blackbox.py

651 lines
33 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Own black-box tests for lab4. They complement, and never weaken, tests/smoke.py.
The suite assumes a running stack (make up) and creates only synthetic data.
It keeps the lab3 regression surface — exact JSON keys, strict input
validation, Bearer-only business API, membership hiding as 404, keyset
pagination, concurrent registration/messages/idempotency — and adds the lab4
attachment regression: message attachment_ids, attachment-only messages and
idempotency over the attachment payload. Deep upload limits and ACL negatives
live in student-tests/attachment-checks.py.
Python 3.9+, standard library only.
"""
import base64
import concurrent.futures
import datetime as dt
import json
import sys
import threading
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, check, timestamp # noqa: E402
CHECKS = 0
def ok(condition, message):
global CHECKS
CHECKS += 1
check(condition, message)
def expect_keys(payload, expected, where):
ok(set(payload) == set(expected), where + ': JSON keys differ: ' + repr(sorted(payload)))
def basic(username, password):
return 'Basic ' + base64.b64encode((username + ':' + password).encode('utf-8')).decode('ascii')
def register(c, username=None, display_name=None, password=None):
username = username or 'bb_' + uuid.uuid4().hex[:12]
password = password or 'B3st-' + uuid.uuid4().hex
display_name = display_name or 'Тестовый пользователь'
body = {'username': username, 'display_name': display_name, 'password': password}
user = c.call('POST', '/api/v1/users', 201, body=body, schema='User')['json']
expect_keys(user, {'id', 'username', 'display_name', 'created_at'}, 'User')
return {'id': user['id'], 'user': user, 'registration': body, 'password': password}
def login(c, actor):
response = c.call('POST', '/api/v1/auth/sessions', 201,
headers={'Authorization': basic(actor['registration']['username'], actor['password'])},
schema='Session')['json']
expect_keys(response, {'token', 'token_type', 'expires_at', 'user'}, 'Session')
actor['token'] = response['token']
actor['session'] = response
return actor
def new_chat(c, actor, title, member_ids):
return c.call('POST', '/api/v1/chats', 201, actor=actor,
body={'title': title, 'member_ids': member_ids}, schema='Chat')['json']
def key():
return uuid.uuid4().hex
def send_with_key(c, actor, chat, text, idem, headers=None):
merged = {'Idempotency-Key': idem}
merged.update(headers or {})
return c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor,
body={'text': text}, headers=merged, schema='Message')['json']
def send(c, actor, chat, text, headers=None):
return send_with_key(c, actor, chat, text, key(), headers)
def all_messages(c, actor, chat, limit=100):
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=' + str(limit)
items, seen = [], set()
for _ in range(1000):
page = c.call('GET', path, actor=actor, schema='MessagePage')['json']
items.extend(page['items'])
if page['next_cursor'] is None:
return items
ok(page['next_cursor'] not in seen, 'message cursor cycle')
seen.add(page['next_cursor'])
from urllib.parse import quote
path = ('/api/v1/chats/' + chat['id'] + '/messages?limit=' + str(limit) +
'&cursor=' + quote(page['next_cursor'], safe=''))
raise AssertionError('message pagination exceeded safety bound')
def sorted_messages(items):
return sorted(items, key=lambda x: (timestamp(x['created_at']), uuid.UUID(x['id']).int))
def test_health(c):
live = c.call('GET', '/health/live', schema='Health')
ok(live['json'] == {'status': 'ok'}, 'liveness body')
ok(bool(live['headers'].get('X-Request-Id')), 'liveness X-Request-Id')
ok(bool(live['headers'].get('X-Instance-Id')), 'liveness X-Instance-Id')
ready = c.call('GET', '/health/ready', schema='Health')
ok(ready['json'] == {'status': 'ok'}, 'readiness body')
print('PASS health')
def test_registration_and_login(c):
alice = register(c)
bob = register(c)
login(c, alice)
login(c, bob)
ok(len(alice['session']['token']) >= 32, 'session token shorter than contract minimum')
ok(alice['session']['token_type'] == 'Bearer', 'token_type')
ok(timestamp(alice['session']['expires_at']) > dt.datetime.now(dt.timezone.utc), 'expiry in the past')
ok(alice['session']['user'] == alice['user'], 'session user differs from created user')
# Duplicate username, including a different display name/password.
c.call('POST', '/api/v1/users', 409, body={
'username': alice['registration']['username'],
'display_name': 'Другой',
'password': 'Another-password-123',
})
# Wrong / unknown / malformed credentials all give the same Basic 401.
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': basic(alice['registration']['username'], 'wrong-password-123')})
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': basic('definitely_unknown', 'wrong-password-123')})
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic !!!!'})
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic ' + base64.b64encode(b'no-colon').decode()})
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Bearer abcdefghijklmnopqrstuvwxyz'})
# Basic is not accepted on business endpoints; X-User-Id grants nothing.
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': basic(alice['registration']['username'], alice['password'])})
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': alice['id']})
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'Bearer ' + 'a' * 43})
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'X-User-Id ' + alice['id']})
me = c.call('GET', '/api/v1/users/me', actor=alice, headers={'X-User-Id': bob['id']}, schema='User')['json']
ok(me['id'] == alice['id'], 'X-User-Id overrode the bearer identity')
# A UTF-8 password containing colons is valid and is not truncated at the
# first colon by Basic parsing.
unicode_password = 'pässwörd:with:12'
unicode_user = register(c, password=unicode_password)
login(c, unicode_user)
ok(unicode_user['session']['user']['username'] == unicode_user['registration']['username'], 'unicode password login')
# Session JSON must never contain the password or its hash.
serialized = json.dumps(alice['session'], ensure_ascii=False)
for forbidden in ('password', 'argon2', 'salt'):
ok(forbidden not in serialized, 'session leaks ' + forbidden)
print('PASS registration/auth')
def test_registration_validation(c):
username = 'bb_' + uuid.uuid4().hex[:10]
password = 'B3st-' + uuid.uuid4().hex
valid = {'username': username, 'display_name': 'Имя', 'password': password}
def bad(body, status=400, raw=None, headers=None):
c.call('POST', '/api/v1/users', status, body=body if raw is None else None, raw=raw,
headers=headers)
bad({'username': username, 'display_name': 'Имя'})
bad({'username': username, 'display_name': 'Имя', 'password': 'short'})
bad({'username': username, 'display_name': 'Имя', 'password': 'p' * 129})
bad({'username': username, 'display_name': 'Имя', 'password': ' ' * 12})
bad({'username': 'ab', 'display_name': 'Имя', 'password': password})
bad({'username': 'a' * 33, 'display_name': 'Имя', 'password': password})
bad({'username': 'UPPER', 'display_name': 'Имя', 'password': password})
bad({'username': 'bad-name', 'display_name': 'Имя', 'password': password})
bad({'username': 'бвт', 'display_name': 'Имя', 'password': password})
bad({'username': username, 'display_name': '', 'password': password})
bad({'username': username, 'display_name': ' ', 'password': password})
bad({'username': username, 'display_name': 'Имя', 'password': password, 'extra': 1})
bad({'username': username, 'display_name': 'Имя', 'password': password, 'Password': 'x'})
bad({'Username': username, 'display_name': 'Имя', 'password': password})
bad({'username': username, 'display_name': 'Имя', 'password': 123456789012})
bad({'username': None, 'display_name': 'Имя', 'password': password})
bad({}, raw=b'{', headers={'Content-Type': 'application/json'})
bad({}, raw=b'[]', headers={'Content-Type': 'application/json'})
bad({}, status=415, raw=json.dumps(valid).encode(), headers={'Content-Type': 'text/plain'})
bad({}, raw=(json.dumps(valid)[:-1] + ', "username": "x"}').encode(), headers={'Content-Type': 'application/json'})
# Exact code-point boundaries.
long_name = register(c, display_name='😀' * 100)
ok(long_name['user']['display_name'] == '😀' * 100, '100 code points display_name changed')
c.call('POST', '/api/v1/users', 400, body={
'username': 'bb_' + uuid.uuid4().hex[:10],
'display_name': '😀' * 101,
'password': password,
})
c.call('POST', '/api/v1/users', 400, body={
'username': 'a' * 32 + 'b',
'display_name': 'Имя', 'password': password,
})
register(c, username='a' * 24 + uuid.uuid4().hex[:8])
print('PASS registration validation')
def test_chats(c, alice, bob, eve):
chat = new_chat(c, alice, 'Комната с Unicode 🚀', [alice['id'], bob['id']])
ok(set(chat['member_ids']) == {alice['id'], bob['id']}, 'chat member set')
expect_keys(chat, {'id', 'title', 'member_ids', 'created_at'}, 'Chat')
def bad(body, status=400):
c.call('POST', '/api/v1/chats', status, actor=alice, body=body)
bad({'title': 'Без автора', 'member_ids': [bob['id']]})
bad({'title': 'Дубликат', 'member_ids': [alice['id'], alice['id']]})
bad({'title': 'Неизвестный', 'member_ids': [alice['id'], str(uuid.uuid4())]})
bad({'title': 'Не UUID', 'member_ids': [alice['id'], 'not-a-uuid']})
bad({'title': 'Слишком много', 'member_ids': [alice['id']] + [str(uuid.uuid4()) for _ in range(100)]})
bad({'title': '', 'member_ids': [alice['id']]})
bad({'title': ' ', 'member_ids': [alice['id']]})
bad({'title': 'я' * 101, 'member_ids': [alice['id']]})
bad({'title': 'Лишнее', 'member_ids': [alice['id']], 'extra': True})
bad({'title': 'Нет списка'})
own = c.call('GET', '/api/v1/chats/' + chat['id'], actor=bob, schema='Chat')['json']
ok(own['id'] == chat['id'], 'member cannot read chat')
c.call('GET', '/api/v1/chats/' + chat['id'], 404, actor=eve)
c.call('GET', '/api/v1/chats/' + str(uuid.uuid4()), 404, actor=alice)
c.call('GET', '/api/v1/chats/not-a-uuid', 400, actor=alice)
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=eve,
body={'text': 'чужое'}, headers={'Idempotency-Key': key()})
hidden = c.call('GET', '/api/v1/chats?limit=100', actor=eve, schema='ChatPage')['json']
ok(all(item['id'] != chat['id'] for item in hidden['items']), 'foreign chat leaked into list')
listed = c.call('GET', '/api/v1/chats?limit=100', actor=bob, schema='ChatPage')['json']
ok(any(item['id'] == chat['id'] for item in listed['items']), 'member chat missing from list')
print('PASS chats/membership')
def test_messages(c, alice, bob, eve, chat):
text = 'Привет 👋 e\u0301 中文'
message = send(c, alice, chat, text)
expect_keys(message, {'id', 'chat_id', 'sender_id', 'text', 'created_at', 'attachment_ids'}, 'Message')
ok(message['attachment_ids'] == [], 'attachment_ids must default to an empty array')
ok(message['text'] == text, 'message text changed')
ok(message['sender_id'] == alice['id'] and message['chat_id'] == chat['id'], 'message identity')
# X-User-Id cannot substitute for the Bearer owner.
spoofed = send(c, alice, chat, 'не от Боба', headers={'X-User-Id': bob['id']})
ok(spoofed['sender_id'] == alice['id'], 'X-User-Id changed the message sender')
def bad(actor, body, status=400, raw=None, headers=None):
merged = {'Idempotency-Key': key()}
merged.update(headers or {})
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', status, actor=actor,
body=body, raw=raw, headers=merged)
bad(alice, {'text': ''})
bad(alice, {'text': ' '})
bad(alice, {'text': None})
bad(alice, {})
bad(alice, {'text': 'x' * 4001})
bad(alice, {'text': 'ok', 'sender_id': alice['id']})
bad(alice, {'text': 'ok', 'attachment_ids': None})
bad(alice, {'text': 'ok', 'attachment_ids': 'not-an-array'})
bad(alice, {'text': 'ok', 'attachment_ids': ['not-a-uuid']})
bad(alice, {'text': 'ok', 'attachment_ids': [str(uuid.uuid4()), str(uuid.uuid4())] * 6})
bad(alice, {'Text': 'ok'})
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 400, actor=alice,
raw=b'{', headers={'Content-Type': 'application/json', 'Idempotency-Key': key()})
# Resource access is checked before body parsing: a foreign chat with a
# malformed body still looks like a missing chat.
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=eve,
raw=b'{', headers={'Content-Type': 'application/json', 'Idempotency-Key': key()})
boundary = send(c, alice, chat, 'я' * 4000)
ok(len(boundary['text']) == 4000, '4000 code point message changed')
history = all_messages(c, bob, chat)
ok(any(item == boundary for item in history), 'member cannot read message history')
print('PASS messages')
def test_pagination(c, alice, bob):
chat = new_chat(c, alice, 'Пагинация', [alice['id'], bob['id']])
for index in range(23):
send(c, alice if index % 2 == 0 else bob, chat, 'строка %02d' % index)
expected = sorted_messages(all_messages(c, alice, chat, limit=100))
collected = []
cursor = None
limits = [7, 5, 100, 1, 3, 9]
step = 0
while True:
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=' + str(limits[step % len(limits)])
if cursor:
from urllib.parse import quote
path += '&cursor=' + quote(cursor, safe='')
page = c.call('GET', path, actor=bob, schema='MessagePage')['json']
collected.extend(page['items'])
step += 1
if page['next_cursor'] is None:
break
cursor = page['next_cursor']
ok(step < 100, 'pagination did not finish')
ok(collected == expected, 'pagination lost, duplicated or reordered messages')
ids = [item['id'] for item in collected]
ok(len(ids) == len(set(ids)), 'pagination repeated an id')
first = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=3', actor=alice, schema='MessagePage')['json']
ok(first['next_cursor'] is not None, 'first page cursor missing')
other = new_chat(c, alice, 'Другой чат', [alice['id']])
c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + first['next_cursor'], 400, actor=alice)
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?cursor=not-base64!!', 400, actor=alice)
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=0', 400, actor=alice)
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=101', 400, actor=alice)
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=abc', 400, actor=alice)
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=1&limit=2', 400, actor=alice)
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?cursor=', 400, actor=alice)
# A message cursor is scoped to a chat and cannot continue the chat list.
c.call('GET', '/api/v1/chats?cursor=' + first['next_cursor'], 400, actor=alice)
listed = c.call('GET', '/api/v1/chats?limit=100', actor=alice, schema='ChatPage')['json']
ok(any(item['id'] == chat['id'] for item in listed['items']), 'paginated chat missing from list')
ok(any(item['id'] == other['id'] for item in listed['items']), 'other chat missing from list')
print('PASS pagination')
def test_concurrent_registration(c):
username = 'race_' + uuid.uuid4().hex[:10]
body = {'username': username, 'display_name': 'Гонка', 'password': 'Race-password-123'}
def attempt(_):
local = Client(c.base)
try:
return local.call('POST', '/api/v1/users', (201, 409), body=body)['status']
except Exception as exc: # failures are assertions for this test
return 'error:' + type(exc).__name__
barrier = threading.Barrier(8)
def synchronized_attempt(index):
barrier.wait()
return attempt(index)
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
statuses = list(pool.map(synchronized_attempt, range(8)))
ok(statuses.count(201) == 1, 'concurrent registration: expected exactly one 201, got ' + repr(statuses))
ok(statuses.count(409) == 7, 'concurrent registration: expected seven 409, got ' + repr(statuses))
c.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': basic(username, 'Race-password-123')}, schema='Session')
print('PASS concurrent registration')
def test_concurrent_messages(c, alice, bob):
chat = new_chat(c, alice, 'Конкурентная запись', [alice['id'], bob['id']])
def worker(index):
local = Client(c.base)
actor = alice if index % 2 == 0 else bob
return local.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor,
body={'text': 'concurrent %02d' % index},
headers={'Idempotency-Key': key()}, schema='Message')['json']
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool:
messages = list(pool.map(worker, range(24)))
ids = [message['id'] for message in messages]
ok(len(ids) == 24 and len(set(ids)) == 24, 'concurrent messages produced duplicate ids')
for index, message in enumerate(messages):
ok(message['sender_id'] == (alice['id'] if index % 2 == 0 else bob['id']), 'concurrent sender mismatch')
history = all_messages(c, alice, chat)
ok(len(history) == 24, 'concurrent history has %d rows, want 24' % len(history))
ok(sorted_messages(history) == history, 'concurrent history is not ordered by (created_at, id)')
ok([item['text'] for item in history].count('concurrent 00') == 1, 'concurrent duplicate text')
print('PASS concurrent messages')
def test_logout(c, alice):
second = login(c, {'id': alice['id'], 'user': alice['user'],
'registration': alice['registration'], 'password': alice['password']})
first_token = alice['token']
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
c.call('GET', '/api/v1/users/me', 401, actor={'token': first_token})
c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor={'token': first_token})
me = c.call('GET', '/api/v1/users/me', actor=second, schema='User')['json']
ok(me['id'] == alice['id'], 'logout revoked another session of the same user')
alice['token'] = second['token']
print('PASS logout')
def test_instances(c, alice):
"""One session served by at least two real processes through the LB."""
seen = set()
for _ in range(40):
response = c.call('GET', '/api/v1/users/me', actor=alice, schema='User')
instance = response['headers']['X-Instance-Id']
seen.add(instance)
ok(not response['headers'].get('Set-Cookie'), 'LB introduced a sticky cookie')
ok(len(seen) >= 2, 'only one X-Instance-Id observed; run the default >=2 replicas')
ok(all(instance for instance in seen), 'empty X-Instance-Id')
# The same token keeps working while the LB moves it between processes.
ready = c.call('GET', '/health/ready', schema='Health')
ok(ready['headers']['X-Instance-Id'] in seen, 'health and business endpoints disagree on replicas')
missing = c.call('GET', '/api/v1/chats/' + str(uuid.uuid4()), 404, actor=alice)
ok(bool(missing['headers']['X-Instance-Id']), 'error response missing X-Instance-Id')
ok(missing['json']['error']['request_id'] == missing['headers']['X-Request-Id'],
'error request_id differs from X-Request-Id')
print('PASS instances (%d observed) ' % len(seen))
def test_idempotency(c, alice, bob, eve, chat):
text = 'Идемпотентность ✅ e\u0301'
idem = key()
first = send_with_key(c, alice, chat, text, idem)
expect_keys(first, {'id', 'chat_id', 'sender_id', 'text', 'created_at', 'attachment_ids'}, 'Message')
replay = send_with_key(c, alice, chat, text, idem)
ok(replay == first, 'sequential replay returned a different Message')
# JSON whitespace and escapes are not part of the semantic body.
raw = json.dumps({'text': text}, ensure_ascii=True, indent=2).encode('utf-8')
escaped = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201,
actor=alice, raw=raw,
headers={'Content-Type': 'application/json', 'Idempotency-Key': idem},
schema='Message')['json']
ok(escaped == first, 'semantically equal JSON did not replay the message')
# A different body with the same key is a conflict and must not append.
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
body={'text': 'другой body'}, headers={'Idempotency-Key': idem})
# The original body is still the recorded result after a conflict.
ok(send_with_key(c, alice, chat, text, idem) == first, 'conflict replaced the stored result')
# Scope includes the user and the chat path, so the same key is independent.
other = new_chat(c, alice, 'Другой чат идемпотентности', [alice['id'], bob['id']])
other_message = send_with_key(c, alice, other, text, idem)
ok(other_message['id'] != first['id'] and other_message['chat_id'] == other['id'],
'same key leaked across chats')
bob_message = send_with_key(c, bob, chat, text, idem)
ok(bob_message['id'] != first['id'] and bob_message['sender_id'] == bob['id'],
'same key leaked across users')
# The outsider cannot replay or inspect alice's record: scope + access = 404.
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=eve,
body={'text': text}, headers={'Idempotency-Key': idem})
# Header validation is exact ASCII [A-Za-z0-9._:-]{1,128}.
def bad_key(value, status=400):
headers = {} if value is None else {'Idempotency-Key': value}
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', status, actor=alice,
body={'text': 'ключ'}, headers=headers)
bad_key(None)
bad_key('')
bad_key('bad key')
bad_key('ключ'.encode('utf-8').decode('latin-1')) # raw non-ASCII header bytes
bad_key('a' * 129)
accepted = 'A.-_:z9' + 'x' * 121
ok(len(accepted) == 128, 'test key length')
boundary = send_with_key(c, alice, chat, 'максимальный ключ', accepted)
ok(boundary['text'] == 'максимальный ключ', '128-character key rejected')
# Revoked/unknown session is checked before the idempotency record.
temp = login(c, register(c))
temp_chat = new_chat(c, temp, 'Сессия и ключ', [temp['id'], alice['id']])
temp_key = key()
keep = send_with_key(c, temp, temp_chat, 'до logout', temp_key)
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=temp)
c.call('POST', '/api/v1/chats/' + temp_chat['id'] + '/messages', 401,
actor={'token': temp['token']}, body={'text': 'до logout'},
headers={'Idempotency-Key': temp_key})
# A different user's valid session cannot inherit the record.
c.call('POST', '/api/v1/chats/' + temp_chat['id'] + '/messages', 404, actor=bob,
body={'text': 'до logout'}, headers={'Idempotency-Key': temp_key})
ok(keep['sender_id'] == temp['id'], 'temporary message identity')
print('PASS idempotency replay/conflict/scope/validation')
def test_idempotency_concurrency(c, alice, bob, chat):
"""Concurrent same-key POSTs through several replicas must be exactly-once."""
text = 'конкурентная идемпотентность ' + uuid.uuid4().hex
idem = key()
barrier = threading.Barrier(16)
def worker(index):
local = Client(c.base)
barrier.wait()
response = local.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201,
actor=alice, body={'text': text},
headers={'Idempotency-Key': idem}, schema='Message')
return response['json'], response['headers']['X-Instance-Id']
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as pool:
results = list(pool.map(worker, range(16)))
ids = {item['id'] for item, _ in results}
instances = {instance for _, instance in results}
ok(len(ids) == 1, 'concurrent replay returned %d distinct messages' % len(ids))
ok(len(instances) >= 2, 'concurrent replay did not cross replicas: ' + repr(instances))
history = [m for m in all_messages(c, bob, chat) if m['text'] == text]
ok(len(history) == 1, 'concurrent replay appended %d rows' % len(history))
# Different bodies racing for one key: one winner, one row, the rest 409.
mixed_key = key()
barrier = threading.Barrier(12)
def mixed(index):
local = Client(c.base)
payload = 'вариант A' if index % 2 == 0 else 'вариант B'
barrier.wait()
try:
response = local.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', (201, 409),
actor=bob, body={'text': payload},
headers={'Idempotency-Key': mixed_key}, schema='Message')
return response['status'], response['json']
except Exception as exc: # noqa: BLE001 - a status other than 201/409 is a failure below
return 'error:' + type(exc).__name__, None
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool:
outcomes = list(pool.map(mixed, range(12)))
statuses = [status for status, _ in outcomes]
ok(set(statuses) <= {201, 409}, 'mixed race produced unexpected results: ' + repr(statuses))
winners = [payload for status, payload in outcomes if status == 201]
ok(len({item['id'] for item in winners}) == 1, 'mixed race produced more than one message')
ok(any(status == 409 for status in statuses), 'mixed race did not produce a conflict')
stored = [m for m in all_messages(c, alice, chat)
if m['text'] in ('вариант A', 'вариант B') and m['id'] == winners[0]['id']]
ok(len(stored) == 1, 'mixed race stored a different or duplicate message')
print('PASS concurrent idempotency across %d replicas' % len(instances))
def upload(c, actor, chat, raw=None, filename='sample.png', content_type='image/png', status=201):
if raw is None:
raw = (ROOT / 'tests/fixtures/sample.png').read_bytes()
return c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + filename,
status, actor=actor, raw=raw, headers={'Content-Type': content_type},
schema='Attachment' if status == 201 else None)
def test_attachments(c, alice, bob, eve, chat):
att, content = c.attachment(alice, chat)
expect_keys(att, {'id', 'chat_id', 'owner_id', 'filename', 'content_type', 'size_bytes',
'sha256', 'status', 'variants', 'error_code', 'created_at', 'updated_at'}, 'Attachment')
ok(att['status'] == 'ready' and att['variants'] == [] and att['error_code'] is None,
'lab4 upload must return ready with no variants and no error')
# A message may be attachment-only: text="" is legal with at least one
# attachment of this chat, and the order of ids is preserved.
second, _ = c.attachment(alice, chat)
message = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': '', 'attachment_ids': [second['id'], att['id']]},
headers={'Idempotency-Key': key()}, schema='Message')['json']
ok(message['text'] == '' and message['attachment_ids'] == [second['id'], att['id']],
'attachment-only message lost text or order')
history = all_messages(c, bob, chat)
ok(any(item == message for item in history), 'member cannot read a message with attachments')
# Both endpoints enforce chat membership; a foreign id is indistinguishable
# from an absent one.
for suffix in ('', '/content'):
c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 404, actor=eve)
c.call('GET', '/api/v1/attachments/' + str(uuid.uuid4()) + suffix, 404, actor=alice)
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 200, actor=bob)
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=original', 200, actor=bob)
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=thumbnail', 404, actor=bob)
# An attachment from another chat cannot be linked, even by its owner.
eve_chat = new_chat(c, eve, 'Чужой чат', [eve['id']])
foreign, _ = c.attachment(eve, eve_chat)
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=alice,
body={'text': 'чужая картинка', 'attachment_ids': [foreign['id']]},
headers={'Idempotency-Key': key()})
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=alice,
body={'text': 'нет такой', 'attachment_ids': [str(uuid.uuid4())]},
headers={'Idempotency-Key': key()})
# The owner of the foreign attachment still cannot link it here.
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=eve,
body={'text': 'чужое', 'attachment_ids': [foreign['id']]},
headers={'Idempotency-Key': key()})
# And the same attachment works in its own chat.
own = c.call('POST', '/api/v1/chats/' + eve_chat['id'] + '/messages', 201, actor=eve,
body={'text': '', 'attachment_ids': [foreign['id']]},
headers={'Idempotency-Key': key()}, schema='Message')['json']
ok(own['attachment_ids'] == [foreign['id']], 'attachment cannot be used in its own chat')
# Attachment ids are unique, limited to ten and syntactically valid UUIDs.
for ids in ([att['id']] * 2,
[str(uuid.uuid4()) for _ in range(11)],
['not-a-uuid']):
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 400, actor=alice,
body={'text': 'x', 'attachment_ids': ids},
headers={'Idempotency-Key': key()})
# Idempotency covers the attachment payload: [] is the same as an absent
# field, while a different set of ids with the same key is a conflict.
plain_key = key()
plain = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': 'без вложений'}, headers={'Idempotency-Key': plain_key},
schema='Message')['json']
explicit = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': 'без вложений', 'attachment_ids': []},
headers={'Idempotency-Key': plain_key}, schema='Message')['json']
ok(explicit == plain, 'absent attachment_ids and [] are not semantically equal')
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
body={'text': 'без вложений', 'attachment_ids': [att['id']]},
headers={'Idempotency-Key': plain_key})
with_key = key()
first = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': '', 'attachment_ids': [att['id']]},
headers={'Idempotency-Key': with_key}, schema='Message')['json']
replay = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': '', 'attachment_ids': [att['id']]},
headers={'Idempotency-Key': with_key}, schema='Message')['json']
ok(replay == first, 'attachment message replay differs')
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
body={'text': '', 'attachment_ids': [second['id']]},
headers={'Idempotency-Key': with_key})
print('PASS attachments and message links')
def main():
args = arguments('Lab4 own black-box suite; creates synthetic data')
c = Client(args.base_url, args.ca_file)
test_health(c)
alice = register(c)
bob = register(c)
eve = register(c)
login(c, alice)
login(c, bob)
login(c, eve)
test_registration_and_login(c)
test_registration_validation(c)
test_chats(c, alice, bob, eve)
chat = new_chat(c, alice, 'Основной чат blackbox', [alice['id'], bob['id']])
test_messages(c, alice, bob, eve, chat)
test_attachments(c, alice, bob, eve, chat)
test_instances(c, alice)
test_idempotency(c, alice, bob, eve, chat)
test_idempotency_concurrency(c, alice, bob, chat)
test_pagination(c, alice, bob)
test_concurrent_registration(c)
test_concurrent_messages(c, alice, bob)
test_logout(c, alice)
print('PASS: lab4 student black-box suite, %d checks' % CHECKS)
if __name__ == '__main__':
try:
main()
except AssertionError as exc:
print('FAIL:', exc)
raise SystemExit(1)