am-freescan/scripts/verify_local_framework.py
lixiaolong 64db825a9f feat: 完善设备工作流集成、组合执行与主题适配
集成旋转底座、机械臂示教与坐标系,完善扫描参数、电量和框架点复用。增加组合执行、步骤进度与日志,优化首屏和流程画布性能,修复表头主题适配,并保留验证脚本和回归测试。
2026-11-02 17:38:34 +08:00

90 lines
6.9 KiB
Python

"""Local archive/fixture HTTP regression. Never executes scanner or other hardware controls.
Only creates fixtures and local files under a unique E2E prefix, then removes its own
rows and exact archived IDs after a successful run. Failed runs retain diagnostics.
"""
from concurrent.futures import ThreadPoolExecutor
import argparse
import hashlib
import json
from pathlib import Path
import re
import urllib.request
import urllib.error
from verify_cmvr_native import Client, TargetReadOnlyDb, require, unique_prefix
ROOT=Path(__file__).resolve().parents[1]
def upload(client,name,payload,authenticated=True,tenant=1):
boundary='----FreeScanLocalFrameworkRegressionBoundary'
body=(f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="{name}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode()+payload+f'\r\n--{boundary}--\r\n'.encode())
headers={'tenant-id':str(tenant),'Content-Type':'multipart/form-data; boundary='+boundary}
if authenticated:headers['Authorization']='Bearer '+client._token
request=urllib.request.Request(client.base_url+'/admin-api/cmvr/scanner/framework/local-files',data=body,headers=headers,method='POST')
try:
with urllib.request.urlopen(request,timeout=180) as response:result=json.loads(response.read())
except urllib.error.HTTPError as error:result=json.loads(error.read())
return result
def main():
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--large',action='store_true');args=parser.parse_args()
client=Client().login();db=TargetReadOnlyDb(client)
prefix='E2E-LOCAL-FRAME-'+unique_prefix().split('_',2)[-1]
checks=[];uploaded=[]
def check(name,condition):require(condition,name);checks.append(name)
def snapshot():
return {table:db.select('SELECT COUNT(*) n FROM '+table)[0]['n'] for table in ('lab_scanner_command','lab_scanner_framework_transfer','te_task_inst','lab_resource_occupation')}
before=snapshot()
for name,data in [('empty.txt',b''),('wrong.stl',b'not framework')]:
check('reject '+name,upload(client,name,data).get('code')==400)
check('reject anonymous upload',upload(client,'frame.p3',b'123',authenticated=False).get('code')==401)
check('reject another tenant',upload(client,'frame.p3',b'123',tenant=2).get('code') in (400,401,403))
files=[('one.p3',b'local regression fixture only'),('two.asc',b'0 0 0\n1 0 0\n')]
if args.large:files.append(('100m.p3',bytes(100*1024*1024)))
for suffix,payload in files:
name=prefix+'-'+suffix;response=upload(client,name,payload)
check('archive '+suffix,response.get('code')==200)
file=response['data'];uploaded.append(file)
check('canonical receipt '+suffix,file['name']==name and file['bytes']==len(payload) and file['sha256']==hashlib.sha256(payload).hexdigest() and file['downloadUrl']=='/admin-api/cmvr/scanner/files/'+file['fileId'])
req=urllib.request.Request(client.base_url+file['downloadUrl'],headers={'Authorization':'Bearer '+client._token,'tenant-id':'1'})
with urllib.request.urlopen(req,timeout=180) as downloaded:check('download exact bytes '+suffix,downloaded.read()==payload)
if args.large:check('100MiB plus one byte rejected',upload(client,prefix+'-oversized.p3',bytes(100*1024*1024+1)).get('code') in (400,413))
fixture=client.request('POST','/admin-api/lab/master/fixture/create',dict(fixtureCode=prefix,fixtureName=prefix,status='ENABLED'))['data']
def bind(expected,files=uploaded,confirmed=True):
return client.request('POST','/admin-api/lab/master/fixture/framework/import',dict(fixtureId=fixture,expectedVersion=expected,confirmed=confirmed,frameworkUrls=files),expected=None)
def current():return client.request('GET','/admin-api/lab/master/fixture/framework/get',query={'fixtureId':fixture})['data']
check('confirmation required',bind(None,confirmed=False).get('code')==400)
v1=bind(None);check('first fixture import',v1.get('code')==0);v1=v1['data']
saved=current();check('ready and reusable',saved['current']['id']==v1 and len(json.loads(saved['current']['urlsJson']))==len(uploaded))
check('stale page blocked',bind(None).get('code')==400)
bad_sources=[[],['/api/v1/files/'+'a'*32],['http://example.invalid/admin-api/cmvr/scanner/files/'+'a'*32],['/admin-api/cmvr/scanner/files/'+'a'*32],['/admin-api/cmvr/scanner/files/'+f'{i:032x}' for i in range(9)]]
for i,files in enumerate(bad_sources):check('invalid fixture source '+str(i),bind(v1,files).get('code') in (400,503))
check('failed import preserves current',current()['current']['id']==v1)
with ThreadPoolExecutor(max_workers=2) as pool:results=list(pool.map(lambda _:bind(v1),range(2)))
check('concurrent overwrite one winner',sorted(r['code'] for r in results)==[0,400])
saved=current();check('old ready version retained',len(saved['history'])==2 and all(row['status']=='READY' and row.get('instanceId') is None for row in saved['history']) and saved['current']['id']!=v1)
client.request('POST','/admin-api/lab/master/fixture/disable',query={'id':fixture})
check('disabled fixture cannot import',bind(saved['current']['id']).get('code')==400)
check('no hardware commands, tasks or occupation created',snapshot()==before)
# Keep an exact manifest for diagnosis and conservative cleanup, never scan arbitrary files.
manifest=dict(prefix=prefix,fixtureId=fixture,uploaded=uploaded,checks=checks)
(ROOT/'.local/local-framework-http.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2),encoding='utf-8')
from cleanup_verification import cleanup
cleaned=cleanup([prefix],apply=True)
archive=(ROOT/'.local/artifacts/fixture-framework').resolve()
removed=0
for receipt in uploaded:
require(re.fullmatch('[a-f0-9]{32}',receipt['fileId']) and receipt['name'].startswith(prefix+'-'),'archive ownership')
paths=[archive/receipt['fileId'],archive/(receipt['fileId']+'.json')]
require(all(path.resolve().parent==archive and not path.is_symlink() for path in paths),'archive location')
metadata=json.loads(paths[1].read_text(encoding='utf-8'))
require(metadata==receipt and hashlib.sha256(paths[0].read_bytes()).hexdigest()==receipt['sha256'],'archive identity')
for path in paths:path.unlink();removed+=1
check('business test data removed',db.select('SELECT COUNT(*) n FROM lab_fixture WHERE fixture_code=%s',(prefix,))[0]['n']==0 and db.select('SELECT COUNT(*) n FROM lab_fixture_framework WHERE fixture_id=%s',(fixture,))[0]['n']==0)
db.close()
report=dict(passed=True,prefix=prefix,checks=checks,count=len(checks),deviceControlRequests=0,cleanup=cleaned,removedArchiveFiles=removed)
(ROOT/'.local/local-framework-http.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
print(json.dumps(dict(passed=True,count=len(checks),deviceControlRequests=0,cleanup=cleaned['counts'],removedArchiveFiles=removed)))
if __name__=='__main__':main()