am-freescan/scripts/verify_import_template_v3.py

68 lines
7.3 KiB
Python
Raw Normal View History

"""Verify actual template download and no-workflow task imports. Never dispatches execution."""
from pathlib import Path
import csv,io,json,sys,datetime,uuid,urllib.request,zipfile,xml.etree.ElementTree as ET
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'scripts'))
from verify_cmvr_native import Client,TargetReadOnlyDb,NativeVerifier
from cleanup_verification import cleanup
def run():
c=Client().login();db=TargetReadOnlyDb(c)
prefix='E2E-IMPORT-V3-'+datetime.datetime.now().strftime('%Y%m%d%H%M%S')+'-'+uuid.uuid4().hex[:4]
checks=[];base='/admin-api/lab/task/import';batches=[]
def check(name,ok):
if not ok:raise AssertionError(name)
checks.append(name)
leases=list(db.select('SELECT owner_key,resource_key,status FROM lab_resource_occupation WHERE deleted=0 ORDER BY resource_key'))
before={table:db.select('SELECT COUNT(*) n FROM '+table)[0]['n'] for table in ['lab_test_task','lab_execution','lab_sample','lab_task_import_batch','lab_task_sample_unit']}
def upload(rows,version='v3.0'):
content=io.StringIO(newline='');writer=csv.DictWriter(content,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)
boundary='----Freescan'+uuid.uuid4().hex;filename=prefix+'-'+uuid.uuid4().hex[:6]+'.csv'
raw=(f'--{boundary}\r\nContent-Disposition: form-data; name="templateVersion"\r\n\r\n{version}\r\n--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="{filename}"\r\nContent-Type: text/csv\r\n\r\n').encode()+content.getvalue().encode('utf-8-sig')+f'\r\n--{boundary}--\r\n'.encode()
request=urllib.request.Request(c.base_url+base+'/upload',data=raw,headers={'tenant-id':'1','Authorization':'Bearer '+c._token,'Content-Type':'multipart/form-data; boundary='+boundary},method='POST')
with urllib.request.urlopen(request,timeout=30) as response:result=json.load(response)
check('upload '+version,result.get('code')==0);batch=result['data'];batches.append(batch['id']);return batch
def rows(batch):return c.request('GET',base+'/'+str(batch['id'])+'/rows/page',query={'pageNo':1,'pageSize':20})['data']['list']
def commit(batch):return c.request('POST',base+'/'+str(batch['id'])+'/commit',body={'importValidOnly':False})['data']
def task_id(batch):return rows(batch)[0]['generatedTaskId']
def state(task):return c.request('GET','/admin-api/lab/scan-task/get',query={'taskId':task})['data']
try:
request=urllib.request.Request(c.base_url+base+'/template/current',headers={'tenant-id':'1','Authorization':'Bearer '+c._token})
with urllib.request.urlopen(request,timeout=30) as response:
payload=response.read();check('download advertises v3 xlsx', 'v3.0.xlsx' in response.headers.get('Content-Disposition',''))
(ROOT/'.local/import-template-v3.xlsx').write_bytes(payload)
ns={'x':'http://schemas.openxmlformats.org/spreadsheetml/2006/main'}
with zipfile.ZipFile(io.BytesIO(payload)) as book:
strings=[''.join(si.itertext()) for si in ET.fromstring(book.read('xl/sharedStrings.xml')).findall('x:si',ns)]
sheet=ET.fromstring(book.read('xl/worksheets/sheet1.xml'));cells=sheet.findall('x:sheetData/x:row',ns)[0].findall('x:c',ns)
headers=[strings[int(cell.find('x:v',ns).text)] if cell.get('t')=='s' else ''.join(cell.itertext()) for cell in cells]
check('download preserves external fields and removes workflow input',all(x in headers for x in ['任务名称','样件数量','外部任务编号','样品名称','项目名称','车型/产品','零件号','申请人','检测要求']) and '方法号' not in headers and '扫描方案' not in headers)
styles=ET.fromstring(book.read('xl/styles.xml'));fonts=styles.find('x:fonts',ns);formats=styles.find('x:cellXfs',ns)
for required in ['外部任务编号','任务名称','样品编号','样件数量']:
cell=cells[headers.index(required)];font=fonts[int(formats[int(cell.get('s','0'))].get('fontId','0'))];check('required header red '+required,font.find('x:color',ns).get('indexed')=='10')
row={'外部任务编号':prefix+'-NEW','任务名称':'批量导入无方案验证','样品编号':prefix+'-S','样品名称':'批量导入样品','样件数量':'3'}
batch=upload([row]);check('new template needs no method or optional dates',batch['validRows']==1 and batch['errorRows']==0)
data=rows(batch)[0]['normalizedData'];check('defaults supplied by system',data['testType']=='DIMENSION_SCAN' and data['priority']=='NORMAL' and not data.get('testCaseId'))
check('commit creates one task',commit(batch)['generatedCount']==1);task=task_id(batch);detail=state(task)
check('three separate units without frozen workflow',len(detail['units'])==3 and not detail['config'].get('selectedTestCaseId') and not detail['config'].get('versionId'))
check('repeated commit is idempotent',commit(batch)['generatedCount']==0)
resized=upload([{**row,'样件数量':'2'}]);check('duplicate registration identifies draft',resized['duplicateRows']==1)
check('draft can be updated without a method',commit(resized)['updatedDraftCount']==1 and len(state(task)['units'])==2)
legacy=NativeVerifier(c,prefix=prefix).create_published_case('legacy',1)
old={'外部任务编号':prefix+'-OLD','试验名称':'旧模板兼容','样品编号':prefix+'-S','样品数量':'1','方法号':legacy['caseId'],'备注':prefix}
old_batch=upload([old],'v2.0');check('legacy batch version retained',old_batch['templateVersion']=='v2.0' and old_batch['errorRows']==0)
commit(old_batch);old_task=task_id(old_batch);original=state(old_task)['config'];check('legacy explicit published case retained',original['selectedTestCaseId']==legacy['caseId'])
old_new={'外部任务编号':old['外部任务编号'],'任务名称':'更新旧草稿登记信息','样品编号':prefix+'-S','样件数量':'2'}
update=upload([old_new]);check('v3 updates existing configured draft',commit(update)['updatedDraftCount']==1)
saved=state(old_task)['config'];check('configured case and pinned release preserved',saved['selectedTestCaseId']==legacy['caseId'] and saved['versionId']==original['versionId'])
invalid=upload([{**row,'外部任务编号':prefix+'-BAD','样件数量':'0'}]);check('invalid quantity rejected',invalid['errorRows']==1)
rejected=c.request('POST',base+'/'+str(invalid['id'])+'/commit',body={'importValidOnly':False},expected=None);check('invalid batch cannot commit',rejected.get('code') not in (0,200))
check('no device occupation',leases==list(db.select('SELECT owner_key,resource_key,status FROM lab_resource_occupation WHERE deleted=0 ORDER BY resource_key')))
result=cleanup([prefix],apply=True)
check('temporary batch rows removed',not db.select('SELECT id FROM lab_task_import_batch WHERE id IN ('+','.join(['%s']*len(batches))+')',tuple(batches)))
check('customer baseline counts preserved',all(db.select('SELECT COUNT(*) n FROM '+table)[0]['n']==count for table,count in before.items()))
report={'success':True,'prefix':prefix,'passed':len(checks),'checks':checks,'headers':headers,'deviceCommands':0,'templateFile':'.local/import-template-v3.xlsx','cleanup':result}
(ROOT/'.local/import-template-v3-http.json').write_text(json.dumps(report,ensure_ascii=False,indent=2,default=str),encoding='utf-8');print(json.dumps({'passed':len(checks),'deviceCommands':0,'temporaryDataRemoved':True}))
except Exception as e:
(ROOT/'.local/import-template-v3-http.json').write_text(json.dumps({'success':False,'prefix':prefix,'batches':batches,'checks':checks,'error':str(e)},ensure_ascii=False,indent=2),encoding='utf-8');raise
if __name__=='__main__':run()