cmvr-visual/qa/v2_api_acceptance.py

115 lines
7.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Live private-entry acceptance. Never prints credentials, cookies or token text."""
import io,json,secrets,time
from pathlib import Path
import requests
from PIL import Image
ROOT=Path(__file__).resolve().parents[1]
ENV=dict(line.split('=',1) for line in (ROOT/'.env.server').read_text(encoding='utf-8-sig').splitlines() if line and not line.startswith('#') and '=' in line)
BASE='http://127.0.0.1:8000/api'
report={}
def login(username,password):
client=requests.Session()
response=client.post(BASE+'/auth/login',json={'username':username,'password':password},timeout=15)
assert response.status_code==200,('login',response.status_code)
client.headers['X-CSRF-Token']=response.json()['csrf_token']
return client
admin=login(ENV['ADMIN_USERNAME'],ENV['ADMIN_PASSWORD'])
browser=json.loads((ROOT/'qa/v2-browser.json').read_text(encoding='utf-8'))
run_id=browser['run_id']
token_id=user_id=asset_id=None
other=machine=None
try:
report['readiness']=admin.get(BASE+'/ready',timeout=8).json()
username='v2_verify_'+secrets.token_hex(4)
password=secrets.token_urlsafe(24)
created=admin.post(BASE+'/auth/users',json={'username':username,'display_name':'V2隔离验收(完成后停用)','password':password},timeout=15)
assert created.status_code==201,('create_user',created.status_code)
user_id=created.json()['id'];other=login(username,password)
replacement=secrets.token_urlsafe(24)
assert other.post(BASE+'/auth/password',json={'current_password':password,'new_password':replacement},timeout=15).status_code==200
assert other.get(BASE+'/auth/me',timeout=8).status_code==401
other.close();other=login(username,replacement)
report['password_change_revokes_session']=True
for route in ('/workflow-runs/'+run_id,):
assert other.get(BASE+route,timeout=8).status_code==404
report['run_owner_isolation']=True
data=io.BytesIO();Image.new('RGB',(24,16),'#42c7a1').save(data,format='PNG')
uploaded=admin.post(BASE+'/assets',files={'file':('v2-owned-check.png',data.getvalue(),'image/png')},timeout=15)
assert uploaded.status_code==201,('upload',uploaded.status_code)
asset_id=uploaded.json()['id']
assert other.get(BASE+'/assets/'+asset_id+'/content',timeout=8).status_code==404
assert admin.patch(BASE+'/assets/'+asset_id,json={'favorite':True,'tags':['v2-验收']},timeout=8).status_code==200
matches=admin.get(BASE+'/assets',params={'favorite':'true','tag':'v2-验收','origin':'upload'},timeout=8).json()
assert asset_id in [a['id'] for a in matches['items']]
ranged=admin.get(BASE+'/assets/'+asset_id+'/content',headers={'Range':'bytes=0-15'},timeout=8)
assert ranged.status_code==206 and len(ranged.content)==16
report['upload_filters_range_owner']=True
scopes=['jobs:read','jobs:write','assets:read','workflows:read','batches:read','batches:write','events:read']
made=admin.post(BASE+'/auth/tokens',json={'name':'V2受控验收','scopes':scopes},timeout=8)
assert made.status_code==201,('token',made.status_code)
saved=made.json();token_id=saved['record']['id']
machine=requests.Session();machine.headers['Authorization']='Bearer '+saved['token']
assert machine.get(BASE+'/auth/users',timeout=8).status_code==403
rejected=machine.post(BASE+'/jobs',json={'task_type':'math.solve','input':{'prompt':'2+3'},'execution_mode':'interactive'},headers={'Idempotency-Key':'v2-scope-denial-'+secrets.token_hex(6)},timeout=8)
assert rejected.status_code==403
report['machine_cannot_admin_or_bypass_interactive_scope']=True
body={'name':'V2 HTTP断开与串行验收','items':[
{'kind':'job','task_type':'math.solve','input':{'prompt':'只输出数字:2+3等于多少?'},'parameters':{'max_tokens':32,'enable_thinking':False}},
{'kind':'job','task_type':'math.solve','input':{'prompt':'只输出数字:3乘4等于多少?'},'parameters':{'max_tokens':32,'enable_thinking':False}}]}
key='v2-live-batch-'+secrets.token_hex(8)
accepted=machine.post(BASE+'/batches',json=body,headers={'Idempotency-Key':key},timeout=15)
assert accepted.status_code==202,('batch',accepted.status_code,accepted.text[:200])
batch=accepted.json();bid=batch['batch']['id']
replay=machine.post(BASE+'/batches',json=body,headers={'Idempotency-Key':key},timeout=15)
assert replay.status_code==202 and replay.json()['batch']['id']==bid
control=machine.post(BASE+'/batches/'+bid+'/control',json={'desired_state':'pause'},headers={'Idempotency-Key':'pause-'+key},timeout=8)
assert control.status_code==200
assert machine.post(BASE+'/batches/'+bid+'/control',json={'desired_state':'run'},headers={'Idempotency-Key':'resume-'+key},timeout=8).status_code==200
assert other.get(BASE+'/batches/'+bid,timeout=8).status_code==404
# Close the caller's HTTP client. Coordinator uses independent durable jobs.
machine.close();machine=None
deadline=time.monotonic()+90
while time.monotonic()<deadline:
current=admin.get(BASE+'/batches/'+bid,timeout=8).json()
if current['batch']['state'] in {'succeeded','completed_with_errors','blocked','cancelled'}:break
time.sleep(1)
assert current['batch']['state']=='succeeded',('batch_result',current['batch']['state'])
answers=[]
for item in current['items']:
job=admin.get(BASE+'/jobs/'+item['target_id'],timeout=8).json()
assert job['state']=='succeeded'
answers.append((job.get('result') or {}).get('text',''))
assert '5' in answers[0] and '12' in answers[1],('math_output',answers)
report['batch']={'id':bid,'idempotent':True,'pause_resume':True,'http_close_continues':True,'state':'succeeded','answers':answers}
machine=requests.Session();machine.headers['Authorization']='Bearer '+saved['token']
stream=machine.get(BASE+'/events',stream=True,timeout=(8,8))
assert stream.status_code==200
lines=stream.iter_lines(chunk_size=1)
assert next(lines)==b': connected'
assert admin.delete(BASE+'/auth/tokens/'+token_id,timeout=8).status_code==204
# At most one buffered delimiter may remain; revoked streams end at next poll.
list(lines)
stream.close()
assert machine.get(BASE+'/jobs',timeout=8).status_code==401
report['token_revocation_ends_sse']=True
final_run=admin.get(BASE+'/workflow-runs/'+run_id,timeout=8).json()
report['workflow']={'id':run_id,'state':final_run['run']['state'],'steps':[{k:s[k] for k in ('step_key','state','selected_job_id')} for s in final_run['steps']]}
finally:
if token_id:admin.delete(BASE+'/auth/tokens/'+token_id,timeout=8)
if asset_id:admin.delete(BASE+'/assets/'+asset_id,timeout=8)
if user_id:
disabled=admin.patch(BASE+'/auth/users/'+user_id,json={'disabled':True},timeout=8)
report['verification_user_disabled']=disabled.status_code==200
if other:report['disabled_session_revoked']=other.get(BASE+'/auth/me',timeout=8).status_code==401
for client in (other,machine,admin):
if client:client.close()
(ROOT/'qa/v2-api.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
print(json.dumps(report,ensure_ascii=False))