test(student-tests): lab2 consolidate negative, concurrency, auth and resilience checks in one commit
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
|
||||
from client import Client, check, run # noqa: E402
|
||||
|
||||
REPO_ROOT = ROOT
|
||||
|
||||
|
||||
def compose(*args, timeout=90):
|
||||
return subprocess.run(
|
||||
['docker', 'compose', '--env-file', '.env', *args],
|
||||
cwd=REPO_ROOT, capture_output=True, text=True, timeout=timeout,
|
||||
)
|
||||
|
||||
|
||||
def make_user(c):
|
||||
username = 'rs_' + uuid.uuid4().hex[:10]
|
||||
password = 'T3st-' + uuid.uuid4().hex
|
||||
c.call('POST', '/api/v1/users', 201, body={
|
||||
'username': username, 'display_name': 'Res', 'password': password})
|
||||
import base64
|
||||
cred = base64.b64encode(f'{username}:{password}'.encode()).decode()
|
||||
s = c.call('POST', '/api/v1/auth/sessions', 201,
|
||||
headers={'Authorization': 'Basic ' + cred}, schema='Session')['json']
|
||||
return {'id': s['user']['id'], 'token': s['token']}
|
||||
|
||||
|
||||
def wait_ready(c, seconds=90):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
return
|
||||
except Exception:
|
||||
time.sleep(1)
|
||||
raise RuntimeError('health/ready не восстановился за %d секунд' % seconds)
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument('--service', choices=['redis', 'postgres'], required=True)
|
||||
p.add_argument('--base-url', default=None)
|
||||
args = p.parse_args()
|
||||
|
||||
c = Client(args.base_url)
|
||||
alice = make_user(c)
|
||||
c.call('GET', '/api/v1/users/me', actor=alice, schema='User')
|
||||
|
||||
print(f'[{args.service}] останавливаем сервис')
|
||||
r = compose('stop', args.service)
|
||||
check(r.returncode == 0, f'docker compose stop: {r.stderr.strip()}')
|
||||
|
||||
try:
|
||||
time.sleep(2)
|
||||
|
||||
# Защищённый endpoint должен вернуть 503 unavailable.
|
||||
resp = c.call('GET', '/api/v1/users/me', 503, actor=alice)
|
||||
code = resp['json']['error']['code']
|
||||
check(code == 'unavailable',
|
||||
f'ожидался код unavailable, получено {code!r}')
|
||||
|
||||
# Сообщение не должно раскрывать детали про Redis/Postgres/сеть.
|
||||
msg = resp['json']['error']['message'].lower()
|
||||
for bad in ('redis', 'postgres', 'sql', 'connection', 'refused', 'dial'):
|
||||
check(bad not in msg, f'сообщение раскрывает "{bad}": {msg}')
|
||||
|
||||
# Здоровье тоже должно репортить 503.
|
||||
c.call('GET', '/health/ready', 503)
|
||||
finally:
|
||||
print(f'[{args.service}] запускаем сервис обратно')
|
||||
r = compose('start', args.service)
|
||||
check(r.returncode == 0, f'docker compose start: {r.stderr.strip()}')
|
||||
wait_ready(c)
|
||||
|
||||
# Токен alice всё ещё валиден после возврата сервиса.
|
||||
c.call('GET', '/api/v1/users/me', actor=alice, schema='User')
|
||||
print(f'PASS: {args.service} недоступен → 503 unavailable без утечек; восстановление OK')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user