am-freescan/scripts/verify_import_deletion.py
lixiaolong cfff7295a6 feat(scanner): integrate scanner workflows and real-time preview
Add scanner API integration, workflow components, execution-bound live images and 3D model viewing. Harden task control, parameters, resource protection and reports, with automated regressions and detailed verification records.
2026-10-23 09:03:27 +08:00

121 lines
6.5 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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.

"""Verify import deletion through real local APIs and remove all successful-run fixtures."""
import concurrent.futures
import csv
import io
import json
import urllib.request
import uuid
from cleanup_verification import cleanup
from verify_scan_only import ScanOnlyVerifier, ROOT
def upload(v, rows, files):
filename = v.prefix + '-' + uuid.uuid4().hex[:6] + '.csv'
output = io.StringIO(newline='')
writer = csv.DictWriter(output, fieldnames=list(rows[0]))
writer.writeheader(); writer.writerows(rows)
boundary = '----AMFreeScan' + uuid.uuid4().hex
raw = (f'--{boundary}\r\nContent-Disposition: form-data; name="templateVersion"\r\n\r\nv2.0\r\n'
f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="{filename}"\r\n'
'Content-Type: text/csv\r\n\r\n').encode() + output.getvalue().encode('utf-8-sig') + f'\r\n--{boundary}--\r\n'.encode()
request = urllib.request.Request(v.client.base_url + '/admin-api/lab/task/import/upload', data=raw,
headers={'tenant-id':'1', 'Authorization':'Bearer ' + v.client._token,
'Content-Type':'multipart/form-data; boundary=' + boundary}, method='POST')
with urllib.request.urlopen(request, timeout=20) as response:
result = json.load(response)
assert result['code'] == 0, result.get('msg')
files.extend(v.native.db.select('SELECT id,name FROM infra_file WHERE name=%s AND deleted=0', (filename,)))
return result['data']
def rows_of(v, batch):
return v.api('GET', f"/lab/task/import/{batch['id']}/rows/page", query={'pageNo':1,'pageSize':100})['list']
def remove_rows(v, batch, ids, rejected=False):
return v.api('DELETE', f"/lab/task/import/{batch['id']}/rows", {'rowIds':ids}, rejected=rejected)
def run():
v = ScanOnlyVerifier(); files = []; passed = False
checks = []
print('Regression prefix: '+v.prefix,flush=True)
def check(name):
checks.append(dict(name=name,passed=True))
print('PASS '+name,flush=True)
try:
case = v.create_case('导入删除验è¯<EFBFBD>')
invalid = upload(v, [v.row('invalid', '', 1)], files)
assert invalid['errorRows'] == 1
v.api('DELETE', f"/lab/task/import/{invalid['id']}")
v.api('GET', f"/lab/task/import/{invalid['id']}", rejected=True)
v.api('POST', f"/lab/task/import/{invalid['id']}/commit", {'importValidOnly':False}, rejected=True)
check('delete uncommitted batch prevents later commit')
mixed = upload(v, [v.row('mixed-bad','',1),v.row('mixed-good',case['caseId'],1)], files)
bad, good = rows_of(v,mixed)
remove_rows(v,mixed,[good['id']],rejected=True)
remove_rows(v,mixed,[bad['id'],good['id']],rejected=True)
remove_rows(v,mixed,[bad['id']])
summary = v.api('GET', f"/lab/task/import/{mixed['id']}")
assert summary['totalRows']==1 and summary['errorRows']==0 and summary['validRows']==1
assert v.api('POST',f"/lab/task/import/{mixed['id']}/commit",{'importValidOnly':False})['generatedCount']==1
v.api('DELETE',f"/lab/task/import/{mixed['id']}",rejected=True)
check('row deletion refreshes counts and permits committing valid remainder; committed batch protected')
committed = upload(v,[v.row('committed-bad','',1),v.row('committed-good',case['caseId'],1)],files)
bad,good=rows_of(v,committed)
assert v.api('POST',f"/lab/task/import/{committed['id']}/commit",{'importValidOnly':True})['generatedCount']==1
kept_task=rows_of(v,committed)[1]['generatedTaskId']
foreign=upload(v,[v.row('foreign-bad','',1)],files)
foreign_id=rows_of(v,foreign)[0]['id']
remove_rows(v,committed,[bad['id'],foreign_id],rejected=True)
assert len(rows_of(v,committed))==2
remove_rows(v,committed,[bad['id']])
assert rows_of(v,committed)[0]['generatedTaskId']==kept_task
assert v.api('GET',f"/lab/task/import/{committed['id']}")['status']=='COMMITTED'
remove_rows(v,foreign,[foreign_id])
assert v.api('GET',f"/lab/task/import/{foreign['id']}")['totalRows']==0
v.api('POST',f"/lab/task/import/{foreign['id']}/commit",{'importValidOnly':True},rejected=True)
v.api('DELETE',f"/lab/task/import/{foreign['id']}")
check('cross-batch requests rejected atomically; committed tasks preserved; empty batches cannot commit')
duplicate=upload(v,[v.row('same-number','',1),v.row('same-number',case['caseId'],1)],files)
first,second=rows_of(v,duplicate)
assert first['validationStatus']=='ERROR' and second['validationStatus']=='DUPLICATE'
remove_rows(v,duplicate,[first['id']])
promoted=rows_of(v,duplicate)[0]
assert promoted['validationStatus']=='VALID' and promoted['rowNo']==second['rowNo']
check('remaining file duplicate is revalidated without renumbering')
for n in range(2):
race=upload(v,[v.row('race-'+str(n),case['caseId'],1)],files)
base=f"/lab/task/import/{race['id']}"
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
commit=pool.submit(v.client.request,'POST','/admin-api'+base+'/commit',{'importValidOnly':False},None,None)
delete=pool.submit(v.client.request,'DELETE','/admin-api'+base,None,None,None)
outcomes=[commit.result(),delete.result()]
assert sum(r['code']==0 for r in outcomes)==1, outcomes
tasks=v.native.db.select('SELECT id FROM lab_test_task WHERE source_batch_id=%s AND deleted=0',(race['id'],))
assert len(tasks)==(1 if outcomes[0]['code']==0 else 0)
check('concurrent commit/delete has one winner and no orphan task')
passed=True
finally:
try:
if passed:
result=cleanup([v.prefix],apply=True)
for file in files:
assert file['name'].startswith(v.prefix)
if v.native.db.select('SELECT id FROM infra_file WHERE id=%s AND deleted=0',(file['id'],)):
v.client.request('DELETE','/admin-api/infra/file/delete',query={'id':file['id']})
assert not cleanup([v.prefix])['counts']
(ROOT/'.local/import-deletion-verification.json').write_text(json.dumps(dict(prefix=v.prefix,passed=True,checks=checks,cleanup=result,remaining={}),ensure_ascii=False,indent=2),encoding='utf-8')
print('PASS all current-run fixtures and files cleaned',flush=True)
finally:
if v.native._db: v.native.db.close()
if __name__=='__main__':
run()