forked from mtusi2026/mtusi2026lab3
ЛР 3 — БВТ2303 — Брезгунова — на 5
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Additional contract/concurrency tests through LB; synthetic data only."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
sys.path.insert(0, str(ROOT / 'scripts'))
|
||||
from client import Client
|
||||
from actions import base_url, command, COMPOSE
|
||||
|
||||
|
||||
def main():
|
||||
c = Client(base_url())
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
key = uuid.uuid4().hex
|
||||
barrier = threading.Barrier(24)
|
||||
|
||||
def send(i):
|
||||
local = Client(base_url())
|
||||
barrier.wait()
|
||||
return local.message(alice, chat, 'Конкурентно 🌍', key=key)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=24) as pool:
|
||||
replies = list(pool.map(send, range(24)))
|
||||
instances = sorted({r['headers']['X-Instance-Id'] for r in replies})
|
||||
assert len(instances) >= 2
|
||||
assert all(r['json'] == replies[0]['json'] for r in replies)
|
||||
original = replies[0]['json']
|
||||
c.call('POST', path, 409, actor=alice, body={'text': 'другое'}, headers={'Idempotency-Key': key})
|
||||
for bad in ('', 'a b', 'x' * 129):
|
||||
c.call('POST', path, 400, actor=alice, body={'text': 'invalid'}, headers={'Idempotency-Key': bad})
|
||||
# Same key, independently scoped user and chat.
|
||||
second = c.message(bob, chat, 'Other sender', key=key)['json']
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'Other scope', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
||||
third = c.message(alice, other, 'Other chat', key=key)['json']
|
||||
assert len({original['id'], second['id'], third['id']}) == 3
|
||||
c.call('POST', path, 404, actor=eve, body={'text': 'Конкурентно 🌍'}, headers={'Idempotency-Key': key})
|
||||
# A concurrent different-body race must select ONE body and reject the other.
|
||||
race_key = uuid.uuid4().hex
|
||||
barrier = threading.Barrier(24)
|
||||
|
||||
def race(i):
|
||||
barrier.wait()
|
||||
return Client(base_url()).call('POST', path, [201, 409], actor=alice,
|
||||
body={'text': 'race-' + str(i % 2)}, headers={'Idempotency-Key': race_key}, schema='Message')
|
||||
|
||||
with ThreadPoolExecutor(max_workers=24) as pool:
|
||||
raced = list(pool.map(race, range(24)))
|
||||
assert sum(r['status'] == 201 for r in raced) == 12
|
||||
assert len({r['json']['id'] for r in raced if r['status'] == 201}) == 1
|
||||
history = c.call('GET', path, actor=bob, schema='MessagePage')['json']['items']
|
||||
assert sum(m['text'] == 'Конкурентно 🌍' for m in history) == 1
|
||||
# Only the expiry timestamp of this synthetic claim is changed.
|
||||
query = f"UPDATE message_keys SET expires_at=clock_timestamp()-interval '1 second' WHERE user_id='{alice['id']}' AND chat_id='{chat['id']}' AND key='{key}'"
|
||||
command(COMPOSE + ['exec', '-T', 'postgres', 'psql', '-X', '-v', 'ON_ERROR_STOP=1', '-U', 'messenger', '-d', 'messenger', '-c', query])
|
||||
expired = c.message(alice, chat, 'After expiry', key=key)['json']
|
||||
assert expired['id'] != original['id']
|
||||
assert c.message(alice, chat, 'After expiry', key=key)['json'] == expired
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
|
||||
c.call('POST', path, 401, actor=alice, body={'text': 'After expiry'}, headers={'Idempotency-Key': key})
|
||||
report = {'pass': True, 'parallel_requests': 24, 'observed_instances': instances,
|
||||
'identical_response_and_one_message': True, 'conflicting_body_race_201': 12,
|
||||
'conflicting_body_race_409': 12, 'key_validation': True,
|
||||
'scope_user_and_chat': True, 'authorization_rechecked': True,
|
||||
'expired_key_reusable_without_deleting_old_message': True}
|
||||
(ROOT / 'evidence' / 'integration.json').write_text(json.dumps(report, indent=2) + '\n')
|
||||
print(json.dumps(report, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user