lab2 done
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Khakimov Dmitrij
2026-10-06 22:38:28 +03:00
parent 47a3cd582d
commit 300ef7714e
74 changed files with 2785 additions and 112 deletions
+31
View File
@@ -0,0 +1,31 @@
# Собственные проверки lab2
Публичные `tests/*.py` оставлены без изменений.
- `make test-own`: Go race tests HTTP/use case и KDF; интеграционный тест пропускается
без INTEGRATION_TESTS=1.
- `make test-integration PORT=8080`: контейнер Go с race detector. Тест PostgreSQL
создаёт отдельную случайную схему и удаляет только её при завершении. Проверяет
goose up с нуля и повторно, переход со старого журнала с сохранением данных,
down/up в изолированной схеме, 12 конкурентных регистраций, rollback после вставки первого
участника, обход 10 000 сообщений с совпадающими timestamps; печатает EXPLAIN
(ANALYZE, BUFFERS) для страницы около 9000-го сообщения.
- `make test-grade4 PORT=8080`: HTTP-сценарий на работающем Compose-стенде. Создаёт
синтетические данные, проверяет неверный пароль, Bearer-only, logout, Unicode,
гонку 8 регистраций, реальные остановки Redis/PostgreSQL, восстановление сессии,
cursor после рестарта и expiry с SESSION_TTL_SECONDS=2. В finally восстанавливает
зависимости и обычный TTL=3600. Не запускайте параллельно smoke или нагрузке.
- `make test-persistence PORT=8080 ACTION_SCRIPT=scripts/restart.sh`: публичная
проверка полного рестарта с сохранением данных и прежнего токена.
Все Compose-команды относятся к проекту mtusi2026lab2. Токены и пароли живут только
в памяти теста, в результаты не выводятся. EXPLAIN использует синтетическую схему;
его время — измерение одного небольшого набора, не универсальная оценка PostgreSQL.
`make measure-load PORT=8080` выполняет 3 секунды прогрева и 30 секунд нагрузки
с конкуренцией 4; сохраняет latency/RPS/error ratio в `evidence/load.json`,
Docker stats и размеры набора данных в `evidence/resources.json`.
Для запуска интеграционных Go-тестов вне контейнера нужен `goose` v3.27.1 в PATH.
Контейнер tests уже содержит эту версию. Каталог SQL задаётся GOOSE_MIGRATION_DIR;
тест передаёт отдельный search_path и выполняет down только в своей временной схеме.
+120
View File
@@ -0,0 +1,120 @@
#!/usr/bin/env python3
"""Additional lab2 acceptance checks. Never print credentials or session tokens."""
import base64
from concurrent.futures import ThreadPoolExecutor
import os
from pathlib import Path
import subprocess
import sys
import time
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from client import Client, Failure, check, run
ROOT = Path(__file__).resolve().parents[2]
def compose(*args, ttl=None):
env = dict(os.environ)
if ttl is not None:
env['SESSION_TTL_SECONDS'] = str(ttl)
result = subprocess.run([str(ROOT / 'scripts/compose.sh'), *args], env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=180)
check(result.returncode == 0, 'compose operation failed: ' + args[0])
def login(c, username, password, expected=201):
basic = base64.b64encode((username + ':' + password).encode()).decode()
return c.call('POST', '/api/v1/auth/sessions', expected,
headers={'Authorization': 'Basic ' + basic}, schema='Session' if expected == 201 else None)
def main():
c = Client(timeout=5)
alice, bob, eve, chat = c.bootstrap()
credentials = alice['registration']
login(c, credentials['username'], 'incorrect-password', 401)
login(c, 'unknown_' + uuid.uuid4().hex[:12], 'incorrect-password', 401)
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': alice['id']})
basic = base64.b64encode((credentials['username'] + ':' + credentials['password']).encode()).decode()
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'Basic ' + basic})
response = c.call('GET', '/api/v1/users/me', actor=alice, headers={'X-User-Id': bob['id']}, schema='User')
check(response['json']['id'] == alice['id'], 'X-User-Id changed session owner')
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)
print('PASS: wrong password, unknown user, Bearer-only access, X-User-Id ignored, logout')
# Maximum UTF-8 password length and a colon are supported without truncation.
username = 'unicode_' + uuid.uuid4().hex[:12]
password = '🔑' * 127 + ':'
c.call('POST', '/api/v1/users', 201, body={'username': username, 'display_name': 'Unicode', 'password': password}, schema='User')
login(c, username, password)
login(c, username, '🔑' * 127 + 'x', 401)
print('PASS: 128-code-point Unicode password including colon; suffix verified')
username = 'race_' + uuid.uuid4().hex[:12]
def register(_):
return Client().call('POST', '/api/v1/users', [201, 409], body={
'username': username, 'display_name': 'Concurrent', 'password': 'synthetic-password-123'
})['status']
with ThreadPoolExecutor(max_workers=8) as pool:
statuses = list(pool.map(register, range(8)))
check(statuses.count(201) == 1 and statuses.count(409) == 7, 'registration race broken')
print('PASS: HTTP registration race: one 201, seven 409')
# Revoke before restart: absence must also survive AOF recovery.
for service in ('redis', 'postgres'):
compose('stop', service)
try:
c.call('GET', '/health/live', schema='Health')
start = time.monotonic()
c.call('GET', '/health/ready', 503)
check(time.monotonic() - start < 4, 'readiness error exceeded timeout budget')
c.call('GET', '/api/v1/users/me', 503, actor=bob)
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': bob['id']})
login(c, bob['registration']['username'], bob['registration']['password'], 503)
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 503, actor=bob, body={'text': 'must fail'})
finally:
compose('up', '-d', '--wait', service)
c.call('GET', '/health/ready', schema='Health')
c.call('GET', '/api/v1/users/me', actor=bob, schema='User')
c.call('GET', '/api/v1/users/me', 401, actor=alice)
print('PASS: ' + service + ' outage bounded; live=200, ready=503, protected=503, anonymous=401; session recovered, logout retained')
# The same signed cursor remains valid across an API process restart.
c.message(bob, chat, 'cursor before restart 1')
c.message(bob, chat, 'cursor before restart 2')
page = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=1', actor=bob, schema='MessagePage')['json']
check(page['next_cursor'] is not None, 'missing cursor')
compose('restart', 'api')
deadline = time.monotonic() + 30
while True:
try:
c.call('GET', '/health/ready', schema='Health')
break
except Failure:
check(time.monotonic() < deadline, 'API did not recover')
time.sleep(.2)
from urllib.parse import quote
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?cursor=' + quote(page['next_cursor']), actor=bob, schema='MessagePage')
print('PASS: cursor and existing session survive API restart')
try:
compose('up', '-d', '--wait', '--force-recreate', 'api', ttl=2)
short = c.user('expiry')
c.call('GET', '/api/v1/users/me', actor=short, schema='User')
time.sleep(2.2)
c.call('GET', '/api/v1/users/me', 401, actor=short)
compose('restart', 'redis')
compose('up', '-d', '--wait', 'redis')
c.call('GET', '/api/v1/users/me', 401, actor=short)
print('PASS: SESSION_TTL_SECONDS=2 expires; Redis restart does not revive expired session')
finally:
compose('up', '-d', '--wait', '--force-recreate', 'api', ttl=3600)
print('PASS: all grade-4 HTTP checks; normal TTL restored to 3600')
if __name__ == '__main__':
run(main)