feat:some_improvement

This commit is contained in:
Оля Мороз
2026-10-07 17:33:29 +03:00
parent 828a9f792a
commit 9773639f52
17 changed files with 620 additions and 23 deletions
+147
View File
@@ -0,0 +1,147 @@
#!/usr/bin/env python3
"""
Собственные проверки критериев уровня 4 lab2, не связанные с коротким TTL:
- гонка регистрации одного username (201 + 409);
- откат CreateChat при неизвестном участнике;
- logout удаляет сессию из источника истины;
- недоступность Redis/Valkey: API работает через БД;
- недоступность PostgreSQL: /health/ready → 503.
Истечение сессии при коротком SESSION_TTL_SECONDS — в lab2_expiry.py.
Запуск:
python3 student_tests/lab2_extra.py --base-url http://localhost:8080
"""
import base64
import os
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, Failure, LAB, arguments, check, run # noqa: E402
COMPOSE_ENV = os.environ.get('COMPOSE_ENV_FILE', '.env')
COMPOSE_FILE = os.environ.get('COMPOSE_FILE', 'compose.yaml')
def compose(*args, check_rc=True):
cmd = ['docker', 'compose', '--env-file', COMPOSE_ENV, '-f', COMPOSE_FILE, *args]
proc = subprocess.run(cmd, capture_output=True, text=True)
if check_rc and proc.returncode != 0:
raise Failure('compose %s failed: %s' % (' '.join(args), proc.stderr.strip()))
return proc
def test_redis_down_api_still_works(c):
"""Остановить Redis → API продолжает обслуживать через БД (источник истины)."""
alice, bob, eve, chat = c.bootstrap()
c.call('GET', '/api/v1/users/me', 200, actor=alice, schema='User')
compose('stop', '-t', '1', 'redis')
try:
c.call('GET', '/health/ready', 200, schema='Health')
c.call('GET', '/api/v1/users/me', 200, actor=alice, schema='User')
cred = base64.b64encode(
(alice['registration']['username'] + ':' + alice['registration']['password']).encode()
).decode()
c.call('POST', '/api/v1/auth/sessions', 201,
headers={'Authorization': 'Basic ' + cred}, schema='Session')
c.message(bob, chat, 'redis down, but DB is up')
finally:
compose('start', 'redis')
for _ in range(30):
if compose('ps', '--format', 'json', 'redis', check_rc=False).stdout.find('"Health":"healthy"') >= 0:
break
time.sleep(0.5)
print('PASS: API works through DB when Redis is down')
def test_postgres_down_readiness_503(c):
"""Остановить PostgreSQL → /health/ready должен вернуть 503."""
c.call('GET', '/health/ready', 200, schema='Health')
compose('stop', '-t', '1', 'postgres')
try:
c.call('GET', '/health/ready', 503)
finally:
compose('start', 'postgres')
for _ in range(60):
if compose('ps', '--format', 'json', 'postgres', check_rc=False).stdout.find('"Health":"healthy"') >= 0:
break
time.sleep(0.5)
print('PASS: /health/ready returns 503 when PostgreSQL is down')
def test_username_race(c):
"""Два параллельных POST с одинаковым username: ровно один 201, другой 409."""
username = 'race_' + str(int(time.time() * 1000))[-8:]
body = {'username': username, 'display_name': 'Race',
'password': 'T3st-Race-password-123'}
def post():
try:
r = c.call('POST', '/api/v1/users', (201, 409), body=body)
return r['status']
except Failure:
return -1
with ThreadPoolExecutor(max_workers=2) as pool:
statuses = list(pool.map(lambda _: post(), range(2)))
check(sorted(statuses) == [201, 409],
'username race produced statuses %r, expected [201,409]' % statuses)
print('PASS: username race yields exactly one 201 and one 409')
def test_create_chat_rollback_unknown_member(c):
"""CreateChat с неизвестным UUID: 400, и в БД нет ни чата, ни membership."""
alice, _, _, _ = c.bootstrap()
unknown = '99999999-9999-4999-8999-999999999999'
body = {'title': 'rollback ' + str(int(time.time())),
'member_ids': [alice['id'], unknown]}
c.call('POST', '/api/v1/chats', 400, actor=alice, body=body)
listed = c.call('GET', '/api/v1/chats?limit=100', actor=alice, schema='ChatPage')['json']
check(all(ch['title'] != body['title'] for ch in listed['items']),
'rollback failed: partial chat persisted')
print('PASS: create chat is atomic; unknown member aborts the whole operation')
def test_logout_removes_from_source_of_truth(c):
"""Logout должен отзывать сессию так, чтобы она не воскресла из кэша/БД."""
alice, _, _, _ = c.bootstrap()
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
c.call('GET', '/api/v1/users/me', 401, actor=alice)
c.call('GET', '/api/v1/users/me', 401, actor=alice)
print('PASS: logout revokes session in source of truth')
def main():
def configure(p):
p.add_argument('--skip-docker', action='store_true',
help='пропустить сценарии с остановкой redis/postgres')
args = arguments('Lab2 собственные проверки уровня 4 (без короткого TTL)', configure)
check(LAB == 2, 'this test targets lab2 only')
c = Client(args.base_url, args.ca_file)
test_username_race(c)
test_create_chat_rollback_unknown_member(c)
test_logout_removes_from_source_of_truth(c)
if args.skip_docker:
print('SKIP: --skip-docker set; skipped redis/postgres down tests')
else:
test_redis_down_api_still_works(c)
test_postgres_down_readiness_503(c)
print('PASS: lab2 level-4 criteria (own tests, no short TTL)')
if __name__ == '__main__':
run(main)