#!/usr/bin/env python3 """Проверяет заполнение кеша, fallback, запись и logout при отказе Redis.""" import hashlib from pathlib import Path import subprocess import sys sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) from client import Client, check def compose(*args, **kwargs): return subprocess.run(['docker', 'compose', *args], check=True, **kwargs) def main(): c = Client() alice, bob, _, chat = c.bootstrap() c.call('GET', '/api/v1/users/me', actor=alice, schema='User') key = 'session:' + hashlib.sha256(alice['token'].encode('ascii')).hexdigest() # Хеш ключа передаётся через stdin и не выводится. result = compose('exec', '-T', 'redis', 'redis-cli', '-x', 'EXISTS', input=key, text=True, capture_output=True) check(result.stdout.strip() == '1', 'session profile was not cached') result = compose('exec', '-T', 'redis', 'redis-cli', '-x', 'TTL', input=key, text=True, capture_output=True) check(0 < int(result.stdout) <= 3600, 'cache TTL missing') print('PASS: Redis contains session profile with TTL') try: compose('stop', 'redis') c.call('GET', '/api/v1/users/me', actor=alice, schema='User') message = c.message(alice, chat, 'Redis fallback check')['json'] page = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=bob, schema='MessagePage')['json'] check(any(m['id'] == message['id'] for m in page['items']), 'fallback lost message') c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice) c.call('GET', '/api/v1/users/me', 401, actor=alice) print('PASS: PostgreSQL read/write and logout work without Redis') finally: compose('up', '-d', '--wait', 'redis') c.call('GET', '/api/v1/users/me', 401, actor=alice) c.call('GET', '/api/v1/users/me', actor=bob, schema='User') print('PASS: stale cache cannot revive revoked session; Redis recovered') if __name__ == '__main__': main()