am-freescan/scripts/verify_business_file_catalog.py

70 lines
6.0 KiB
Python
Raw Normal View History

"""Read-only deployed business file catalogue regression. No device API or business fixtures."""
from pathlib import Path
import sys,json,time,urllib.request,urllib.parse,hashlib,statistics
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'scripts'))
from verify_cmvr_native import Client,TargetReadOnlyDb
def run():
c=Client().login();db=TargetReadOnlyDb(c);checks=[]
def check(name,ok):
if not ok:raise AssertionError(name)
checks.append(name)
def page(**query):return c.request('GET','/admin-api/lab/data/catalog/page',query={'pageNo':1,'pageSize':100,**query})['data']
tables=['lab_test_task','lab_execution','lab_artifact_file','lab_dimension_file','lab_task_import_batch','lab_fixture_framework','lab_fixture_trajectory','lab_resource_occupation']
baseline={t:db.select('SELECT COUNT(*) n FROM '+t)[0]['n'] for t in tables}
data=page();items=data['list'];check('real business files returned',len(items)>12 and len(items)==data['total'])
check('stable unique source identifiers',len(set(x['key'] for x in items))==len(items))
check('internal paths and credentials omitted',not any(k in x for x in items for k in ('storage_path','storagePath','file_url','fileUrl','password','apiKey')))
for kind,table in [('ARTIFACT','lab_artifact_file'),('TASK_ATTACHMENT','lab_scan_attachment'),('TASK_IMPORT','lab_task_import_batch')]:
expected=db.select('SELECT COUNT(*) n FROM '+table+' WHERE deleted=0 AND tenant_id=1')[0]['n']
selected=page(sourceType=kind);check(kind+' source completeness',expected==selected['total'] and all(x['sourceType']==kind for x in selected['list']))
scans=[x for x in items if x['sourceType']=='SCAN_EXPORT'];check('scanner exports include original and supplement ownership',bool(scans) and all(x['executionNo'] and x['taskNo'] and x['unitNo'] for x in scans))
check('supplement executions identified',any(x['executionType']=='SUPPLEMENT' and x['sourceLabel']=='补扫导出' for x in scans))
for ext in ('PLY','STL','PDF','XLSX'):
selected=page(fileType=ext);check(ext+' filter',all(x['fileType']==ext for x in selected['list']))
selected=page(keyword=scans[0]['executionNo']);check('execution keyword search includes archived files',any(x['key']==scans[0]['key'] for x in selected['list']))
a=page(pageSize=5);b=page(pageNo=2,pageSize=5);check('pagination does not duplicate rows',not set(x['key'] for x in a['list'])&set(x['key'] for x in b['list']))
check('empty search is explicit',page(keyword='NO_SUCH_BUSINESS_FILE_20261103')['total']==0)
missing=[x for x in items if x.get('availabilityMessage')]
check('missing originals retain source records and disable downloads',bool(missing) and all(not x['downloadable'] and x['status']=='原文件待恢复' for x in missing))
denied=c.request('GET','/admin-api/lab/data/catalog/page',auth=False,expected=None);check('anonymous catalogue rejected',denied.get('code')==401)
for key in ('SCAN_EXPORT:0/../runtime.json','FIXTURE_FRAMEWORK:missing/0'):
rejected=c.request('GET','/admin-api/lab/data/catalog/download-link',query={'key':key},expected=None);check('unknown or traversing key rejected',rejected.get('code') not in (0,200))
small=min(scans,key=lambda x:x['sizeBytes'] or 2**63)
link=c.request('GET','/admin-api/lab/data/catalog/download-link',query={'key':small['key']})['data'];check('archived scan uses authenticated platform download',link['authenticated'] and link['url'].startswith('/lab/data/catalog/content?'))
request=urllib.request.Request(c.base_url+'/admin-api'+link['url'],headers={'tenant-id':'1','Authorization':'Bearer '+c._token})
digest=hashlib.sha256();size=0;head=b''
with urllib.request.urlopen(request,timeout=30) as response:
check('download has file attachment header','attachment;' in response.headers.get('Content-Disposition',''))
while block:=response.read(65536):
if not head:head=block[:100]
size+=len(block);digest.update(block)
check('download byte count matches archive',size==small['sizeBytes'])
execution,file=small['sourceId'].split('/')
metadata=json.loads((ROOT/'.local/artifacts/1'/execution/'scanner-files'/(file+'.json')).read_text(encoding='utf-8'))
check('download hash matches real archived content',digest.hexdigest()==metadata['sha256'])
for kind in ('TASK_IMPORT','TASK_ATTACHMENT','FIXTURE_FRAMEWORK'):
row=next(x for x in items if x['sourceType']==kind)
if not row['downloadable']:
rejected=c.request('GET','/admin-api/lab/data/catalog/download-link',query={'key':row['key']},expected=None)
check(kind+' missing original remains traceable and download is blocked',bool(row.get('availabilityMessage')) and rejected.get('code') not in (0,200))
continue
result=c.request('GET','/admin-api/lab/data/catalog/download-link',query={'key':row['key']})
check(kind+' download link resolves',result.get('code')==0)
url=result['data']['url']
if result['data']['authenticated']:
request=urllib.request.Request(c.base_url+'/admin-api'+url,headers={'tenant-id':'1','Authorization':'Bearer '+c._token})
count=0
with urllib.request.urlopen(request,timeout=30) as response:
check(kind+' content is a real file',not response.headers.get('Content-Type','').startswith('application/json'))
while block:=response.read(65536):count+=len(block)
check(kind+' downloads actual nonempty bytes',count>0)
latencies=[]
for _ in range(5):
start=time.monotonic();page(pageSize=20);latencies.append(round((time.monotonic()-start)*1000,1))
check('catalogue reads preserve business and occupation counts',all(db.select('SELECT COUNT(*) n FROM '+t)[0]['n']==n for t,n in baseline.items()))
report={'passed':len(checks),'checks':checks,'total':data['total'],'sources':data['sources'],'warnings':data['warnings'],'downloadBytes':size,'latencyMs':latencies,'medianMs':statistics.median(latencies),'deviceCalls':0,'businessDataCreated':0,'businessCountsPreserved':True,'missingOriginals':len(missing)}
(ROOT/'.local/business-catalog-http.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8');print(json.dumps(report,ensure_ascii=True))
if __name__=='__main__':run()