113 lines
10 KiB
Python
113 lines
10 KiB
Python
|
|
"""Real local HTTP regression. Creates only explicitly marked non-device tasks.
|
||
|
|
|
||
|
|
No scan, motion, homing or third-party endpoint is invoked. Keep test sources;
|
||
|
|
remove the batch using cleanup_verification.py after UI verification succeeds.
|
||
|
|
"""
|
||
|
|
from __future__ import annotations
|
||
|
|
import argparse,datetime,hashlib,io,json,sys,urllib.request,urllib.error,uuid,zipfile
|
||
|
|
from pathlib import Path
|
||
|
|
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
||
|
|
from verify_cmvr_native import Client
|
||
|
|
|
||
|
|
def pdf():
|
||
|
|
objects=[b'<< /Type /Catalog /Pages 2 0 R >>',b'<< /Type /Pages /Kids [3 0 R] /Count 1 >>',b'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>',b'<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>']
|
||
|
|
text=b'BT /F1 14 Tf 30 120 Td (QA fixture - not a customer report) Tj ET';objects.append(b'<< /Length '+str(len(text)).encode()+b' >>\nstream\n'+text+b'\nendstream')
|
||
|
|
data=b'%PDF-1.4\n';offsets=[0]
|
||
|
|
for n,obj in enumerate(objects,1):offsets.append(len(data));data+=f'{n} 0 obj\n'.encode()+obj+b'\nendobj\n'
|
||
|
|
xref=len(data);data+=f'xref\n0 {len(offsets)}\n0000000000 65535 f \n'.encode()+b''.join(f'{o:010d} 00000 n \n'.encode() for o in offsets[1:]);data+=f'trailer\n<< /Size {len(offsets)} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n'.encode();return data
|
||
|
|
PLY=b'ply\nformat ascii 1.0\nelement vertex 3\nproperty float x\nproperty float y\nproperty float z\nend_header\n0 0 0\n1 0 0\n0 1 0\n'
|
||
|
|
STL=b'solid qa\nfacet normal 0 0 1\nouter loop\nvertex 0 0 0\nvertex 1 0 0\nvertex 0 1 0\nendloop\nendfacet\nendsolid qa\n'
|
||
|
|
|
||
|
|
def run(prefix):
|
||
|
|
if not prefix.startswith('SCANQA-DIMENSION-') or len(prefix)<24:raise ValueError('Use a full dimension verification batch prefix')
|
||
|
|
c=Client().login();report={'prefix':prefix,'createdTasks':[],'checks':[],'deviceCalls':0,'thirdPartyCalls':0}
|
||
|
|
checkpoint=ROOT/'.local/dimension-http-verification.json'
|
||
|
|
def save():checkpoint.write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
|
||
|
|
def check(name,condition):
|
||
|
|
if not condition:raise AssertionError(name)
|
||
|
|
report['checks'].append(name);save()
|
||
|
|
def api(method,path,data=None,query=None,ok=True):
|
||
|
|
result=c.request(method,'/admin-api/lab/dimension'+path,body=data,query=query,expected=(0,) if ok else None)
|
||
|
|
return result.get('data') if ok else result
|
||
|
|
def raw(path,fields=None,uploads=None,auth=True):
|
||
|
|
boundary='----DimensionQA'+uuid.uuid4().hex;body=b''
|
||
|
|
if fields is not None:
|
||
|
|
for name,value in fields.items():body+=f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode()
|
||
|
|
for name,(filename,payload) in (uploads or {}).items():body+=f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"; filename="{filename}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode()+payload+b'\r\n'
|
||
|
|
body+=f'--{boundary}--\r\n'.encode()
|
||
|
|
headers={'tenant-id':'1'}
|
||
|
|
if auth:headers['Authorization']='Bearer '+c._token
|
||
|
|
if fields is not None:headers['Content-Type']='multipart/form-data; boundary='+boundary
|
||
|
|
request=urllib.request.Request(c.base_url+'/admin-api/lab/dimension'+path,data=body if fields is not None else None,headers=headers)
|
||
|
|
try:
|
||
|
|
with urllib.request.urlopen(request,timeout=60) as response:return response.read(),response.headers.get('content-type','')
|
||
|
|
except urllib.error.HTTPError as error:return error.read(),error.headers.get('content-type','')
|
||
|
|
def multipart(path,fields,uploads,ok=True):
|
||
|
|
data,_=raw(path,fields,uploads);result=json.loads(data)
|
||
|
|
if ok:check('POST '+path+' accepted',result.get('code')==0);return result['data']
|
||
|
|
check('POST '+path+' rejected invalid input',result.get('code')!=0);return result
|
||
|
|
for name,qty in [('A',2),('B',1)]:
|
||
|
|
task=api('POST','/create',{'taskName':prefix+'-'+name,'externalTaskNo':prefix+'-'+name,'sampleCode':prefix+'-S'+name,'sampleName':'QA fixture '+name,'quantity':qty,'requirement':'Verification only; no device execution'})
|
||
|
|
report['createdTasks'].append(str(task));save()
|
||
|
|
task,other=report['createdTasks'];get=lambda unit=0:api('GET','/get',query={'taskId':task,'unitId':unit})
|
||
|
|
detail=get();unit=str(detail['units'][0]['id']);second=str(detail['units'][1]['id']);other_unit=str(api('GET','/get',query={'taskId':other})['units'][0]['id'])
|
||
|
|
check('new task is a pending scan draft without selecting a scan plan',detail['task']['processType']=='SCAN_ONLY' and detail['task']['status']=='PENDING_CONFIRM')
|
||
|
|
def upload(role,name,payload,unitId=0):return str(multipart('/upload',{'taskId':task,'unitId':unitId,'role':role},{'file':(name,payload)}))
|
||
|
|
model=upload('MODEL','part.stp',b'ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\nENDSEC;\nEND-ISO-10303-21;')
|
||
|
|
drawing=upload('DRAWING','drawing.pdf',pdf());cloud=upload('SCAN_CLOUD','scan.ply',PLY,unit)
|
||
|
|
selection={'taskId':task,'unitId':unit,'revision':0,'modelId':model,'drawingId':drawing,'cloudId':cloud,'reason':'QA explicit input selection'}
|
||
|
|
api('PUT','/select',selection);check('inputs complete but not sent',get(unit)['stage']=='READY')
|
||
|
|
wrong=dict(selection,unitId=second);check('cloud cannot be assigned to a different sample',api('PUT','/select',wrong,ok=False)['code']!=0)
|
||
|
|
wrong=dict(selection,taskId=other,unitId=other_unit);check('files cannot cross tasks',api('PUT','/select',wrong,ok=False)['code']!=0)
|
||
|
|
check('stale revision is rejected',api('PUT','/select',selection,ok=False)['code']!=0)
|
||
|
|
api('POST','/prepare',{'taskId':task,'unitId':unit,'revision':1});detail=get(unit);check('comparison stays explicitly pending',detail['stage']=='WAITING_COMPARISON' and detail['comparisonConnected'] is False)
|
||
|
|
fields={'taskId':task,'unitId':unit,'revision':2,'externalNo':prefix+'-EXT1','reason':'QA synthetic fixture; not a customer comparison result'}
|
||
|
|
multipart('/delivery',fields,{'stl':('result.stl',STL),'pdf':('report.pdf',b'bad pdf')},False)
|
||
|
|
check('partial pair rolled back',len(get(unit)['files'])==3)
|
||
|
|
delivery=multipart('/delivery',fields,{'stl':('result.stl',STL),'pdf':('report.pdf',pdf())})
|
||
|
|
check('results wait for human confirmation',get(unit)['stage']=='PENDING_CONFIRM')
|
||
|
|
content,_=raw('/package?id='+str(delivery));check('unconfirmed package cannot be downloaded',json.loads(content).get('code')!=0)
|
||
|
|
check('unchecked confirmation rejected',api('POST','/confirm',{'deliveryId':delivery,'revision':3,'filesConfirmed':False},ok=False)['code']!=0)
|
||
|
|
api('POST','/confirm',{'deliveryId':delivery,'revision':3,'filesConfirmed':True});detail=get(unit);check('confirmed sample is delivered',detail['stage']=='DELIVERED')
|
||
|
|
check('another unfinished sample prevents overall task completion',detail['task']['status']=='CLAIMED')
|
||
|
|
blob,kind=raw('/package?id='+str(delivery));check('package is binary zip','zip' in kind)
|
||
|
|
with zipfile.ZipFile(io.BytesIO(blob)) as zip:
|
||
|
|
check('package includes actual paired STL and PDF',zip.read('result.stl')==STL and zip.read('report.pdf')==pdf());manifest=json.loads(zip.read('manifest.json'));check('manifest contains frozen inputs and checksums','signature' in json.loads(manifest['delivery']['input_json']) and len(manifest['mesh']['sha256'])==64)
|
||
|
|
new_model=upload('MODEL','revision.x_t',b'PARASOLID QA fixture')
|
||
|
|
api('PUT','/select',dict(selection,revision=4,modelId=new_model));detail=get(unit);check('input changes preserve history but mark it stale',detail['stage']=='READY' and len(detail['deliveries'])==1 and not detail['deliveries'][0]['current'])
|
||
|
|
check('stale result cannot be reconfirmed',api('POST','/confirm',{'deliveryId':delivery,'revision':5,'filesConfirmed':True},ok=False)['code']!=0)
|
||
|
|
historic,_=raw('/package?id='+str(delivery));check('old confirmed delivery remains downloadable',historic[:2]==b'PK')
|
||
|
|
# Finish every sample, then replace one input to verify the task reopens.
|
||
|
|
api('POST','/prepare',{'taskId':task,'unitId':unit,'revision':5})
|
||
|
|
current=multipart('/delivery',dict(fields,revision=6,externalNo=prefix+'-EXT2'),{'stl':('result.stl',STL),'pdf':('report.pdf',pdf())})
|
||
|
|
api('POST','/confirm',{'deliveryId':current,'revision':7,'filesConfirmed':True})
|
||
|
|
second_cloud=upload('SCAN_CLOUD','second.ply',PLY,second)
|
||
|
|
api('PUT','/select',dict(selection,unitId=second,revision=0,modelId=new_model,cloudId=second_cloud))
|
||
|
|
api('POST','/prepare',{'taskId':task,'unitId':second,'revision':1})
|
||
|
|
second_delivery=multipart('/delivery',dict(fields,unitId=second,revision=2,externalNo=prefix+'-EXT3'),{'stl':('second.stl',STL),'pdf':('second.pdf',pdf())})
|
||
|
|
api('POST','/confirm',{'deliveryId':second_delivery,'revision':3,'filesConfirmed':True})
|
||
|
|
check('all samples delivered completes an imported-cloud task',get(unit)['task']['status']=='COMPLETED')
|
||
|
|
third_model=upload('MODEL','new-input.stp',b'ISO-10303-21; QA changed input version')
|
||
|
|
api('PUT','/select',dict(selection,revision=8,modelId=third_model))
|
||
|
|
check('replacing an input reopens the task without deleting history',get(unit)['task']['status']=='CLAIMED' and len(get(unit)['deliveries'])==2)
|
||
|
|
anonymous,_=raw('/page',auth=False);check('anonymous requests are rejected',json.loads(anonymous).get('code')==401)
|
||
|
|
report['success']=True;report['uiTask']=task;report['uiUnit']=unit;save();print(json.dumps({'prefix':prefix,'checks':len(report['checks']),'success':True,'uiTask':task,'cleanupRequired':True}))
|
||
|
|
return report
|
||
|
|
def verify_scan_draft(case_id):
|
||
|
|
"""Create an unconfirmed draft only, using an explicitly selected existing case."""
|
||
|
|
checkpoint=ROOT/'.local/dimension-http-verification.json';report=json.loads(checkpoint.read_text())
|
||
|
|
assert report['success'] and report['prefix'].startswith('SCANQA-DIMENSION-')
|
||
|
|
c=Client().login();prefix=report['prefix']
|
||
|
|
result=c.request('POST','/admin-api/lab/dimension/create',body={'taskName':prefix+'-SCAN','externalTaskNo':prefix+'-SCAN','sampleCode':prefix+'-SSC','sampleName':'QA scan draft only','quantity':1,'testCaseId':case_id},expected=(0,))
|
||
|
|
task=str(result['data']);report['createdTasks'].append(task);report['scanDraftTask']=task;checkpoint.write_text(json.dumps(report,indent=2))
|
||
|
|
detail=c.request('GET','/admin-api/lab/dimension/get',query={'taskId':task},expected=(0,))['data']
|
||
|
|
assert detail['task']['processType']=='SCAN_ONLY' and detail['task']['status']=='PENDING_CONFIRM'
|
||
|
|
assert len(detail['units'])==1 and detail['units'][0]['status']=='PENDING'
|
||
|
|
report['checks'].append('published scan case creates an unconfirmed draft without device execution');checkpoint.write_text(json.dumps(report,indent=2))
|
||
|
|
print(json.dumps({'scanDraftVerified':True,'deviceCalls':0}))
|
||
|
|
|
||
|
|
if __name__=='__main__':
|
||
|
|
parser=argparse.ArgumentParser();parser.add_argument('--prefix',default='SCANQA-DIMENSION-'+datetime.datetime.now().strftime('%Y%m%d-%H%M%S'));parser.add_argument('--scan-case-id');args=parser.parse_args()
|
||
|
|
if args.scan_case_id:verify_scan_draft(args.scan_case_id)
|
||
|
|
else:run(args.prefix)
|