Files
mtusi2026lab4/student-tests/expiry_check.py
T

57 lines
2.3 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/expiry_check.py --ttl 2
Скрипт пересоздаёт только api с SESSION_TTL_SECONDS=<ttl>, проверяет истечение сессии,
затем возвращает api с обычным TTL из .env. Volumes и данные не трогаются.
"""
import argparse
import hashlib
import os
import time
from helpers import call, compose, new_user, wait_ready
def restart_api(ttl=None):
env = dict(os.environ)
if ttl is None:
env.pop('SESSION_TTL_SECONDS', None)
else:
env['SESSION_TTL_SECONDS'] = str(ttl)
compose('up', '-d', '--no-deps', '--no-build', 'api', env=env)
wait_ready()
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--ttl', type=int, default=2)
args = parser.parse_args()
print('пересоздаю api с SESSION_TTL_SECONDS=%d' % args.ttl)
restart_api(args.ttl)
try:
alice = new_user('expiry')
status = call('GET', '/api/v1/users/me', token=alice['token'])[0]
print('сразу после входа: /users/me -> %d' % status)
assert status == 200
key = 'session:' + hashlib.sha256(alice['token'].encode()).hexdigest()
cache_ttl = int(compose('exec', '-T', 'valkey', 'valkey-cli', 'TTL', key))
print('TTL ключа этой сессии в Valkey: %d с (-2 = ключа нет)' % cache_ttl)
assert cache_ttl <= args.ttl, 'кэш живёт дольше сессии'
time.sleep(args.ttl + 1.5)
status, headers, _ = call('GET', '/api/v1/users/me', token=alice['token'])
print('через %.1f с: /users/me -> %d, WWW-Authenticate: %s' % (args.ttl + 1.5, status, headers['WWW-Authenticate']))
assert status == 401 and headers['WWW-Authenticate'] == 'Bearer realm="messenger"'
status = call('DELETE', '/api/v1/auth/sessions/current', token=alice['token'])[0]
print('logout истёкшим токеном -> %d' % status)
assert status == 401
print('PASS: сессия истекла по SESSION_TTL_SECONDS=%d, кэш не продлил её' % args.ttl)
finally:
print('возвращаю api с TTL из .env')
restart_api()
if __name__ == '__main__':
main()