"""Usage (стенд уже запущен через docker compose up -d): python student-tests/failure_check.py Останавливает Valkey, затем PostgreSQL (docker compose stop, без удаления volumes), проверяет поведение API и восстановление после docker compose start. """ 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) expect('отозванный токен', timed('GET', '/api/v1/users/me', other['token']), [401], 1) finally: compose('up', '-d', '--wait', 'valkey') 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('FAIL: ' + ', '.join(failures) if failures else 'PASS: отказы Valkey и PostgreSQL обработаны') raise SystemExit(1 if failures else 0) if __name__ == '__main__': main()