am-freescan/scripts/verify_scanner_trial_stop.py

119 lines
9.3 KiB
Python
Raw Normal View History

"""Regression of the actual test-case trial/stop API using ONLY a localhost scanner.
Requires idle development services; restores real dev settings and removes only
the exact tagged verification case/instances/leases after the run.
"""
import argparse
import copy
import datetime as dt
import json
import uuid
from pathlib import Path
from cleanup_verification import cleanup
from verify_cmvr_native import Client,TargetReadOnlyDb,require,response_identifier
from verify_scanner_workflow import Supplier,LocalResources,DevBackend,ScannerVerifier,wait_for,require_idle_scanner
ROOT=Path(__file__).resolve().parents[1]
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--manage-dev',action='store_true',required=True)
parser.add_argument('--skip-build',action='store_true')
parser.add_argument('--allow-unreachable-scanner',action='store_true',help='Only for localhost fixture testing when the physical HTTP service times out')
args=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 prevents trial regression deployment')
require_idle_scanner(client,args.allow_unreachable_scanner)
db.close()
prefix='E2E-TRIAL-'+dt.datetime.now().strftime('%m%d%H%M%S')+'-'+uuid.uuid4().hex[:4]
print('Trial-stop regression prefix: '+prefix,flush=True)
supplier=Supplier();supplier.start();resources=LocalResources(prefix,supplier.port);backend=DevBackend()
verifier=None;instances=[];checks=[];passed=False;cleaned={}
def check(name):checks.append(dict(name=name,passed=True));print('PASS '+name,flush=True)
def held(instance):return verifier.native.db.select('SELECT status FROM lab_resource_occupation WHERE owner_key=%s AND tenant_id=1 AND deleted=0',('NATIVE:'+instance,))
try:
resources.provision()
if args.skip_build:backend.require_current_package()
else:backend.build()
backend.stop_existing();backend.start(supplier,resources)
verifier=ScannerVerifier(prefix,supplier,report_path=ROOT/'.local/scanner-trial-stop-progress.json')
case=verifier.create_scanner_case('trial-stop',sleep_ms=300000)
# Reproduce the real case: initialize -> stop (before any project) -> create.
graph=case['graph'];prepare=copy.deepcopy(next(n for n in graph['nodes'] if n['id']=='stopScan'))
prepare['id']='prepareStop';prepare['properties']['name']='工程前确认停止'
graph['nodes'].insert(2,prepare)
graph['edges']=[dict(id='edge-'+str(i),sourceNodeId=graph['nodes'][i]['id'],targetNodeId=graph['nodes'][i+1]['id']) for i in range(len(graph['nodes'])-1)]
supplier.fail_redundant_stop=True
request=dict(itemId=case['itemId'],flowData=json.dumps(case['graph'],ensure_ascii=False),robotId=resources.robot,
runtimeAssignments=[dict(roleKey='scanner',members=[dict(memberKey='scanner-1',robotId=resources.robot,devices={'scanner':resources.device})])],runParams={'verificationMarker':prefix})
def submit():
instance=response_identifier(verifier.client.native('POST','/flow/executeTrial',request));instances.append(instance)
return instance
def collecting(instance):
wait_for(lambda:supplier.scanning,20,'trial acquisition')
wait_for(lambda:any(row.get('action')=='SLEEP' for row in verifier.native.node_logs(instance)),20,'trial wait node')
require(bool(held(instance)),'Trial did not acquire resource leases');return instance
def start():return collecting(submit())
first=start()
require(supplier.count('/api/v1/scan/stop')==0,'Idle pre-project stop reached the SDK')
records=verifier.native.db.select("SELECT state,remote_task_id,result_json FROM lab_scanner_command WHERE owner_ref=%s AND operation='SCAN_STOP'",('workflow:'+first,))
require(len(records)==1 and records[0]['state']=='SUCCEEDED' and records[0]['remote_task_id'] is None,'Idle stop was not recorded as a local confirmation')
require(json.loads(records[0]['result_json'])['result']['alreadyStopped'] is True,'Idle-stop confirmation evidence is missing')
check('初始化后尚未采集:工程前停止由明确设备状态确认,不调用会超时的厂家PauseSDK,后续工程与采集正常开始')
verifier.client.native('POST','/flow/stop/'+first)
verifier.native.wait_native(first,expected=4);require(not supplier.scanning,'Stop acknowledged without stopping acquisition')
require(not held(first),'Acknowledged trial stop left a resource lease')
verifier.client.native('POST','/flow/stop/'+first);require(not held(first),'Repeated stop restored a lease')
check('用例试运行中终止:确认停采后自动释放工位和设备占用,重复终止不重新占用')
second=start();supplier.failed_operation='/api/v1/scan/stop'
rejected=verifier.client.native('POST','/flow/stop/'+second,expected=None)
require(rejected.get('code') not in (0,200),'Unconfirmed physical stop reported success')
verifier.native.wait_native(second,expected=4)
require(supplier.scanning and held(second) and all(r['status']=='STOP_PENDING' for r in held(second)),'Stop failure did not retain the pending lease')
before=len(supplier.posts)
blocked=verifier.client.native('POST','/flow/executeTrial',request,expected=None)
require(blocked.get('code') not in (0,200) and len(supplier.posts)==before,'Another trial reached the device during an unconfirmed stop')
check('SDK停止失败:终止返回明确错误,保留STOP_PENDING占用,禁止再次试运行发送设备操作')
verifier.client.request('POST','/admin-api/lab/scan-task/clear-occupation',dict(ownerKey='NATIVE:'+second,reason=prefix+' explicit stop confirmation'),expected=(0,))
require(not supplier.scanning and not held(second),'Explicit stop confirmation did not release the original trial')
check('停止失败后通过系统确认停止,成功停稳后仅释放原试运行占用')
third=start();verifier.client.native('POST','/flow/stop/'+third)
require(not supplier.scanning and not held(third),'Re-run could not stop and release')
check('释放后可再次试运行,终止再次完成停采及释放')
supplier.project_delay_seconds=3
projects=supplier.count('/api/v1/projects');fourth=submit()
wait_for(lambda:supplier.project_building,20,'project creation in progress')
verifier.client.native('POST','/flow/pause/'+fourth)
verifier.native.wait_native(fourth,expected=3);require(bool(held(fourth)),'Pause incorrectly released its resources')
verifier.client.native('POST','/flow/resume/'+fourth);collecting(fourth)
require(supplier.count('/api/v1/projects')==projects+1,'Resume recreated an already accepted project')
verifier.client.native('POST','/flow/stop/'+fourth);require(not supplier.scanning and not held(fourth),'Stop after resume did not release')
check('新建工程途中暂停保留占用;恢复复用原工程不重复创建;再终止确认停采并释放')
fifth=submit();wait_for(lambda:supplier.project_building,20,'second project creation in progress')
starts=supplier.count('/api/v1/scan/start')
verifier.client.native('POST','/flow/pause/'+fifth);verifier.native.wait_native(fifth,expected=3)
verifier.client.native('POST','/flow/stop/'+fifth)
require(not held(fifth) and not supplier.scanning,'Terminate after project-phase pause left a lease')
require(supplier.count('/api/v1/scan/start')==starts,'Termination started an unexecuted acquisition')
check('新建工程途中暂停后直接终止:释放占用,不继续执行后续采集节点')
passed=True
finally:
try:
if verifier:
supplier.uncertain=False;supplier.hold_controls=False;supplier.failed_operation=None
for instance in instances:
rows=verifier.native.db.select('SELECT status FROM te_task_inst WHERE id=%s',(instance,))
if rows and str(rows[0]['status']) in ('1','3'):verifier.client.native('POST','/flow/stop/'+instance,expected=None)
if held(instance):verifier.client.request('POST','/admin-api/lab/scan-task/clear-occupation',dict(ownerKey='NATIVE:'+instance,reason=prefix+' cleanup confirmation'),expected=(0,))
cleaned=cleanup([prefix],apply=True);require(not cleanup([prefix])['counts'],'Tagged trial regression data remains')
resources.close()
finally:
backend.stop();supplier.close()
if backend.changed:backend.start()
report=dict(prefix=prefix,passed=passed,checks=checks,cleanup=cleaned,physicalScannerControlRequests=0)
(ROOT/'.local/scanner-trial-stop-regression-20261026.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print(json.dumps(dict(passed=passed,checks=len(checks),physicalScannerControlRequests=0)),flush=True)
if __name__=='__main__':main()