Files
mtusi2026lab2/student-tests/test_lab2.py
T
celis cac37bddec
Skeleton contracts / contracts (pull_request) Canceled after 0s
ЛР 2 — БПИ2303 — Морару — на 5 (трек 2)
TypeScript/Node API на PostgreSQL с сессиями в Valkey (AOF), миграции,
compose-стенд, restart hook, тесты уровня 4 и эксперимент трека 2
(планы запроса на 240k сообщений, стоимость записи, backup/restore).
2026-10-29 20:58:56 +03:00

162 lines
7.8 KiB
Python
Executable File

#!/usr/bin/env python3
"""Level-4 checks of my solution: races, rollback, pagination, expiry, logout, wrong password, dependency loss.
Uses the public tests/client.py helpers. Stops/starts compose services (volumes are kept):
python3 student-tests/test_lab2.py --base-url http://127.0.0.1:8080
"""
import base64
import subprocess
import sys
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, check, run # noqa: E402
def compose(*args):
subprocess.run(['docker', 'compose', *args], cwd=ROOT, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def psql(query):
out = subprocess.run(['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger',
'-tAc', query], cwd=ROOT, check=True, capture_output=True, text=True)
return out.stdout.strip()
def basic(username, password):
return {'Authorization': 'Basic ' + base64.b64encode((username + ':' + password).encode()).decode()}
def wait_ready(c, seconds=60):
deadline = time.monotonic() + seconds
while True:
try:
return c.call('GET', '/health/ready', schema='Health')
except Exception:
check(time.monotonic() < deadline, 'API did not become ready')
time.sleep(0.5)
def test_registration_race(c):
body = {'username': 'race_' + uuid.uuid4().hex[:12], 'display_name': 'Гонка', 'password': 'Race-password-123'}
with ThreadPoolExecutor(20) as pool:
codes = list(pool.map(lambda _: Client(c.base).call('POST', '/api/v1/users', [201, 409], body=body)['status'],
range(20)))
check(codes.count(201) == 1 and codes.count(409) == 19, 'race: expected one 201 and 19x409, got %r' % codes)
check(psql("SELECT count(*) FROM users WHERE username = '%s'" % body['username']) == '1', 'race: duplicate row')
return '20 parallel registrations of one username -> 1x201, 19x409, 1 row'
def test_chat_rollback(c):
alice = c.user('rb')
title = 'rollback-' + uuid.uuid4().hex
before = psql('SELECT count(*) FROM chats')
# caller passes validation; the unknown member fails the FK after the chat row was inserted
c.call('POST', '/api/v1/chats', 400, actor=alice, body={'title': title, 'member_ids': [alice['id'], str(uuid.uuid4())]})
check(psql("SELECT count(*) FROM chats WHERE title = '%s'" % title) == '0', 'rollback: orphan chat row left')
check(psql('SELECT count(*) FROM chat_members m LEFT JOIN chats c ON c.id = m.chat_id WHERE c.id IS NULL') == '0',
'rollback: orphan members')
check(psql('SELECT count(*) FROM chats') == before, 'rollback: chat count changed')
return 'chat with unknown member -> 400, no chat/member rows (transaction rolled back)'
def test_pagination_and_injection(c):
alice, bob = c.user('pa'), c.user('pb')
chat = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'Пагинация', 'member_ids': [alice['id'], bob['id']]}, schema='Chat')['json']
other = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'Другой', 'member_ids': [alice['id']]}, schema='Chat')['json']
sent = [c.message(alice if i % 2 else bob, chat, "msg %03d'); DROP TABLE messages;--" % i)['json'] for i in range(57)]
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=7'
got, cursor = [], None
while True:
page = c.call('GET', path + ('&cursor=' + quote(cursor, safe='') if cursor else ''), actor=bob, schema='MessagePage')['json']
got += page['items']
cursor = page['next_cursor']
if cursor is None:
break
# contract order is (created_at, id); two messages in one millisecond are ordered by id
check(got == sorted(sent, key=lambda m: (m['created_at'], uuid.UUID(m['id']).int)), 'pagination: lost/duplicated/reordered')
first = c.call('GET', path, actor=alice, schema='MessagePage')['json']
c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + quote(first['next_cursor'], safe=''), 400, actor=alice)
c.call('GET', path + '&cursor=garbage', 400, actor=alice)
check(psql("SELECT to_regclass('messages') IS NOT NULL") == 't', 'injection text affected schema')
return '57 messages over limit=7 pages: exact order, no dupes; foreign/garbage cursor -> 400; SQL text stored verbatim'
def test_wrong_password_and_logout(c):
alice = c.user('lo')
reg = alice['registration']
for creds in (basic(reg['username'], reg['password'] + 'x'), basic('nobody_' + uuid.uuid4().hex[:8], reg['password'])):
r = c.call('POST', '/api/v1/auth/sessions', 401, headers=creds)
check(r['headers']['WWW-Authenticate'] == 'Basic realm="messenger", charset="UTF-8"', 'wrong challenge')
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': alice['id']})
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
c.call('GET', '/api/v1/users/me', 401, actor=alice)
c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor=alice)
return 'wrong password / unknown user -> identical 401 Basic; logout -> 204, then 401 twice'
def test_expiry(c):
compose('--profile', 'ttl', 'up', '-d', '--wait', 'api_short_ttl')
try:
short = Client('http://127.0.0.1:8081')
wait_ready(short)
alice = short.user('ttl')
short.call('GET', '/api/v1/users/me', actor=alice, schema='User')
time.sleep(3)
r = short.call('GET', '/api/v1/users/me', 401, actor=alice)
check(r['headers']['WWW-Authenticate'] == 'Bearer realm="messenger"', 'wrong challenge')
# the same Valkey is shared, so the main API must reject it too
c.call('GET', '/api/v1/users/me', 401, actor=alice)
finally:
compose('--profile', 'ttl', 'stop', 'api_short_ttl')
return 'SESSION_TTL_SECONDS=2: 200 right after login, 401 after 3 s on both API processes'
def outage(c, service, survives):
alice = c.user('out' + service[:2])
compose('stop', service)
try:
for path in ('/health/ready', '/api/v1/users/me'):
started = time.monotonic()
r = c.call('GET', path, 503, actor=alice)
elapsed = time.monotonic() - started
check(r['json']['error']['code'] == 'unavailable' and elapsed < 5, service + ': not a bounded 503')
# an anonymous request is still 401, never served as trusted
c.call('GET', '/api/v1/users/me', 401)
survivor = c.call('POST', '/api/v1/users', [201, 503], body={'username': 'o_' + uuid.uuid4().hex[:12],
'display_name': 'x', 'password': 'Outage-password-1'})
check(survivor['status'] == (201 if survives else 503), service + ': unexpected registration result')
finally:
compose('start', service)
wait_ready(c)
c.call('GET', '/api/v1/users/me', actor=alice, schema='User') # same token after recovery
return '%s stopped -> ready/me 503 unavailable in %.2fs, anonymous 401, registration %s; recovered with same token' % (
service, elapsed, '201' if survives else '503')
def test_valkey_outage(c):
return outage(c, 'valkey', survives=True)
def test_postgres_outage(c):
return outage(c, 'postgres', survives=False)
def main():
args = arguments('Student level-4 checks (stops/starts compose services)')
c = Client(args.base_url or 'http://127.0.0.1:8080')
wait_ready(c)
tests = [test_registration_race, test_chat_rollback, test_pagination_and_injection, test_wrong_password_and_logout,
test_expiry, test_valkey_outage, test_postgres_outage]
for test in tests:
print('PASS', test.__name__, '-', test(c), flush=True)
if __name__ == '__main__':
run(main)