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

128 lines
12 KiB
Python
Raw Permalink 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.

"""Opt-in API 1.3 workflow regression using ONLY a localhost scanner fixture.
Requires idle development services. Restores real dev settings and cleans exactly
this verification batch. Does not start or configure physical scanning hardware.
"""
import argparse
import datetime as dt
import json
from pathlib import Path
import urllib.request
import urllib.parse
import uuid
from cleanup_verification import cleanup
from verify_cmvr_native import Client,TargetReadOnlyDb,require
from verify_scanner_workflow import Supplier,LocalResources,DevBackend,ScannerVerifier,scanner_flow,wait_for
from verify_scanner_contract import run as verify_contract
ROOT=Path(__file__).resolve().parents[1]
def framework_graph(steps):
template=scanner_flow(200);start=template['nodes'][0];end=template['nodes'][-1];nodes=[start]
for index,(action,body) in enumerate(steps):
properties=dict(name=action,action=action,inputParams=[],nodeParams=[])
if action=='SLEEP':properties['nodeParams']=[dict(name='delayMs',type='input',input=200)]
else:properties.update(nodeType='EDGE',executionTarget=dict(roleKey='scanner',deviceSlotKey='scanner'),
nodeParams=[dict(name='requestJson',type='input',input=json.dumps(body)),dict(name='timeoutMs',type='input',input=120000)])
nodes.append(dict(id='step-'+str(index),type='sleep' if action=='SLEEP' else 'serviceNode',properties=properties,x=100+250*index,y=180))
nodes.append(end)
return dict(schemaVersion=2,nodes=nodes,edges=[dict(id='edge-'+str(i),sourceNodeId=nodes[i]['id'],targetNodeId=nodes[i+1]['id']) for i in range(len(nodes)-1)])
def main():
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--manage-dev',action='store_true',required=True)
parser.add_argument('--allow-unreachable-scanner',action='store_true',help='Allow a read-only scanner transport timeout ONLY when no platform work, commands or leases exist; all controls use the localhost fixture')
parser.add_argument('--preserve-stop-pending-leases',action='store_true',help='Keep exact STOP_PENDING leases of failed or terminated user trials; tests use a new independent fixture robot and device')
options=parser.parse_args()
client=Client().login();db=TargetReadOnlyDb(client)
for sql in ["SELECT COUNT(*) n FROM lab_execution WHERE status IN ('QUEUED','RUNNING','PAUSED') AND deleted=0","SELECT COUNT(*) n FROM te_task_inst WHERE status IN ('1','3')",'SELECT COUNT(*) n FROM lab_scanner_command WHERE active_endpoint IS NOT NULL']:
require(db.select(sql)[0]['n']==0,'Active work or leases prevent framework regression deployment')
lease_sql='SELECT owner_key,resource_type,resource_id,status FROM lab_resource_occupation WHERE deleted=0 ORDER BY owner_key,resource_type,resource_id'
original_leases=db.select(lease_sql)
for lease in original_leases:
require(options.preserve_stop_pending_leases and lease['status']=='STOP_PENDING' and lease['owner_key'].startswith('NATIVE:'),'Only explicitly preserved stopped-trial leases may coexist with isolated fixture testing')
rows=db.select('SELECT status FROM te_task_inst WHERE id=%s',(lease['owner_key'].removeprefix('NATIVE:'),))
require(len(rows)==1 and str(rows[0]['status']) in ('2','4'),'Preserved user trial has not ended')
if original_leases:print('Preserving '+str(len(original_leases))+' exact STOP_PENDING user leases; fixture resources are independent',flush=True)
physical_response=client.native('GET','/scanner/status',expected=None)
unreachable=physical_response.get('code')==504 and physical_response.get('scannerCode')=='transport_uncertain'
if unreachable:
require(options.allow_unreachable_scanner,'Physical scanner status is unreachable; use the explicit flag for localhost-only verification with no platform work')
print('Physical scanner status unavailable; all controls remain restricted to the localhost fixture',flush=True)
else:
require(physical_response.get('code')==200 and all(physical_response.get('data',{}).get(k) is False for k in ['scanning','busy','stateUncertain','restartRequired']),'Physical scanner is not confirmed idle')
db.close()
prefix='E2E-FRAME-'+dt.datetime.now().strftime('%m%d%H%M%S')+'-'+uuid.uuid4().hex[:4]
print('Framework verification prefix: '+prefix,flush=True)
supplier=Supplier();supplier.start();resources=LocalResources(prefix,supplier.port,preserved_leases=original_leases if options.preserve_stop_pending_leases else None);backend=DevBackend();verifier=None;passed=False;cleaned={}
try:
resources.provision();backend.stop_existing();backend.build();backend.start(supplier,resources)
verifier=ScannerVerifier(prefix,supplier,report_path=ROOT/'.local/scanner-framework-progress.json')
require(verify_contract(),'Documented API contract mismatch');verifier.check('41路由完整覆盖、30个JSON示例及未知字段拒绝通过,不把同步上传当异步命令')
def upload(name,payload):
request=urllib.request.Request(verifier.client.base_url+'/admin-api/cmvr/scanner/framework/files',data=payload,
headers={'tenant-id':'1','Authorization':'Bearer '+verifier.client._token,'Content-Type':'application/octet-stream','X-File-Name':urllib.parse.quote(name,safe='')})
with urllib.request.urlopen(request,timeout=15) as response:result=json.load(response)
require(result['code']==200,'Synchronous framework upload rejected');return result['data']
files=[upload('框架+ A.p3',b'LOCAL FRAME A\n'),upload('Frame-B.asc',b'LOCAL FRAME B\n')]
require(all('taskId' not in item for item in files) and supplier.framework_uploads[files[0]['fileId']]['bytes']==b'LOCAL FRAME A\n','Upload bytes/receipt differ')
require(not supplier.project and not supplier.scanning and supplier.count('/api/v1/framework/import')==0,'Upload operated the SDK')
verifier.check('真实HTTP上传原始字节和中文文件名,201回执转平台结果,无SDK导入或任务轮询')
def run_case(suffix,steps,expected='SUCCEEDED'):
case=verifier.create_case(suffix);case['graph']=framework_graph(steps)
version=verifier.native.publish(case['itemId'],case['graph'],'LOCALHOST API13 REGRESSION')
case.update(versionId=version['id'],versionNo=version['versionNo'])
task=verifier.import_task(suffix,case['caseId'],1);detail=verifier.prepare(task,case['caseId'])
execution,_=verifier.start(task,detail['units'][0]);verifier.wait_execution(execution,status=expected)
if expected=='SUCCEEDED':verifier.assert_occupied(task,False)
return task,execution
common=[('SCANNER_INITIALIZE',{}),('SCANNER_STOP',{}),('SCANNER_CREATE_PROJECT',{'mode':'trak'})]
task,photo=run_case('photogrammetry',common+[
('SCANNER_SCAN_TYPE',{'scanType':'photogrammetry','device':'tracker','confirm':True}),
('SCANNER_PREVIEW_START',{}),('SCANNER_START',{}),('SLEEP',{}),('SCANNER_STOP',{}),
('SCANNER_FRAMEWORK_OPTIMIZE',{}),('SCANNER_EXPORT',{'formats':['P3']}),('SCANNER_PREVIEW_STOP',{})])
assets=wait_for(lambda:verifier.view(photo,'/assets'),10,'P3 export asset');require(len(assets)==1 and assets[0]['name'].endswith('.p3'),'P3 result not associated with execution')
_,payload=verifier.binary('/asset/'+assets[0]['fileId'],photo);require(payload==b'FRAMEWORK FIXTURE\n','P3 download bytes differ')
require(supplier.count('/api/v1/mesh')==0 and supplier.framework_optimized,'Photogrammetry tried to generate a surface mesh')
verifier.check('摄影测量完整业务流程:新建工程→选择跟踪仪→采集→暂停→优化→P3导出及按执行归档下载,无表面网格节点')
before=len(supplier.posts);original_project=supplier.project
guard_task,guard_execution=run_case('existing-data-guard',[
('SCANNER_SCAN_TYPE',dict(scanType='mesh',device='scanner',confirm=True))],expected='FAILED')
instance=verifier.binding(guard_execution)['cmvr_inst_id']
commands=verifier.native.db.select("SELECT state,result_json FROM lab_scanner_command WHERE owner_ref=%s AND operation='SCAN_TYPE'",('workflow:'+instance,))
require(len(commands)==1 and commands[0]['state']=='FAILED' and json.loads(commands[0]['result_json'])['error']['code']=='project_data_present','SDK project-data error was not retained')
require(len(supplier.posts)==before+1 and supplier.project==original_project,'Failed switch was retried or replaced existing data')
verifier.wait_stop_confirmation(guard_task)
verifier.api('POST','/lab/scan-task/cancel',dict(taskId=guard_task,reason=prefix+' completed failed-guard verification'))
verifier.assert_occupied(guard_task,False)
verifier.check('已有摄影测量数据时拒绝切换设备,保留project_data_present及原工程;失败不自动重试,确认停止后释放本次失败测试占用')
_,imported=run_case('framework-import',common+[
('SCANNER_SCAN_TYPE',{'scanType':'mesh','device':'scanner','confirm':True}),
('SCANNER_FRAMEWORK_IMPORT',{'fileIds':[item['fileId'] for item in files],'confirm':True}),
('SCANNER_PREVIEW_START',{}),('SCANNER_START',{}),('SLEEP',{}),('SCANNER_STOP',{}),
('SCANNER_MESH',{}),('SCANNER_MESH_CONFIRM',{}),('SCANNER_EXPORT',{'formats':['PLY','STL']}),('SCANNER_PREVIEW_STOP',{})])
imported_assets=verifier.view(imported,'/assets');require({item['name'].rsplit('.',1)[-1] for item in imported_assets}=={'ply','stl'},'Import workflow did not export both models')
require(supplier.framework_imported and supplier.framework_file_count==2,'Frameworks were not imported into the new project')
verifier.check('框架导入完整业务流程:上传的2个编号→新Trak表面工程→导入→采集→PLY/STL成果,资源释放')
_,old_payload=verifier.binary('/asset/'+assets[0]['fileId'],photo);require(old_payload==payload,'Old P3 result changed after creating another project')
verifier.check('切换至框架导入工程后,原摄影测量执行的P3归档仍可下载,历史成果保留')
passed=True
finally:
try:
if verifier:
supplier.uncertain=False;supplier.hold_controls=False;supplier.failed_operation=None
for task in verifier.active_tasks:
detail=verifier.task(task)
if detail['task']['status'] not in ('COMPLETED','CANCELLED'):verifier.api('POST','/lab/scan-task/cancel',dict(taskId=task,reason=prefix+' cleanup'))
if verifier.task(task)['config'].get('stopPending'):verifier.api('POST','/lab/scan-task/confirm-stop',dict(taskId=task,reason=prefix+' cleanup stop'))
cleaned=cleanup([prefix],apply=True);require(not cleanup([prefix])['counts'],'Tagged framework regression data remains')
require(verifier.native.db.select(lease_sql)==original_leases,'Original user pending-stop leases changed')
resources.close()
finally:
backend.stop();supplier.close()
if backend.changed:backend.start()
report=dict(prefix=prefix,passed=passed,checks=verifier.report['checks'] if verifier else [],cleanup=cleaned,physicalScannerControlRequests=0,physicalStatusBefore='unreachable' if unreachable else 'idle',originalPendingStopLeasesPreserved=len(original_leases))
(ROOT/'.local/scanner-framework-regression-20261027.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print(json.dumps(dict(passed=passed,checks=len(report['checks']),physicalScannerControlRequests=0)),flush=True)
if __name__=='__main__':main()