forked from mtusi2026/mtusi2026lab2
feat:some_improvement
This commit is contained in:
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Проверка истечения сессии при коротком SESSION_TTL_SECONDS.
|
||||
|
||||
Сам:
|
||||
1. Запоминает текущее значение SESSION_TTL_SECONDS в .env.
|
||||
2. Ставит временное (по умолчанию 2) и перезапускает контейнер api.
|
||||
3. Ждёт /health/ready.
|
||||
4. Регистрирует пользователя, создаёт сессию, убеждается, что токен живой,
|
||||
ждёт TTL+2 с и убеждается, что тот же токен даёт 401.
|
||||
5. Восстанавливает .env и перезапускает api (в finally).
|
||||
|
||||
Запуск:
|
||||
python3 student_tests/lab2_expiry.py --base-url http://localhost:8080 --ttl 2
|
||||
|
||||
.env остаётся в исходном состоянии даже при ошибке теста.
|
||||
"""
|
||||
import base64
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
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 read_env_ttl():
|
||||
"""Возвращает (value, exists): значение SESSION_TTL_SECONDS из .env, если есть."""
|
||||
try:
|
||||
with open(COMPOSE_ENV, 'r', encoding='utf-8') as f:
|
||||
for line in f:
|
||||
if line.startswith('SESSION_TTL_SECONDS='):
|
||||
return line.split('=', 1)[1].strip(), True
|
||||
except FileNotFoundError:
|
||||
raise Failure('no %s' % COMPOSE_ENV)
|
||||
return '', False
|
||||
|
||||
|
||||
def write_env_ttl(value, existed):
|
||||
"""Перезаписывает SESSION_TTL_SECONDS, сохраняя остальные строки."""
|
||||
with open(COMPOSE_ENV, 'r', encoding='utf-8') as f:
|
||||
lines = f.readlines()
|
||||
lines = [ln for ln in lines if not ln.startswith('SESSION_TTL_SECONDS=')]
|
||||
if existed:
|
||||
lines.append('SESSION_TTL_SECONDS=%s\n' % value)
|
||||
with open(COMPOSE_ENV, 'w', encoding='utf-8') as f:
|
||||
f.writelines(lines)
|
||||
|
||||
|
||||
def restart_api():
|
||||
compose('up', '-d', '--force-recreate', 'api')
|
||||
|
||||
|
||||
def wait_ready(base_url, timeout=90):
|
||||
# curl без внешних зависимостей: используем http.client через urllib.
|
||||
import urllib.request
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(base_url + '/health/ready', timeout=2) as r:
|
||||
if r.status == 200:
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
raise Failure('API did not become ready within %d s' % timeout)
|
||||
|
||||
|
||||
def test_short_ttl_expiry(c, ttl_seconds):
|
||||
username = 'ttl_' + str(int(time.time()))
|
||||
password = 'T3st-' + username
|
||||
body = {'username': username, 'display_name': 'TTL', 'password': password}
|
||||
user = c.call('POST', '/api/v1/users', 201, body=body, schema='User')['json']
|
||||
cred = base64.b64encode(('%s:%s' % (username, password)).encode()).decode()
|
||||
session = c.call('POST', '/api/v1/auth/sessions', 201,
|
||||
headers={'Authorization': 'Basic ' + cred},
|
||||
schema='Session')['json']
|
||||
actor = {'id': user['id'], 'user': user, 'token': session['token']}
|
||||
|
||||
c.call('GET', '/api/v1/users/me', 200, actor=actor, schema='User')
|
||||
time.sleep(ttl_seconds + 2)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=actor)
|
||||
print('PASS: session expires after SESSION_TTL_SECONDS=%d' % ttl_seconds)
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--ttl', type=int, default=2,
|
||||
help='короткий SESSION_TTL_SECONDS на время теста')
|
||||
|
||||
args = arguments('Lab2: истечение сессии при коротком TTL', configure)
|
||||
check(LAB == 2, 'this test targets lab2 only')
|
||||
check(1 <= args.ttl <= 5, '--ttl must be 1..5 (короткий TTL только для этого теста)')
|
||||
|
||||
original, existed = read_env_ttl()
|
||||
print('original SESSION_TTL_SECONDS=%s' % (original if existed else '<unset>'))
|
||||
|
||||
def restore():
|
||||
print('restoring SESSION_TTL_SECONDS=%s' % (original if existed else '<unset>'))
|
||||
write_env_ttl(original, existed)
|
||||
restart_api()
|
||||
|
||||
try:
|
||||
write_env_ttl(str(args.ttl), True)
|
||||
print('starting API with SESSION_TTL_SECONDS=%d' % args.ttl)
|
||||
restart_api()
|
||||
wait_ready(args.base_url)
|
||||
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
test_short_ttl_expiry(c, args.ttl)
|
||||
finally:
|
||||
restore()
|
||||
|
||||
print('PASS: lab2 short-TTL expiry (own test)')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user