Files
mtusi2026lab4/student-tests/failure_check.py
T

128 lines
7.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Usage (стенд уже запущен через docker compose up -d):
python student-tests/failure_check.py
Останавливает и замораживает Valkey и PostgreSQL (docker compose stop/pause, без удаления volumes),
проверяет поведение API и восстановление.
"""
import time
import uuid
from helpers import basic, call, compose, new_chat, new_user, wait_ready
failures = []
def timed(method, path, token=None, body=None, headers=None):
started = time.monotonic()
try:
status = call(method, path, body=body, token=token, headers=headers, timeout=10)[0]
except OSError as error:
status = type(error).__name__
return status, time.monotonic() - started
def expect(title, result, allowed, max_seconds):
status, seconds = result
ok = status in allowed and seconds <= max_seconds
print(' %-48s -> %-4s за %.2f с %s' % (title, status, seconds, 'OK' if ok else 'FAIL'))
if not ok:
failures.append(title)
def main():
alice = new_user('failure')
chat = new_chat(alice)
history = '/api/v1/chats/%s/messages' % chat['id']
assert call('POST', history, {'text': 'до отказа'}, alice['token'])[0] == 201
fake = uuid.uuid4().hex * 2
print('1. Valkey остановлен: кэш обходится, всё работает через PostgreSQL')
compose('stop', 'valkey')
try:
expect('первый запрос: обнаружение отказа кэша', timed('GET', '/api/v1/users/me', alice['token']), [200], 1.5)
expect('GET /users/me действующим токеном', timed('GET', '/api/v1/users/me', alice['token']), [200], 1)
expect('POST сообщение', timed('POST', history, alice['token'], {'text': 'без кэша'}), [201], 1)
expect('неизвестный токен', timed('GET', '/api/v1/users/me', fake), [401], 1)
expect('без Authorization', timed('GET', '/api/v1/users/me'), [401], 1)
expect('/health/ready (Valkey некритичен)', timed('GET', '/health/ready'), [200], 1)
started = time.monotonic()
other = new_user('nocache')
expect('регистрация и вход без кэша', (200, time.monotonic() - started), [200], 1)
expect('logout без кэша', timed('DELETE', '/api/v1/auth/sessions/current', other['token']), [204], 1.5)
expect('отозванный токен', timed('GET', '/api/v1/users/me', other['token']), [401], 1)
finally:
compose('up', '-d', '--wait', 'valkey')
print('1б. Valkey на паузе: logout, затем unpause — отозванный токен не оживает из кэша')
revoked = new_user('paused')
call('GET', '/api/v1/users/me', token=revoked['token'])
compose('pause', 'valkey')
try:
expect('logout при паузе Valkey', timed('DELETE', '/api/v1/auth/sessions/current', revoked['token']), [204], 1.5)
finally:
compose('unpause', 'valkey')
time.sleep(6)
expect('через 6 с после unpause: /users/me', timed('GET', '/api/v1/users/me', revoked['token']), [401], 1)
expect('через 6 с после unpause: сообщение', timed('POST', history, revoked['token'], {'text': 'после logout'}), [401], 1)
print('1в. Valkey на паузе: logout, рестарт API, unpause — отзыв переживает рестарт процесса')
restarted = new_user('restart')
call('GET', '/api/v1/users/me', token=restarted['token'])
compose('pause', 'valkey')
try:
expect('logout при паузе Valkey', timed('DELETE', '/api/v1/auth/sessions/current', restarted['token']), [204], 1.5)
compose('restart', 'api')
wait_ready()
finally:
compose('unpause', 'valkey')
time.sleep(6)
expect('после рестарта API и unpause: /users/me', timed('GET', '/api/v1/users/me', restarted['token']), [401], 1)
expect('после рестарта API и unpause: сообщение', timed('POST', history, restarted['token'], {'text': 'после рестарта'}), [401], 1)
print('2. PostgreSQL остановлен: ограниченная ошибка 503, анонимный запрос не проходит')
compose('stop', 'postgres')
stopped_at = time.monotonic()
try:
expect('GET история', timed('GET', history, alice['token']), [503], 3)
expect('POST сообщение', timed('POST', history, alice['token'], {'text': 'при отказе БД'}), [503], 3)
expect('неизвестный токен (не 200!)', timed('GET', '/api/v1/users/me', fake), [503], 3)
expect('без Authorization', timed('GET', '/api/v1/users/me'), [401], 1)
expect('вход по Basic верным паролем', timed('POST', '/api/v1/auth/sessions',
headers=basic(alice['username'], alice['password'])), [503], 3)
expect('/health/live', timed('GET', '/health/live'), [200], 1)
expect('/health/ready', timed('GET', '/health/ready'), [503], 3)
finally:
compose('up', '-d', '--wait', 'postgres')
ready_at = wait_ready()
print('3. PostgreSQL запущен: готовность через %.1f с после остановки' % (ready_at - stopped_at))
status = call('GET', '/api/v1/users/me', token=alice['token'])[0]
texts = [m['text'] for m in call('GET', history + '?limit=100', token=alice['token'])[2]['items']]
print(' прежний токен -> %d; история: %s' % (status, texts))
if status != 200 or texts != ['до отказа', 'без кэша']:
failures.append('восстановление')
print('4. PostgreSQL заморожен (pause): запросы получают 503 в пределах общего срока, а не зависают')
compose('pause', 'postgres')
try:
expect('GET история', timed('GET', history, alice['token']), [503], 4.5)
expect('POST сообщение', timed('POST', history, alice['token'], {'text': 'при заморозке'}), [503], 4.5)
expect('неизвестный токен (не 200!)', timed('GET', '/api/v1/users/me', fake), [503], 4.5)
expect('вход по Basic', timed('POST', '/api/v1/auth/sessions', headers=basic(alice['username'], alice['password'])), [503], 4.5)
expect('/health/ready', timed('GET', '/health/ready'), [503], 2)
expect('/health/live', timed('GET', '/health/live'), [200], 1)
finally:
compose('unpause', 'postgres')
unpaused = time.monotonic()
wait_ready()
texts = [m['text'] for m in call('GET', history + '?limit=100', token=alice['token'])[2]['items']]
print(' готовность через %.1f с после unpause; история: %s' % (time.monotonic() - unpaused, texts))
if texts != ['до отказа', 'без кэша']:
failures.append('после заморозки')
print('FAIL: ' + ', '.join(failures) if failures else 'PASS: отказы Valkey и PostgreSQL обработаны')
raise SystemExit(1 if failures else 0)
if __name__ == '__main__':
main()