forked from mtusi2026/mtusi2026lab3
ЛР 3 — БВТ-2302 — Сабитов — на 3
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
"""Inherited contract checks (stdlib only). Needs running LB + API + PostgreSQL.
|
||||
|
||||
Run: python tests/contract_edge_tests.py --base-url http://localhost:8080
|
||||
Prints only status summary; credentials/tokens remain in process memory.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, base):
|
||||
self.base = base.rstrip('/')
|
||||
self.count = 0
|
||||
|
||||
def call(self, method, path, expected, payload=None, auth=None, raw=None, content_type=None):
|
||||
headers = {'Accept': 'application/json'}
|
||||
if method == 'POST' and path.endswith('/messages'):
|
||||
headers['Idempotency-Key'] = uuid.uuid4().hex
|
||||
if auth:
|
||||
headers['Authorization'] = auth
|
||||
if payload is not None:
|
||||
raw = json.dumps(payload, ensure_ascii=True).encode('utf-8')
|
||||
content_type = 'application/json'
|
||||
if content_type:
|
||||
headers['Content-Type'] = content_type
|
||||
req = urllib.request.Request(self.base + path, data=raw, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=15) as response:
|
||||
code = response.status
|
||||
body = response.read()
|
||||
reply_headers = response.headers
|
||||
except urllib.error.HTTPError as error:
|
||||
code = error.code
|
||||
body = error.read()
|
||||
reply_headers = error.headers
|
||||
if code != expected:
|
||||
raise AssertionError(f'{method} {path}: expected {expected}, received {code}')
|
||||
if not reply_headers.get('X-Request-Id'):
|
||||
raise AssertionError(f'{method} {path}: missing X-Request-Id')
|
||||
if not reply_headers.get('X-Instance-Id'):
|
||||
raise AssertionError(f'{method} {path}: missing X-Instance-Id')
|
||||
self.count += 1
|
||||
return json.loads(body) if body else None
|
||||
|
||||
|
||||
def run(base):
|
||||
c = Client(base)
|
||||
prefix = uuid.uuid4().hex[:14]
|
||||
name = 'ct_' + prefix
|
||||
password = 'ContractTest-' + uuid.uuid4().hex[:16]
|
||||
user_path = '/api/v1/users'
|
||||
actor_path = '/api/v1/auth/sessions'
|
||||
registration = {'username': name, 'display_name': 'Тест Unicode', 'password': password}
|
||||
|
||||
# Public registration must reject unknown fields and malformed Unicode.
|
||||
c.call('POST', user_path, 400, payload={**registration, 'unknown': 'field'})
|
||||
c.call('POST', user_path, 400, payload={**registration, 'display_name': '\ud800'})
|
||||
c.call('POST', user_path, 415, raw=b'{}', content_type='text/plain')
|
||||
user = c.call('POST', user_path, 201, payload=registration)
|
||||
if user['username'] != name:
|
||||
raise AssertionError('registration username mismatch')
|
||||
|
||||
basic = 'Basic ' + base64.b64encode((name + ':' + password).encode('utf-8')).decode('ascii')
|
||||
# Login is Basic-only, without a JSON request body.
|
||||
c.call('POST', actor_path, 400, auth=basic, payload={'unknown': 'field'})
|
||||
session = c.call('POST', actor_path, 201, auth=basic)
|
||||
bearer = 'Bearer ' + session['token']
|
||||
|
||||
# Protected POST endpoints must authenticate before parsing malformed JSON.
|
||||
c.call('POST', '/api/v1/chats', 401, raw=b'{invalid', content_type='application/json')
|
||||
c.call('POST', '/api/v1/chats', 400, auth=bearer, raw=b'{invalid', content_type='application/json')
|
||||
c.call('POST', '/api/v1/chats', 415, auth=bearer, raw=b'{}', content_type='text/plain')
|
||||
|
||||
c.call('GET', '/api/v1/chats/' + uuid.uuid4().hex, 400, auth=bearer)
|
||||
c.call('POST', '/api/v1/chats', 400, auth=bearer,
|
||||
payload={'title': 'duplicate', 'member_ids': [user['id'], user['id']]})
|
||||
c.call('POST', '/api/v1/chats', 400, auth=bearer,
|
||||
payload={'title': 'missing author', 'member_ids': [str(uuid.uuid4())]})
|
||||
chat1 = c.call('POST', '/api/v1/chats', 201, auth=bearer,
|
||||
payload={'title': 'Page A', 'member_ids': [user['id']]})
|
||||
chat2 = c.call('POST', '/api/v1/chats', 201, auth=bearer,
|
||||
payload={'title': 'Page B', 'member_ids': [user['id']]})
|
||||
msg_path1 = '/api/v1/chats/' + chat1['id'] + '/messages'
|
||||
msg_path2 = '/api/v1/chats/' + chat2['id'] + '/messages'
|
||||
c.call('POST', msg_path1, 401, raw=b'{invalid', content_type='application/json')
|
||||
c.call('POST', msg_path1, 400, auth=bearer, raw=b'{invalid', content_type='application/json')
|
||||
for i in range(2):
|
||||
c.call('POST', msg_path1, 201, auth=bearer, payload={'text': f'Page test {i}'})
|
||||
page = c.call('GET', msg_path1 + '?limit=1', 200, auth=bearer)
|
||||
cursor = page.get('next_cursor')
|
||||
if not cursor or len(page['items']) != 1:
|
||||
raise AssertionError('expected next_cursor for two messages')
|
||||
c.call('GET', msg_path2 + '?limit=1&cursor=' + urllib.parse.quote(cursor, safe=''), 400, auth=bearer)
|
||||
c.call('GET', msg_path1 + '?limit=1&limit=2', 400, auth=bearer)
|
||||
c.call('GET', msg_path1 + '?limit=1&cursor=@invalid@', 400, auth=bearer)
|
||||
print(f'PASS: {c.count} Lab 2 contract edge-case HTTP checks')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
args = parser.parse_args()
|
||||
run(args.base_url)
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Operator scenario: stop each real replica and verify writes, reads and replay via LB."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
from client import Client, Failure, arguments, check, run
|
||||
from resilience import history
|
||||
|
||||
|
||||
def configure(p):
|
||||
p.add_argument('--action-script', required=True)
|
||||
p.add_argument('--restore-script', required=True)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Stop either API replica with the other running', configure)
|
||||
c = Client(args.base_url, args.ca_file, timeout=2)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
for target in ('api1', 'api2'):
|
||||
seen = {c.call('GET', '/api/v1/users/me', actor=alice)['headers']['X-Instance-Id'] for _ in range(20)}
|
||||
check(seen == {'api1', 'api2'}, 'both replicas required before stop')
|
||||
key = uuid.uuid4().hex
|
||||
original = c.message(alice, chat, 'Сохранить ' + key, key=key)['json']
|
||||
env = dict(os.environ, TARGET_INSTANCE_ID=target)
|
||||
action = Path(args.action_script).resolve()
|
||||
start = time.monotonic()
|
||||
proc = subprocess.Popen([str(action)], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
errors, confirmed, instances = 0, [], []
|
||||
recovery = None
|
||||
pending_key = uuid.uuid4().hex
|
||||
try:
|
||||
while time.monotonic() - start < 6:
|
||||
check(proc.poll() in (None, 0), 'stop hook failed')
|
||||
try:
|
||||
# Same session, same message/key even after losing its original replica.
|
||||
repeated = c.message(alice, chat, original['text'], key=key)
|
||||
reply = c.message(alice, chat, 'После отказа ' + pending_key, key=pending_key)
|
||||
confirmed.append(reply['json'])
|
||||
pending_key = uuid.uuid4().hex
|
||||
page = history(c, bob, chat)
|
||||
except Failure:
|
||||
errors += 1
|
||||
else:
|
||||
check(repeated['json'] == original, 'failover changed replayed Message')
|
||||
check(original in page and all(m in page for m in confirmed), 'confirmed data lost')
|
||||
if proc.poll() == 0:
|
||||
instances.append(reply['headers']['X-Instance-Id'])
|
||||
if recovery is None:
|
||||
recovery = time.monotonic() - start
|
||||
time.sleep(0.1)
|
||||
check(proc.wait(timeout=3) == 0, 'stop hook failed')
|
||||
check(recovery is not None and recovery <= 10, 'recovery exceeded ten seconds')
|
||||
check(len(instances) >= 5 and target not in instances[-5:], 'stopped replica still serves requests')
|
||||
page = history(c, bob, chat)
|
||||
check(original in page and all(m in page for m in confirmed), 'confirmed data lost')
|
||||
for text in {m['text'] for m in confirmed}:
|
||||
check(sum(m['text'] == text for m in page) == 1, 'retry duplicate')
|
||||
print(json.dumps({'stopped': target, 'observed_before': sorted(seen),
|
||||
'survivors': sorted(set(instances[-5:])), 'writes': len(confirmed),
|
||||
'errors': errors, 'recovery_seconds': round(recovery, 3)}))
|
||||
finally:
|
||||
if proc.poll() is None:
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
# Record actual stopped process and intact dependencies before restoring.
|
||||
subprocess.run([str(Path(args.restore_script).resolve())], check=True, timeout=60, env=env)
|
||||
print('PASS: stopping either replica preserved sessions, reads, writes and idempotency')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Black-box cross-replica idempotency tests. All HTTP goes through the LB."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
import uuid
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def configure(p):
|
||||
p.add_argument('--restart-script', help='Optional full-stack restart, preserving volumes')
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Shared idempotency and previous-lab behavior', configure)
|
||||
c = Client(args.base_url, args.ca_file, timeout=8)
|
||||
alice, bob, outsider, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
key = uuid.uuid4().hex
|
||||
barrier = threading.Barrier(16)
|
||||
|
||||
def send(i):
|
||||
local = Client(args.base_url, args.ca_file, timeout=8)
|
||||
barrier.wait(timeout=10)
|
||||
# Reordered keys, explicit [] and omission must be equivalent.
|
||||
body = {'attachment_ids': [], 'text': 'Одна параллельная запись'} if i % 2 else {'text': 'Одна параллельная запись'}
|
||||
return local.call('POST', path, 201, actor=alice, body=body,
|
||||
headers={'Idempotency-Key': key}, schema='Message')
|
||||
|
||||
with ThreadPoolExecutor(max_workers=16) as pool:
|
||||
replies = list(pool.map(send, range(16)))
|
||||
original = replies[0]['json']
|
||||
check(all(r['json'] == original for r in replies), 'concurrent replay changed the Message')
|
||||
instances = sorted({r['headers']['X-Instance-Id'] for r in replies})
|
||||
check(len(instances) >= 2, 'race did not reach two API processes')
|
||||
page = c.call('GET', path, actor=alice, schema='MessagePage')['json']
|
||||
check(page['items'] == [original], 'concurrent repeat inserted duplicate messages')
|
||||
print(json.dumps({'parallel_requests': 16, 'instances': instances, 'messages_created': 1}))
|
||||
|
||||
c.call('POST', path, 409, actor=alice, body={'text': 'Другой текст'}, headers={'Idempotency-Key': key})
|
||||
for invalid in ('', 'with space', 'a' * 129, 'with/slash', 'bad,key'):
|
||||
c.call('POST', path, 400, actor=alice, body={'text': 'bad key'}, headers={'Idempotency-Key': invalid})
|
||||
c.call('POST', path, 400, actor=alice, body={'text': 'missing'})
|
||||
c.call('POST', path, 404, actor=outsider, body={'text': original['text']}, headers={'Idempotency-Key': key})
|
||||
|
||||
# The same key belongs independently to another user or chat.
|
||||
other = c.message(bob, chat, 'Другой отправитель', key=key)['json']
|
||||
check(other['id'] != original['id'], 'key incorrectly shared between users')
|
||||
second_chat = c.call('POST', '/api/v1/chats', 201, actor=alice, schema='Chat',
|
||||
body={'title': 'Другой чат', 'member_ids': [alice['id'], bob['id']]})['json']
|
||||
separate = c.message(alice, second_chat, original['text'], key=key)['json']
|
||||
check(separate['id'] != original['id'], 'key incorrectly shared between chats')
|
||||
|
||||
# Send a complete POST and close the connection without reading its outcome.
|
||||
# Retry the exact key/body through the LB, regardless of which API committed.
|
||||
uncertain_key = uuid.uuid4().hex
|
||||
body = json.dumps({'text': 'Неизвестный клиенту результат'}, ensure_ascii=False).encode()
|
||||
url = urlsplit(args.base_url)
|
||||
check(url.scheme == 'http', 'local lost-response scenario expects http')
|
||||
raw = (f'POST {path} HTTP/1.1\r\nHost: {url.netloc}\r\n'
|
||||
f'Authorization: Bearer {alice["token"]}\r\nIdempotency-Key: {uncertain_key}\r\n'
|
||||
f'Content-Type: application/json\r\nContent-Length: {len(body)}\r\nConnection: close\r\n\r\n').encode() + body
|
||||
with socket.create_connection((url.hostname, url.port or 80), timeout=5) as conn:
|
||||
conn.sendall(raw)
|
||||
conn.shutdown(socket.SHUT_WR)
|
||||
replayed = c.message(alice, chat, 'Неизвестный клиенту результат', key=uncertain_key)['json']
|
||||
repeated = c.message(alice, chat, 'Неизвестный клиенту результат', key=uncertain_key)['json']
|
||||
check(replayed == repeated, 'uncertain write cannot be retried')
|
||||
messages = c.call('GET', path, actor=bob, schema='MessagePage')['json']['items']
|
||||
check(sum(m['text'] == replayed['text'] for m in messages) == 1, 'uncertain result created a duplicate')
|
||||
|
||||
if args.restart_script:
|
||||
script = Path(args.restart_script).resolve()
|
||||
subprocess.run([str(script)], check=True, timeout=90, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
try:
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
break
|
||||
except AssertionError:
|
||||
check(time.monotonic() < deadline, 'LB did not recover')
|
||||
time.sleep(0.25)
|
||||
recovered = [c.message(alice, chat, original['text'], key=key) for _ in range(12)]
|
||||
check(all(r['json'] == original for r in recovered), 'restart lost idempotency record')
|
||||
check(len({r['headers']['X-Instance-Id'] for r in recovered}) >= 2, 'both APIs did not recover')
|
||||
print('PASS: same session and exact Message replay after full-stack restart')
|
||||
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
|
||||
for _ in range(6):
|
||||
c.call('POST', path, 401, actor=alice, body={'text': original['text']}, headers={'Idempotency-Key': key})
|
||||
print('PASS: concurrent replay, normalized JSON, key scope, conflict, invalid key, access, uncertain response and logout')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Simple grade-3 negative scenarios; run with the API+Postgres already started."""
|
||||
import base64
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def configure(parser):
|
||||
parser.add_argument('--expiry', action='store_true', help='Run only with SESSION_TTL_SECONDS=2')
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Lab 2 student tests', configure)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
if args.expiry:
|
||||
user = c.user('expiry')
|
||||
c.call('GET', '/api/v1/users/me', actor=user, schema='User')
|
||||
deadline = time.monotonic() + 12
|
||||
while time.monotonic() < deadline:
|
||||
response = c.call('GET', '/api/v1/users/me', (200, 401), actor=user, schema='User')
|
||||
if response['status'] == 401:
|
||||
print('PASS: Bearer session expires without logout')
|
||||
return
|
||||
time.sleep(0.25)
|
||||
check(False, 'session did not expire; start API with SESSION_TTL_SECONDS=2')
|
||||
|
||||
alice, _, outsider, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id']
|
||||
login_path = '/api/v1/auth/sessions'
|
||||
json_header = {'Content-Type': 'application/json'}
|
||||
c.call('POST', '/api/v1/users', 409, body=alice['registration'])
|
||||
c.call('POST', '/api/v1/users', 400, raw=b'{invalid', headers=json_header)
|
||||
c.call('POST', '/api/v1/chats', 401, raw=b'{invalid', headers=json_header)
|
||||
c.call('POST', path + '/messages', 401, raw=b'{invalid', headers=json_header)
|
||||
c.call('GET', path, 404, actor=outsider)
|
||||
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': alice['id']})
|
||||
c.call('GET', path + '/messages?limit=0', 400, actor=alice)
|
||||
c.call('GET', '/api/v1/chats/' + chat['id'].replace('-', ''), 400, actor=alice)
|
||||
|
||||
username = 'unicode_' + uuid.uuid4().hex[:12]
|
||||
password = 'Пароль:abc-123456'
|
||||
bad = f'{{"username":"{username}","display_name":"\\ud800","password":"{password}"}}'.encode('utf-8')
|
||||
c.call('POST', '/api/v1/users', 400, raw=bad, headers=json_header)
|
||||
registered = c.call('POST', '/api/v1/users', 201, schema='User',
|
||||
body={'username': username, 'display_name': 'Проверка 👋', 'password': password})['json']
|
||||
credentials = base64.b64encode(f'{username}:{password}'.encode('utf-8')).decode('ascii')
|
||||
auth = {'Authorization': 'Basic ' + credentials}
|
||||
c.call('POST', login_path, 400, body={}, headers=auth)
|
||||
session = c.call('POST', login_path, 201, headers=auth, schema='Session')['json']
|
||||
check(session['user'] == registered, 'Unicode Basic login returned the wrong user')
|
||||
|
||||
c.message(alice, chat, 'Первая запись')
|
||||
c.message(alice, chat, 'Вторая запись')
|
||||
first = c.call('GET', path + '/messages?limit=1', actor=alice, schema='MessagePage')['json']
|
||||
check(bool(first['next_cursor']), 'missing second page')
|
||||
c.call('GET', path + '/messages?cursor=' + quote(first['next_cursor'] + '!', safe=''), 400, actor=alice)
|
||||
second = c.call('GET', path + '/messages?limit=1&cursor=' + quote(first['next_cursor'], safe=''),
|
||||
actor=alice, schema='MessagePage')['json']
|
||||
check(len(second['items']) == 1 and second['next_cursor'] is None, 'incorrect last page')
|
||||
check(first['items'][0]['id'] != second['items'][0]['id'], 'pagination repeated a message')
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=alice)
|
||||
print('PASS: validation, Unicode Basic login, access, pagination and logout')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user