Files
mtusi2026lab4/student-tests/regressions.py
T

82 lines
4.3 KiB
Python
Executable File
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Регрессии по замечаниям проверки lab3.
1. Видимость подтверждённой записи при отказе Redis в командах инвалидации:
чат с двумя сообщениями → закэшировать историю → в Redis запретить команды
через ACL (сначала только INCR, затем INCR+DEL+UNLINK+SCAN) → отправить
третье сообщение → каждое следующее чтение через LB обязано вернуть его.
2. Пароль из одних пробельных символов при регистрации → 400.
Нужен запущенный Docker-стенд (redis-cli вызывается через docker compose exec).
ACL всегда восстанавливается в finally. --only cache|password запускает одну часть.
"""
import subprocess
import sys
import uuid
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) # публичный client.py
from client import Client, arguments, check, run
from resilience import history
ROOT = Path(__file__).resolve().parents[1]
WHITESPACE_PASSWORDS = (' ' * 12, '\t' * 12, '  ' * 8)
def redis_cli(*args):
r = subprocess.run(['docker', 'compose', 'exec', '-T', 'redis', 'redis-cli', *args],
cwd=ROOT, capture_output=True, text=True, timeout=30)
check(r.returncode == 0, 'redis-cli failed: ' + r.stderr.strip())
return r.stdout.strip()
def visibility_case(c, alice, bob, chat, denied):
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=50'
before = [m['id'] for m in history(c, bob, chat)]
# Прогреваем кэш на обеих репликах.
for _ in range(4):
c.call('GET', path, actor=bob, schema='MessagePage')
redis_cli('ACL', 'SETUSER', 'default', *('-' + cmd for cmd in denied))
try:
sent = c.message(alice, chat, 'после запрета ' + '+'.join(denied))['json']
# Каждое следующее чтение (через любую реплику) видит подтверждённую запись.
for i in range(6):
page = c.call('GET', path, actor=bob, schema='MessagePage')
ids = [m['id'] for m in page['json']['items']]
check(sent['id'] in ids, 'read %d after 201 misses confirmed message (denied: %s)' % (i, denied))
# Порядок (created_at до секунды, id): новое сообщение той же секунды может
# встать раньше старых, поэтому проверяем наличие, а не префикс.
check(set(before) <= set(ids), 'previously confirmed messages missing')
finally:
# reset — чтобы снять и точечные запреты, независимо от порядка правил.
redis_cli('ACL', 'SETUSER', 'default', 'reset', 'on', 'nopass', '~*', '&*', '+@all')
return len(before) + 1
def main():
def configure(p):
p.add_argument('--only', choices=['password', 'cache'], default=None)
args = arguments('Regression checks for lab3 review findings', configure)
c = Client(args.base_url, args.ca_file)
# 2. Пароль из пробельных символов (пробелы, табуляции, неразрывные пробелы).
if args.only in (None, 'password'):
for pw in WHITESPACE_PASSWORDS:
c.call('POST', '/api/v1/users', 400,
body={'username': 'ws_' + uuid.uuid4().hex[:10], 'display_name': 'WS', 'password': pw})
print('PASS: whitespace-only password rejected with 400 (3 variants)')
if args.only == 'password':
return
# 1. Видимость записи при отказе Redis.
alice, bob, _, chat = c.bootstrap()
c.message(alice, chat, 'первое')
c.message(bob, chat, 'второе')
n = visibility_case(c, alice, bob, chat, ['incr'])
print('PASS: Redis ACL -incr: message visible on every next read (%d in history)' % n)
n = visibility_case(c, alice, bob, chat, ['incr', 'del', 'unlink', 'scan'])
print('PASS: Redis ACL -incr -del -unlink -scan: message visible on every next read (%d in history)' % n)
if __name__ == '__main__':
run(main)