forked from mtusi2026/mtusi2026lab2
Подтверждённые сообщения и действующие сессии переживают перезапуск, история читается по индексу, копия восстанавливается в новый том.
164 lines
6.3 KiB
Python
164 lines
6.3 KiB
Python
"""Logout is covered in test_api.py. This script checks expiry and a dead Redis or Postgres.
|
|
|
|
It stops containers and starts them again. Do not run it in parallel with smoke.
|
|
"""
|
|
import json
|
|
import subprocess
|
|
import time
|
|
import uuid
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
from api import basic, bearer, request
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
EVIDENCE = ROOT / 'evidence'
|
|
|
|
|
|
def docker(*args, check=True):
|
|
return subprocess.run(['docker', *args], cwd=ROOT, check=check, capture_output=True, text=True)
|
|
|
|
|
|
def wait_ready(base, timeout=60):
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
status, _, payload = request('GET', '/health/ready', base=base, timeout=3)
|
|
if status == 200 and payload == {'status': 'ok'}:
|
|
return True
|
|
except Exception:
|
|
pass
|
|
time.sleep(0.5)
|
|
return False
|
|
|
|
|
|
def account(base):
|
|
username = 'dep_' + uuid.uuid4().hex[:8]
|
|
password = 'dep-password-1'
|
|
status, _, user = request('POST', '/api/v1/users', base=base, body={
|
|
'username': username,
|
|
'display_name': 'Проверка',
|
|
'password': password,
|
|
})
|
|
if status != 201:
|
|
raise SystemExit('register failed: %s' % status)
|
|
status, _, session = request('POST', '/api/v1/auth/sessions', base=base, headers=basic(username, password))
|
|
if status != 201:
|
|
raise SystemExit('login failed: %s' % status)
|
|
return user, session['token'], session['expires_at']
|
|
|
|
|
|
def expect(name, method, path, code, base='http://127.0.0.1:8080', headers=None):
|
|
status, response_headers, payload = request(method, path, base=base, headers=headers, timeout=12)
|
|
if status != code:
|
|
raise SystemExit('%s: expected %s, got %s %s' % (name, code, status, payload))
|
|
return {
|
|
'name': name,
|
|
'status': status,
|
|
'code': None if payload is None else payload.get('error', {}).get('code'),
|
|
'www_authenticate': response_headers.get('WWW-Authenticate'),
|
|
}
|
|
|
|
|
|
def redis_and_postgres():
|
|
base = 'http://127.0.0.1:8080'
|
|
if not wait_ready(base):
|
|
raise SystemExit('API was not ready')
|
|
user, token, _ = account(base)
|
|
auth = bearer(token)
|
|
status, _, chat = request('POST', '/api/v1/chats', base=base, headers=auth, body={
|
|
'title': 'зависимость',
|
|
'member_ids': [user['id']],
|
|
})
|
|
if status != 201:
|
|
raise SystemExit('chat failed')
|
|
status, _, message = request(
|
|
'POST', '/api/v1/chats/%s/messages' % chat['id'],
|
|
base=base, headers=auth, body={'text': 'до отказа'},
|
|
)
|
|
if status != 201:
|
|
raise SystemExit('message failed')
|
|
rows = []
|
|
|
|
docker('stop', 'mtusi-lab2-redis')
|
|
try:
|
|
rows.append(expect('redis down, no token', 'GET', '/api/v1/users/me', 401))
|
|
rows.append(expect('redis down, bearer', 'GET', '/api/v1/users/me', 503, headers=auth))
|
|
rows.append(expect('redis down, live', 'GET', '/health/live', 200))
|
|
rows.append(expect('redis down, ready', 'GET', '/health/ready', 503))
|
|
finally:
|
|
docker('start', 'mtusi-lab2-redis')
|
|
if not wait_ready(base):
|
|
raise SystemExit('API did not recover after redis start')
|
|
rows.append(expect('redis back, same token', 'GET', '/api/v1/users/me', 200, headers=auth))
|
|
status, _, page = request('GET', '/api/v1/chats/%s/messages?limit=10' % chat['id'], headers=auth)
|
|
if status != 200 or page['items'] != [message]:
|
|
raise SystemExit('message lost across redis stop')
|
|
rows.append({'name': 'history after redis stop', 'status': 200, 'same_message': True})
|
|
|
|
docker('stop', 'mtusi-lab2-postgres')
|
|
try:
|
|
rows.append(expect('postgres down, no token', 'GET', '/api/v1/users/me', 401))
|
|
rows.append(expect('postgres down, bearer', 'GET', '/api/v1/users/me', 503, headers=auth))
|
|
rows.append(expect('postgres down, live', 'GET', '/health/live', 200))
|
|
rows.append(expect('postgres down, ready', 'GET', '/health/ready', 503))
|
|
finally:
|
|
docker('start', 'mtusi-lab2-postgres')
|
|
if not wait_ready(base, timeout=90):
|
|
raise SystemExit('API did not recover after postgres start')
|
|
rows.append(expect('postgres back, same token', 'GET', '/api/v1/users/me', 200, headers=auth))
|
|
status, _, page = request('GET', '/api/v1/chats/%s/messages?limit=10' % chat['id'], headers=auth)
|
|
if status != 200 or page['items'] != [message]:
|
|
raise SystemExit('message lost across postgres stop')
|
|
rows.append({'name': 'history after postgres stop', 'status': 200, 'same_message': True})
|
|
return rows
|
|
|
|
|
|
def short_ttl():
|
|
subprocess.run(
|
|
['docker', 'compose', '--env-file', '.env', '--profile', 'shortttl', 'up', '-d', 'api-short'],
|
|
cwd=ROOT, check=True,
|
|
)
|
|
base = 'http://127.0.0.1:8081'
|
|
try:
|
|
if not wait_ready(base, timeout=90):
|
|
raise SystemExit('short TTL API was not ready')
|
|
_, token, expires_at = account(base)
|
|
expires = datetime.fromisoformat(expires_at.replace('Z', '+00:00'))
|
|
delta = (expires - datetime.now(timezone.utc)).total_seconds()
|
|
if not 0 < delta < 10:
|
|
raise SystemExit('expected a short session, delta=%s' % delta)
|
|
status, _, _ = request('GET', '/api/v1/users/me', base=base, headers=bearer(token))
|
|
if status != 200:
|
|
raise SystemExit('fresh short session was rejected')
|
|
time.sleep(delta + 1.5)
|
|
status, headers, payload = request('GET', '/api/v1/users/me', base=base, headers=bearer(token), timeout=10)
|
|
if status != 401:
|
|
raise SystemExit('expired session returned %s' % status)
|
|
return {
|
|
'ttl_window_seconds': round(delta, 3),
|
|
'after_expiry': status,
|
|
'www_authenticate': headers.get('WWW-Authenticate'),
|
|
'error_code': payload['error']['code'],
|
|
}
|
|
finally:
|
|
docker('stop', 'mtusi-lab2-api-short', check=False)
|
|
|
|
|
|
def main():
|
|
report = {
|
|
'redis_and_postgres': redis_and_postgres(),
|
|
'short_ttl': short_ttl(),
|
|
}
|
|
EVIDENCE.mkdir(exist_ok=True)
|
|
(EVIDENCE / 'dependencies.json').write_text(
|
|
json.dumps(report, ensure_ascii=False, indent=2) + '\n',
|
|
encoding='utf-8',
|
|
)
|
|
print('PASS dependencies')
|
|
print(json.dumps(report, ensure_ascii=False, indent=2))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|