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

230 lines
19 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.

"""Real exported bytes, localhost-only controls, actual platform trial engine.
Temporarily runs the dev backend against a disposable localhost supplier and
fixture station. Restores its original scanner config, cleans the exact batch.
"""
import argparse
import copy
import datetime as dt
import hashlib
import json
from pathlib import Path
import time
import urllib.request
import uuid
from verify_cmvr_native import Client, TargetReadOnlyDb, require, response_identifier
from verify_scanner_workflow import Supplier, LocalResources, DevBackend
from verify_real_framework_url import graph
from cleanup_verification import cleanup
ROOT=Path(__file__).resolve().parents[1]
REPORT=ROOT/'.local/framework-url-offline-20261027.json'
NOTE='本机隔离框架URL回归;使用真实导出的P3字节,所有控制只到本机模拟服务,无真实设备操作'
def loop_graph(first_task,second_task,prefix):
flow=graph(first_task,prefix)
start,end=flow['nodes'][0],flow['nodes'][-1]
children=flow['nodes'][1:-1]
current=dict(id='current',type='currentLoop',properties=dict(name='获取当前循环对象',action='GET_CURRENT_OBJECT',nodeParams=[],outputParams=[dict(name='object',type='string')]))
source=next(n for n in children if n['id']=='source')
source['properties']['nodeParams'][0]=dict(name='taskId',type='quote',quoteType='output',quote=['current','output','object'])
children=[current]+children
loop=dict(id='loop',type='loop',children=[n['id'] for n in children],properties=dict(name='逐轮引用导出结果',action='START_LOOP',nodeParams=[dict(name='loopNum',type='input',input=[first_task,second_task])]))
flow['nodes']=[start,loop,*children,end]
pairs=[('start','loop'),('loop','end')]+[(children[i]['id'],children[i+1]['id']) for i in range(len(children)-1)]
flow['edges']=[dict(id='edge-'+str(i),sourceNodeId=a,targetNodeId=b) for i,(a,b) in enumerate(pairs)]
return flow
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--manage-dev',action='store_true',required=True)
parser.add_argument('--component-audit',action='store_true')
args=parser.parse_args()
client=Client().login();db=TargetReadOnlyDb(client)
require(not db.select("SELECT id FROM te_task_inst WHERE status IN ('1','3')"),'存在运行中工作流')
require(not db.select("SELECT id FROM lab_execution WHERE status IN ('QUEUED','RUNNING','PAUSED') AND deleted=0"),'存在运行中业务执行')
require(not db.select('SELECT owner_key FROM lab_resource_occupation WHERE deleted=0'),'存在设备占用')
require(db.select('SELECT COUNT(*) n FROM lab_scanner_command WHERE active_endpoint IS NOT NULL')[0]['n']==0,'存在未确认命令')
original_config=client.native('GET','/scanner/configuration')['data']
original_status=client.native('GET','/scanner/status')['data']
require(all(original_status.get(k) is False for k in ('scanning','busy','stateUncertain','restartRequired')),'真实设备不空闲')
private_hash=hashlib.sha256((ROOT/'.local/scanner-private.yaml').read_bytes()).hexdigest()
chosen=None
for row in db.select("SELECT command_key,result_json FROM lab_scanner_command WHERE operation='EXPORT' AND state='SUCCEEDED' ORDER BY updated_at DESC LIMIT 40"):
value=json.loads(row['result_json'])
files=[f for f in value.get('result',{}).get('files',[]) if f.get('name','').lower().endswith('.p3')]
if files: chosen=(row,value,files[0]);break
require(chosen,'需要已有真实P3数据')
source_command,source_result,source=chosen
source_url=client.base_url+'/admin-api/cmvr/scanner/files/'+source['fileId']
def read_real_file(c):
req=urllib.request.Request(source_url,headers={'tenant-id':'1','Authorization':'Bearer '+c._token})
with urllib.request.urlopen(req,timeout=20) as r: return r.read(16*1024*1024+1)
payload=read_real_file(client)
require(0<len(payload)<=16*1024*1024 and len(payload)==source['bytes'],'真实P3文件内容或长度无效')
original_commands=db.select('SELECT COUNT(*) n FROM lab_scanner_command')[0]['n']
prefix='E2E-URL-OFF-'+dt.datetime.now(dt.timezone(dt.timedelta(hours=8))).strftime('%m%d%H%M%S')+'-'+uuid.uuid4().hex[:4]
report=dict(prefix=prefix,passed=False,sourceFile=source,sha256=hashlib.sha256(payload).hexdigest(),checks=[],trials=[],physicalScannerControlRequests=0)
def save():REPORT.write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
def check(name,condition=True):
require(condition,name);report['checks'].append(name);save();print('PASS '+name,flush=True)
save();db.close()
supplier=Supplier();supplier.start()
resources=LocalResources(prefix,supplier.port)
backend=DevBackend(ROOT/'am-backend/yudao-server/target-verification/yudao-server.jar')
# Reuse real bytes and realistic export metadata, never query or change real SDK state.
file_id=uuid.uuid4().hex;task_id=uuid.uuid4().hex
file=dict(source,fileId=file_id,downloadUrl='/api/v1/files/'+file_id)
supplier.files[file_id]=payload;supplier.file_names[file_id]=file['name']
supplier.tasks[task_id]=dict(taskId=task_id,state='succeeded',result=dict(files=[file,
dict(fileId=uuid.uuid4().hex,name='unrelated.stl',bytes=99999999,downloadUrl='/api/v1/files/'+'f'*32)]))
second_file_id=uuid.uuid4().hex;second_task_id=uuid.uuid4().hex
second_file=dict(file,fileId=second_file_id,downloadUrl='/api/v1/files/'+second_file_id)
supplier.files[second_file_id]=payload;supplier.file_names[second_file_id]=file['name']
supplier.tasks[second_task_id]=dict(taskId=second_task_id,state='succeeded',result=dict(files=[second_file]))
client=None;db=None
try:
resources.provision();backend.stop_existing();backend.start(supplier,resources)
client=Client().login();db=TargetReadOnlyDb(client)
configuration=client.native('GET','/scanner/configuration')['data']
require(configuration['host']=='127.0.0.1' and configuration['port']==supplier.port and configuration['robotId']==resources.robot,'模拟服务绑定未生效')
check('真实P3内容已加载到独立本机模拟服务,控制不会请求真实设备')
def trial(suffix,mode='frameworkFiles',expected='0',literal=None,confirmed=True,in_loop=False,custom_flow=None):
case_id=uuid.uuid4().hex
client.native('POST','/aima/testcase',dict(id=case_id,caseCode=(prefix+'-'+suffix)[:49],caseName=prefix+' '+suffix,
caseCategory='功能测试',enabled='0',priority='2',testDescription=NOTE,precondition='仅限本机模拟扫描服务',
testSteps='引用真实P3字节→新工程→自动登记导入→读取状态',expectedResult='模拟导入成功且资源释放',remark=NOTE))
item=client.native('GET','/aima/testcase/'+case_id)['data']['detectItemId']
flow=custom_flow or (loop_graph(task_id,second_task_id,prefix+'-'+suffix) if in_loop else graph(task_id,prefix+'-'+suffix))
if not custom_flow:
params=next(n for n in flow['nodes'] if n['id']=='import')['properties']['nodeParams']
params[0]['input']=json.dumps({'confirm':confirmed})
if literal is not None:params[1]=dict(name='frameworkUrls',type='input',input=literal)
else:params[1]['quote']=['source','output','result','files'] if mode=='legacy' else ['source','output',mode]
info=client.native('GET','/test/detect/'+item)['data']
draft=client.native('PUT','/flow/draft',dict(id=item,flowData=json.dumps(flow,ensure_ascii=False),config={},draftRevision=info.get('draftRevision',0)),expected=None)
entry=dict(suffix=suffix,caseId=case_id,itemId=item,draftCode=draft.get('code'));report['trials'].append(entry);save()
body=dict(itemId=item,flowData=json.dumps(flow,ensure_ascii=False),robotId=resources.robot,
runtimeAssignments=[dict(roleKey='scanner',members=[dict(memberKey='scanner-1',robotId=resources.robot,devices={'scanner':resources.device})])],
runParams=dict(brightness=11,markerIds='[9007199254740993,18446744073709551615]') if custom_flow else {})
if not confirmed:
response=draft if draft.get('code')!=200 else client.native('POST','/flow/executeTrial',body,expected=None)
entry['rejectionCode']=response.get('code');entry['rejectionMessage']=response.get('msg')
if response.get('code')==200:entry['instanceId']=response_identifier(response)
save();require(response.get('code')!=200,'未确认的导入竟允许执行');return entry
require(draft.get('code')==200,'草稿保存失败:'+str(draft.get('msg')))
response=client.native('POST','/flow/executeTrial',body)
inst=response_identifier(response);entry['instanceId']=inst;save()
deadline=time.monotonic()+60
while time.monotonic()<deadline:
row=db.select('SELECT status FROM te_task_inst WHERE id=%s',(inst,))[0]
if str(row['status']) in ('0','2','4'):break
time.sleep(.2)
entry['status']=str(row['status'])
logs=client.native('GET','/test/inst/log/detail',query=dict(instId=inst,pageNum=1,pageSize=100))['rows']
entry['logs']=logs;save()
require(entry['status']==expected,'试运行状态不符:'+suffix+' '+entry['status'])
deadline=time.monotonic()+15
while time.monotonic()<deadline:
if not db.select('SELECT owner_key FROM lab_resource_occupation WHERE deleted=0 AND owner_key=%s',('NATIVE:'+inst,)):break
time.sleep(.2)
require(not db.select('SELECT owner_key FROM lab_resource_occupation WHERE deleted=0 AND owner_key=%s',('NATIVE:'+inst,)),'试运行结束后仍占用设备')
if expected=='0' and not custom_flow:require(supplier.framework_imported and supplier.framework_file_count==1,'设备没有确认导入一个框架')
return entry
check('缺少确认会在执行前提前阻止',trial('no-confirm',confirmed=False)['rejectionCode']!=200)
trial('upstream')
check('完整原生试运行:上游导出结果→新工程→URL自动登记→导入任务成功→资源释放',supplier.count('/api/v1/framework/files')==1 and supplier.count('/api/v1/framework/import')==1)
uploaded=list(supplier.framework_uploads.values())
check('实际登记字节与真实P3的SHA256完全相同',len(uploaded)==1 and uploaded[0]['bytes']==payload)
check('混合成果中的大型STL在下载前被筛除','/api/v1/files/'+'f'*32 not in supplier.gets)
trial('again')
check('第二次连续执行复用登记,仅再次导入,未重复登记文件',supplier.count('/api/v1/framework/files')==1 and supplier.count('/api/v1/framework/import')==2)
trial('legacy',mode='legacy')
check('旧导出节点的result.files引用可执行',supplier.count('/api/v1/framework/files')==1)
trial('urls',mode='frameworkUrls')
check('仅URL数组引用能从下载响应读取真实文件名并执行',supplier.count('/api/v1/framework/files')==1)
looped=trial('loop',in_loop=True)
loop_imports=[json.loads(r['paramsOut'])['frameworkTransfer'][0]['sourceFileId'] for r in sorted(looped['logs'],key=lambda r:int(r['id'])) if r.get('action')=='SCANNER_FRAMEWORK_IMPORT' and r.get('status')=='SUCCESS']
check('实际循环两轮分别导入本轮导出的文件,未复用上一轮变量',loop_imports==[file_id,second_file_id])
before=supplier.count('/api/v1/framework/import')
bad=trial('bad-origin',literal='http://invalid.example/api/v1/files/'+file_id,expected='2')
check('外部URL拒绝且失败后释放设备',supplier.count('/api/v1/framework/import')==before and 'invalid_framework_reference' in json.dumps(bad['logs']))
missing=trial('missing-file',literal='/api/v1/files/'+'e'*32,expected='2')
check('失效URL保留明确错误并释放设备,未提交错误导入',supplier.count('/api/v1/framework/import')==before and any('framework_source_unavailable' in str(r.get('message','')) and '重新导出' in str(r.get('message','')) for r in missing['logs']))
if args.component_audit:
def component_flow(steps):
base=graph(task_id,prefix);start,end=base['nodes'][0],base['nodes'][-1];nodes=[start]
start['properties']['inputParams']=[dict(name='brightness',type='number',input=11),dict(name='markerIds',type='string',input='[9007199254740993,18446744073709551615]')]
for identifier,action,body,bindings in steps:
params=[dict(name='requestJson',type='input',input=json.dumps(body)),dict(name='timeoutMs',type='input',input=120000)]
if bindings:params.append(dict(name='requestFields',type='input',input={},children=[dict(name=field,type='quote',quoteType=path[1],quote=path) for field,path in bindings.items()]))
if action=='SCANNER_STATUS' or action=='SCANNER_SCENE':params=[dict(name='timeoutMs',type='input',input=120000)]
nodes.append(dict(id=identifier,type='serviceNode',properties=dict(name=identifier,action=action,nodeType='EDGE',executionTarget=dict(roleKey='scanner',deviceSlotKey='scanner'),nodeParams=params)))
nodes.append(end)
return dict(schemaVersion=2,nodes=nodes,edges=[dict(id='component-edge-'+str(i),sourceNodeId=nodes[i]['id'],targetNodeId=nodes[i+1]['id']) for i in range(len(nodes)-1)])
links=component_flow([
('new-project','SCANNER_CREATE_PROJECT',dict(mode='trak'),{}),
('scene','SCANNER_SCENE',{},{}),
('edit','SCANNER_EDIT',dict(projectUuid='',markerIds=[],confirm=True),dict(projectUuid=['scene','output','projectUuid'],markerIds=['start','input','markerIds'])),
('parameters','SCANNER_PARAMETERS',dict(brightness=8,pointDistance=0.3),dict(brightness=['start','input','brightness'])),
('reuse-actual-input','SCANNER_PARAMETERS',{},{}),
('status-before','SCANNER_STATUS',{},{}),
('disconnect','SCANNER_DISCONNECT',dict(confirm=True,discardProject=True),dict(expectedProjectId=['status-before','output','projectId'],expectedSessionId=['status-before','output','sessionId'])),
('offline-status','SCANNER_STATUS',{},{}),
('reconnect','SCANNER_RECONNECT',dict(confirm=True,discardProject=False,deviceType=3),dict(expectedProjectId=['offline-status','output','projectId'],expectedSessionId=['offline-status','output','sessionId'])),
('status-after','SCANNER_STATUS',{},{}),
])
reused=next(n for n in links['nodes'] if n['id']=='reuse-actual-input')
reused['properties']['nodeParams'][0]=dict(name='requestJson',type='quote',quoteType='input',quote=['parameters','input','requestJson'])
binding_trial=trial('field-links',custom_flow=links)
edit=next(p['body'] for p in reversed(supplier.posts) if p['path']=='/api/v1/edit')
require(edit['markerIds']==[9007199254740993,18446744073709551615],'原始编号精度丢失')
param=next(p['body'] for p in reversed(supplier.posts) if p['path']=='/api/v1/parameters')
check('场景UUID、原始大整数编号、扫描参数与断开/重连会话字段可直接引用,无需脚本拼JSON',param['brightness']==11 and param['pointDistance']==0.3)
actual=[p['body'] for p in supplier.posts if p['path']=='/api/v1/parameters'][-2:]
check('引用普通上游节点的输入时使用已合并的实际请求,不回退静态brightness=8',len(actual)==2 and actual[0]==actual[1] and actual[1]['brightness']==11)
require(any(n['nodeId']=='offline-status' and n['status']=='SUCCESS' for n in binding_trial['logs']),'设备断开后状态组件无法运行')
check('扫描头断开后仍能读取状态并执行重连,采集状态没有被伪造')
resources.stop.set();resources.thread.join(5)
supplier.device_online=False;supplier.initialized=False
with resources.store.cursor() as cursor:
cursor.execute("UPDATE iot_device SET online_status='0' WHERE robot_id=%s AND device_id=%s AND create_by=%s",(resources.robot,resources.device,prefix))
resources.store.connection.commit()
trial('bootstrap-connect',custom_flow=component_flow([('read-offline','SCANNER_STATUS',{},{}),('connect','SCANNER_INITIALIZE',dict(deviceType=3),{}),('read-online','SCANNER_STATUS',{}, {})]))
check('从扫描头未连接状态启动原生试运行,可先诊断再连接设备,无前置在线死锁',supplier.device_online and supplier.initialized)
report['passed']=True
except Exception as error:
report['error']=str(error);raise
finally:
try:
if client and db:
for entry in report['trials']:
inst=entry.get('instanceId')
if not inst:continue
rows=db.select('SELECT status FROM te_task_inst WHERE id=%s',(inst,))
if rows and str(rows[0]['status']) in ('1','3'):client.native('POST','/flow/stop/'+inst,expected=None)
require(not db.select('SELECT owner_key FROM lab_resource_occupation WHERE deleted=0 AND robot_id=%s',(resources.robot,)),'本轮设备仍被占用,停止清理')
report['cleanup']=cleanup([prefix],apply=True)
require(not cleanup([prefix])['counts'],'本轮测试数据未清理完')
resources.close()
finally:
if db:db.close()
backend.stop();supplier.close()
if backend.changed:backend.start()
restored=Client().login();restored_db=TargetReadOnlyDb(restored)
try:
report['normalDevRestored']=restored.native('GET','/scanner/configuration')['data']==original_config
report['privateConfigurationUnchanged']=hashlib.sha256((ROOT/'.local/scanner-private.yaml').read_bytes()).hexdigest()==private_hash
report['realSourceUnchanged']=hashlib.sha256(read_real_file(restored)).hexdigest()==report['sha256']
report['realControlJournalUnchanged']=restored_db.select('SELECT COUNT(*) n FROM lab_scanner_command')[0]['n']==original_commands
require(all(report.get(k) for k in ('normalDevRestored','privateConfigurationUnchanged','realSourceUnchanged','realControlJournalUnchanged')),'还原配置或真实数据核对失败')
finally:restored_db.close();save()
print(json.dumps({k:report[k] for k in ('passed','prefix','checks','normalDevRestored','realSourceUnchanged')},ensure_ascii=True),flush=True)
if __name__=='__main__':main()