Files
mtusi2026lab7/tests/test_grade4.py
T
wanderinho 7ee5192cbd
Skeleton contracts / contracts (pull_request) Blocked by required conditions
ЛР7 - БПИ2303 - Стругов - на 4
2026-12-06 23:11:49 +03:00

95 lines
4.5 KiB
Python

"""Operator test on an isolated lab5 Compose project; uses only its own attachment."""
import json
import subprocess
import time
from pathlib import Path
from client import Client, check
from test_pipeline import CA_FILE, verify
ROOT = Path(__file__).resolve().parents[1]
def cmd(*args, **kw):
return subprocess.run(['docker','compose',*args], cwd=ROOT, text=True, **kw)
def operator(code, *args, service='worker'):
p = cmd('exec','-T',service,'python','-c',code,*args,check=True,capture_output=True)
return json.loads(p.stdout)
STATE = '''import sys,json,pipeline as p
with p.db(p.settings()()) as c:
j=c.execute("SELECT j.*,a.status,a.error_code FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE a.id=%s",(sys.argv[1],)).fetchone()
print(json.dumps(j,default=str))'''
def state(aid): return operator(STATE,aid)
def wait(fn, seconds=180):
end=time.monotonic()+seconds
while time.monotonic()<end:
result=fn()
if result: return result
time.sleep(.25)
raise AssertionError('deadline exceeded')
# Move only our staging object aside to force a genuine S3 read failure.
MOVE = '''import sys,json,pipeline as p
s=p.s3(p.settings()()); key='staging/'+sys.argv[1]; backup='grade4-test/'+sys.argv[1]
a,b=(key,backup) if sys.argv[2]=='hide' else (backup,key)
s.copy_object(Bucket=p.BUCKET,Key=b,CopySource={'Bucket':p.BUCKET,'Key':a}); s.delete_object(Bucket=p.BUCKET,Key=a)
print(json.dumps(True))'''
# Use a one-shot container when the worker is stopped.
def move(aid, mode):
cmd('run','--rm','--no-deps','-T','--entrypoint','python','worker','-c',MOVE,aid,mode,check=True)
OBJECTS = '''import sys,json,pipeline as p
s=p.s3(p.settings()()); aid=sys.argv[1]; out={}
for prefix in ('staging/'+aid,'originals/'+aid,'variants/'+aid+'/'):
for page in s.get_paginator('list_objects_v2').paginate(Bucket=p.BUCKET,Prefix=prefix):
for o in page.get('Contents',[]): out[o['Key']]=[o['ETag'],o['Size'],o['LastModified'].isoformat()]
print(json.dumps(out))'''
def main():
c=Client(ca_file=CA_FILE,timeout=30)
alice,bob,_,chat=c.bootstrap()
cmd('stop','worker',check=True)
hidden=False
try:
att,raw=c.attachment(alice,chat); aid=att['id']
move(aid,'hide'); hidden=True
cmd('up','-d','--no-deps','worker',check=True)
seen={}
def failed():
j=state(aid)
if j['attempt'] not in seen:
seen[j['attempt']]=j['available_at']; print('attempt',j['attempt'],'available_at',j['available_at'],flush=True)
return j if j['status']=='failed' else None
j=wait(failed)
check(j['attempt']==5 and j['error_code']=='retry_exhausted','wrong retry terminal state')
api=c.call('GET','/api/v1/attachments/'+aid,actor=bob,schema='Attachment')['json']
check(api['status']=='failed' and api['error_code']=='retry_exhausted','wrong API failed state')
print('PASS: retry exhausted at attempt 5',flush=True)
move(aid,'restore'); hidden=False
cmd('exec','-T','worker','python','/app/pipeline.py','replay',aid,check=True)
ready=verify(c,bob,att,raw)
print('PASS: replay recovered same attachment',flush=True)
check(cmd('exec','-T','worker','python','/app/pipeline.py','replay',aid).returncode!=0,'ready replay accepted')
print('PASS: ready replay rejected',flush=True)
wait(lambda: state(aid)['cleaned'])
before=operator(OBJECTS,aid)
check(set(before)=={'originals/'+aid,*('variants/'+aid+'/1/'+n for n in ('thumbnail','crop','optimized'))},'unexpected objects or staging remains')
print('PASS: staging removed; exactly four final keys',flush=True)
duplicate='''import sys,json,pipeline as p
with p.db(p.settings()()) as c:
j=c.execute('SELECT * FROM attachment_jobs WHERE attachment_id=%s',(sys.argv[1],)).fetchone()
print(json.dumps(p.broker().xadd(p.STREAM,{'job':p.payload(j)})))'''
mid=operator(duplicate,aid,service='publisher')
gone='''import sys,json,pipeline as p
print(json.dumps(not p.broker().xrange(p.STREAM,min=sys.argv[1],max=sys.argv[1])))'''
wait(lambda: operator(gone,mid))
check(operator(OBJECTS,aid)==before,'duplicate rewrote objects')
check(verify(c,bob,att,raw)['variants']==ready['variants'],'duplicate changed metadata')
print('PASS: duplicate acknowledged without rewriting objects',flush=True)
finally:
if hidden: move(aid,'restore')
cmd('up','-d','--no-deps','worker',check=True)
if __name__=='__main__': main()