Lab3 baseline: HAProxy, replicated stateless API, shared PostgreSQL/Valkey, idempotent messages
This commit is contained in:
@@ -0,0 +1,554 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Own black-box tests for lab3. They complement, and never weaken, tests/smoke.py.
|
||||
|
||||
The suite assumes a running stack (make up) and creates only synthetic data.
|
||||
It checks the contract expectations derived from contracts/openapi.json and
|
||||
contracts/README.md: exact JSON keys, strict input validation, Bearer-only
|
||||
business API, membership hiding as 404, keyset pagination, concurrent username
|
||||
registration and concurrent message writes.
|
||||
|
||||
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'}, 'Message')
|
||||
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': []})
|
||||
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'}, '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 main():
|
||||
args = arguments('Lab2 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_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: lab3 student black-box suite, %d checks' % CHECKS)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print('FAIL:', exc)
|
||||
raise SystemExit(1)
|
||||
Reference in New Issue
Block a user