Files
mtusi2026lab3-fork/student-tests/dependencies.py
T

98 lines
4.4 KiB
Python

#!/usr/bin/env python3
"""Previous-lab regressions: durable replay, expiry, rollback and dependency failures."""
from concurrent.futures import ThreadPoolExecutor
import base64
import json
from pathlib import Path
import subprocess
import sys
import time
import uuid
import urllib.request
import urllib.error
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, arguments, check, run
import manage
def main():
def configure(p):
p.add_argument('--mode', choices=('storage', 'expiry'), default='storage')
args = arguments(__doc__, configure)
c = Client(args.base_url, args.ca_file, timeout=10)
if args.mode == 'expiry':
alice = c.user('expiry')
c.call('GET', '/api/v1/users/me', actor=alice)
time.sleep(3)
for _ in range(8):
c.call('GET', '/api/v1/users/me', 401, actor=alice)
print('PASS: short SESSION_TTL_SECONDS expiry across replicas')
return
alice, bob, eve, chat = c.bootstrap()
# Unique constraint must settle simultaneous registration.
body = dict(alice['registration'], username='race_' + uuid.uuid4().hex[:20])
def register(_):
return Client(args.base_url,args.ca_file).call('POST','/api/v1/users',[201,409],body=body)['status']
with ThreadPoolExecutor(max_workers=2) as pool:
check(sorted(pool.map(register,range(2)))==[201,409], 'registration race corrupted uniqueness')
before = c.call('GET','/api/v1/chats?limit=100',actor=alice,schema='ChatPage')['json']
c.call('POST','/api/v1/chats',400,actor=alice,
body={'title':'Rollback','member_ids':[alice['id'],str(uuid.uuid4())]})
after = c.call('GET','/api/v1/chats?limit=100',actor=alice,schema='ChatPage')['json']
check(before==after, 'invalid chat left a visible partial object')
key = uuid.uuid4().hex
original = c.message(alice,chat,'Replay after full restart',key=key)['json']
try:
manage.compose('stop','redis')
check(c.message(alice,chat,'Redis down')['status']==201, 'Redis failure broke writes')
c.call('GET','/api/v1/users/me',401)
manage.start_services('redis')
manage.wait_healthy('redis')
# Revoking with Redis unavailable must still invalidate the authoritative DB.
temp = c.user('revoke')
manage.compose('stop','redis')
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=temp)
manage.start_services('redis')
manage.wait_healthy('redis')
for _ in range(4):
c.call('GET','/api/v1/users/me',401,actor=temp)
manage.compose('stop','postgres')
# LB may answer 502 when every unready backend is excluded. Verify
# API's own dependency semantics inside its private network separately.
source = """import json,sys,urllib.request,urllib.error
actor=json.load(sys.stdin)
for path,want in [('/health/live',200),('/health/ready',503),('/api/v1/users/me',503)]:
req=urllib.request.Request('http://127.0.0.1:8080'+path,headers={'Authorization':'Bearer '+actor['token']})
try:
response=urllib.request.urlopen(req,timeout=8)
except urllib.error.HTTPError as exc:
response=exc
assert response.code==want,(path,response.code,want)
response.close()
print('PASS: API liveness 200, readiness/business 503 while PostgreSQL is down')
"""
subprocess.run(['docker','compose','exec','-T','api-a','python','-c',source],
cwd=ROOT,input=json.dumps({'token':alice['token']}),text=True,check=True)
try:
response=urllib.request.urlopen(c.base+'/api/v1/users/me',timeout=8)
except urllib.error.HTTPError as exc:
response=exc
check(response.code in (401,502,503,504), 'LB must reject unavailable/unauthenticated request')
response.close()
finally:
manage.start_services('postgres','redis')
for s in ('postgres','redis',*manage.SERVICES):
manage.wait_healthy(s)
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
# Stronger persistence check than public smoke: replay an OLD key as well.
manage.restart()
check(c.message(alice,chat,original['text'],key=key)['json']==original, 'idempotency lost on restart')
print('PASS: registration race, invalid chat rollback, Redis fallback, logout, DB 503, restart replay with original token/key')
if __name__ == '__main__':
run(main)