229 lines
16 KiB
Python
229 lines
16 KiB
Python
|
|
"""Black-box read-boundary exploration and scoped master-data CRUD regression.
|
||
|
|
|
||
|
|
Only localhost; read-only route sweep plus clearly marked fixture creation.
|
||
|
|
Never runs device operations or supplier sync. Creates, executes and publishes
|
||
|
|
only this run's explicitly marked software-only fixtures, then removes them.
|
||
|
|
Source inventory is used to select GET routes; results are checked through HTTP.
|
||
|
|
"""
|
||
|
|
import datetime as dt
|
||
|
|
import json
|
||
|
|
from pathlib import Path
|
||
|
|
import re
|
||
|
|
import urllib.request
|
||
|
|
import urllib.error
|
||
|
|
import urllib.parse
|
||
|
|
import uuid
|
||
|
|
import io
|
||
|
|
import zipfile
|
||
|
|
import argparse
|
||
|
|
import time
|
||
|
|
|
||
|
|
from cleanup_verification import cleanup
|
||
|
|
from verify_cmvr_native import Client, safe
|
||
|
|
|
||
|
|
ROOT=Path(__file__).resolve().parents[1]
|
||
|
|
MISSING='9223372036854775806'
|
||
|
|
|
||
|
|
|
||
|
|
class FeatureVerifier:
|
||
|
|
def __init__(self,review_seconds=0):
|
||
|
|
self.client=Client().login()
|
||
|
|
self.prefix='E2E-ALL-'+dt.datetime.now().strftime('%m%d%H%M%S')+'-'+uuid.uuid4().hex[:4]
|
||
|
|
self.results=[]
|
||
|
|
self.ids={}
|
||
|
|
self.business=None
|
||
|
|
self.review_seconds=review_seconds
|
||
|
|
|
||
|
|
def record(self,name,ok,**details):
|
||
|
|
self.results.append(dict(name=name,passed=bool(ok),**safe(details)))
|
||
|
|
if not ok: print('FAIL',name,str(details),flush=True)
|
||
|
|
|
||
|
|
def call(self,method,path,body=None,query=None):
|
||
|
|
if path=='/lab/document/report/update' and isinstance(body,str):
|
||
|
|
req=urllib.request.Request(self.client.base_url+'/admin-api'+path+'?'+urllib.parse.urlencode(query or {}),
|
||
|
|
data=body.encode('utf-8'),method=method,
|
||
|
|
headers={'tenant-id':'1','Authorization':'Bearer '+self.client._token,'Content-Type':'text/plain; charset=UTF-8'})
|
||
|
|
try:response=urllib.request.urlopen(req,timeout=25)
|
||
|
|
except urllib.error.HTTPError as error:response=error
|
||
|
|
with response:return json.load(response)
|
||
|
|
return self.client.request(method,'/admin-api'+path,body,query,expected=None)
|
||
|
|
|
||
|
|
def expect(self,name,result,success=True):
|
||
|
|
code=result.get('code')
|
||
|
|
ok=code==0 if success else code not in (0,200,500)
|
||
|
|
self.record(name,ok,code=code,message=result.get('msg'))
|
||
|
|
return result.get('data')
|
||
|
|
|
||
|
|
def sweep(self):
|
||
|
|
folder=ROOT/'am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin'
|
||
|
|
found=[]
|
||
|
|
for source in sorted(folder.rglob('*Controller.java')):
|
||
|
|
text=source.read_text(encoding='utf-8')
|
||
|
|
base=re.search(r'@RequestMapping\("([^"\n]+)"\)',text)
|
||
|
|
if not base:continue
|
||
|
|
for route in re.finditer(r'@GetMapping\("([^"\n]+)"\)',text):
|
||
|
|
path=base[1]+route[1]
|
||
|
|
# No provider download packages, external test/sync, or raw file bodies.
|
||
|
|
if any(word in path for word in ('download','content','package','export','template','sync','health/test')):continue
|
||
|
|
signature=text[route.end():].split('{',1)[0]
|
||
|
|
query={'pageNo':1,'pageSize':2}
|
||
|
|
for annotation in re.finditer(r'@(?:RequestParam|PathVariable)(?:\(([^)]*)\))?\s+(?:@\w+(?:\([^)]*\))?\s+)*(Long|String|Integer|Boolean)\s+(\w+)',signature):
|
||
|
|
opts,kind,variable=annotation.groups()
|
||
|
|
match=re.search(r'"([^"\n]+)"',opts or '')
|
||
|
|
name=match[1] if match else variable
|
||
|
|
value='false' if kind=='Boolean' else (self.prefix if kind=='String' else MISSING)
|
||
|
|
if name.lower().endswith('type'):value='SAMPLE'
|
||
|
|
if '{'+name+'}' in path:path=path.replace('{'+name+'}',value)
|
||
|
|
else:query[name]=value
|
||
|
|
path=re.sub(r'\{[^}]+\}',MISSING,path)
|
||
|
|
try:
|
||
|
|
result=self.call('GET',path,query=query)
|
||
|
|
self.record('GET '+path,result.get('code')!=500,code=result.get('code'),message=result.get('msg'))
|
||
|
|
except Exception as error:self.record('GET '+path,False,error=str(error))
|
||
|
|
if path.endswith('/page'):
|
||
|
|
for field in ('pageNo','pageSize'):
|
||
|
|
result=self.call('GET',path,query=dict(query,**{field:0}))
|
||
|
|
self.expect(path+' invalid '+field,result,False)
|
||
|
|
found.append(dict(source=str(source.relative_to(ROOT)),path=path))
|
||
|
|
self.inventory=found
|
||
|
|
|
||
|
|
def masters(self):
|
||
|
|
fixtures={
|
||
|
|
'sample':dict(sampleSource='SELF',sampleType='PART',quantity=1,status='ENABLED'),
|
||
|
|
'lab':dict(location='LOCALHOST QA',status='ENABLED',exclusiveUse=False),
|
||
|
|
'fixture':dict(fixtureSize='S',status='ENABLED',applicables=[]),
|
||
|
|
'device':dict(deviceType='OTHER',vendor='LOCALHOST QA',model='FIXTURE',businessStatus='ENABLED'),
|
||
|
|
'material':dict(materialType='NORMAL',unit='件',returnRequired=False,status='ENABLED'),
|
||
|
|
'method':dict(methodType='FIXED_SCAN',externalId=self.prefix,methodVersion='1',applicableDeviceTypes=['OTHER'],publishStatus='PUBLISHED',status='ENABLED')}
|
||
|
|
for kind,values in fixtures.items():
|
||
|
|
code=kind+'Code';name=kind+'Name';base='/lab/master/'+kind
|
||
|
|
body=dict(values,**{code:self.prefix+'-'+kind,name:self.prefix+'-'+kind})
|
||
|
|
result=self.call('POST',base+'/create',body)
|
||
|
|
identifier=self.expect(kind+' create',result)
|
||
|
|
if not identifier:continue
|
||
|
|
self.ids[kind]=identifier
|
||
|
|
self.expect(kind+' duplicate code',self.call('POST',base+'/create',body),False)
|
||
|
|
detail=self.expect(kind+' get',self.call('GET',base+'/get',query={'id':identifier}))
|
||
|
|
self.record(kind+' saved values',str(detail.get('id'))==str(identifier) and detail.get(code)==body[code])
|
||
|
|
self.expect(kind+' invalid required name',self.call('POST',base+'/create',dict(body,**{code:self.prefix+'-invalid-'+kind,name:''})),False)
|
||
|
|
self.expect(kind+' overlong name',self.call('POST',base+'/create',dict(body,**{code:self.prefix+'-long-'+kind,name:'x'*129})),False)
|
||
|
|
if kind!='method':
|
||
|
|
update=dict(body,id=identifier,**{name:self.prefix+'-edited-'+kind})
|
||
|
|
self.expect(kind+' update',self.call('PUT',base+'/update',update))
|
||
|
|
self.expect(kind+' update without id',self.call('PUT',base+'/update',dict(body,**{code:self.prefix+'-missing-'+kind})),False)
|
||
|
|
for action in ('disable','enable'):
|
||
|
|
self.expect(kind+' '+action,self.call('POST',base+'/'+action,query={'id':identifier}))
|
||
|
|
self.record(kind+' missing record not 500',self.call('GET',base+'/get',query={'id':MISSING}).get('code')!=500)
|
||
|
|
|
||
|
|
if 'sample' in self.ids:
|
||
|
|
body=dict(bizType='SAMPLE',bizId=self.ids['sample'],fileName=self.prefix+'.txt',
|
||
|
|
fileUrl='/admin-api/infra/file/qa/get/'+self.prefix+'.txt',fileType='OTHER')
|
||
|
|
attachment=self.expect('attachment create',self.call('POST','/lab/master/attachment/create',body))
|
||
|
|
self.expect('attachment missing parent',self.call('POST','/lab/master/attachment/create',dict(body,bizId=MISSING)),False)
|
||
|
|
self.expect('attachment executable URL',self.call('POST','/lab/master/attachment/create',dict(body,fileUrl='javascript:alert(1)')),False)
|
||
|
|
self.expect('attachment invalid business type',self.call('POST','/lab/master/attachment/create',dict(body,bizType=self.prefix)),False)
|
||
|
|
if attachment:self.expect('attachment delete',self.call('DELETE','/lab/master/attachment/delete',query={'id':attachment}))
|
||
|
|
|
||
|
|
def documents_and_results(self):
|
||
|
|
from verify_scan_only import ScanOnlyVerifier
|
||
|
|
v=ScanOnlyVerifier();self.business=v
|
||
|
|
v.prefix=self.prefix;v.sample_code=self.prefix+'-BUSINESS-SAMPLE'
|
||
|
|
case=v.create_case('all-feature-documents')
|
||
|
|
case['graph']['nodes'][0]['properties']['resourceRoles']=[]
|
||
|
|
case['graph']['nodes']=[n for n in case['graph']['nodes'] if n.get('properties',{}).get('nodeType')!='EDGE']
|
||
|
|
nodes=case['graph']['nodes']
|
||
|
|
case['graph']['edges']=[dict(id='qa-edge-'+str(i),sourceNodeId=nodes[i]['id'],targetNodeId=nodes[i+1]['id']) for i in range(len(nodes)-1)]
|
||
|
|
v.native.publish(case['itemId'],case['graph'],'Scoped software-only document/result acceptance')
|
||
|
|
task=v.import_task('documents',case['caseId'],1)
|
||
|
|
detail=v.task(task)
|
||
|
|
v.api('PUT','/lab/scan-task/prepare',dict(taskId=task,expectedRevision=detail['config']['revision'],testCaseId=case['caseId'],
|
||
|
|
sampleReceived=True,requireFixture=False,fixtureConfirmed=False,robotId='',runtimeAssignments=[],runParams={}))
|
||
|
|
ready=v.api('POST','/lab/scan-task/precheck',dict(taskId=task))
|
||
|
|
self.record('software task precheck',ready['passed'],items=ready['items'])
|
||
|
|
if not ready['passed']:return
|
||
|
|
execution,_=v.start(task,v.task(task)['units'][0]);v.wait_execution(execution)
|
||
|
|
self.record('software task completes without a robot',v.task(task)['task']['status']=='COMPLETED')
|
||
|
|
batch_body=dict(taskId=task,executionId=execution,externalBatchNo=self.prefix+'-BATCH',sourceSystem='QA',idempotencyKey=self.prefix+'-RESULT',
|
||
|
|
items=[dict(measurementKey='QA-LENGTH',featureName='测试尺寸',measuredValue=1,sourceJudgment='PASS',unit='mm')])
|
||
|
|
batch=self.expect('result receive',self.call('POST','/lab/result/batch',batch_body))
|
||
|
|
if not batch:return
|
||
|
|
self.record('result receive idempotency',str(self.call('POST','/lab/result/batch',batch_body).get('data'))==str(batch))
|
||
|
|
self.expect('result cannot confirm while receiving',self.call('POST','/lab/result/confirm',query=dict(id=batch)),False)
|
||
|
|
self.expect('result complete',self.call('POST','/lab/result/complete',query=dict(id=batch)))
|
||
|
|
self.expect('result confirm',self.call('POST','/lab/result/confirm',query=dict(id=batch)))
|
||
|
|
self.expect('result confirm idempotent',self.call('POST','/lab/result/confirm',query=dict(id=batch)))
|
||
|
|
self.expect('result compare',self.call('GET','/lab/result/compare',query=dict(taskId=task,batchIds=str(batch))))
|
||
|
|
report_body=dict(taskId=task,title=self.prefix+'-REPORT',executionId=execution,resultBatchIds=[batch],idempotencyKey=self.prefix+'-REPORT')
|
||
|
|
report=self.expect('report draft create',self.call('POST','/lab/document/report/create',report_body))
|
||
|
|
if not report:return
|
||
|
|
self.record('report draft idempotency',str(self.call('POST','/lab/document/report/create',report_body).get('data'))==str(report))
|
||
|
|
self.expect('report publish',self.call('POST','/lab/document/report/publish',query=dict(id=report)))
|
||
|
|
if self.review_seconds:
|
||
|
|
review=ROOT/'.local/report-browser-review.json'
|
||
|
|
done=ROOT/'.local/report-browser-review.done'
|
||
|
|
review.write_text(json.dumps(dict(prefix=self.prefix,reportId=str(report))),encoding='utf-8')
|
||
|
|
print('REPORT BROWSER REVIEW READY: '+str(review),flush=True)
|
||
|
|
deadline=time.monotonic()+self.review_seconds
|
||
|
|
try:
|
||
|
|
while time.monotonic()<deadline:
|
||
|
|
if done.exists() and done.read_text(encoding='utf-8').strip()==self.prefix:break
|
||
|
|
time.sleep(.2)
|
||
|
|
finally:
|
||
|
|
review.unlink(missing_ok=True)
|
||
|
|
if done.exists() and done.read_text(encoding='utf-8').strip()==self.prefix:done.unlink()
|
||
|
|
for text in ('first edit','second edit'):
|
||
|
|
self.expect('published report '+text,self.call('POST','/lab/document/report/update','<p>'+text+'</p>',query=dict(id=report,title=self.prefix+'-REPORT')))
|
||
|
|
state=self.expect('report revised draft get',self.call('GET','/lab/document/report/get',query=dict(id=report)))
|
||
|
|
self.record('saving a published revision reuses one draft',len(state['versions'])==2 and sum(v['status']=='DRAFT' for v in state['versions'])==1,
|
||
|
|
versionCount=len(state['versions']))
|
||
|
|
self.record('report body preserves exact text after repeated saves',
|
||
|
|
next(v for v in state['versions'] if v['status']=='DRAFT')['contentHtml']=='<p>second edit</p>')
|
||
|
|
self.expect('report republish',self.call('POST','/lab/document/report/publish',query=dict(id=report)))
|
||
|
|
state=self.call('GET','/lab/document/report/get',query=dict(id=report)).get('data')
|
||
|
|
self.record('formal report retains previous version',sum(v['status']=='PUBLISHED' for v in state['versions'])==1 and any(v['status']=='SUPERSEDED' for v in state['versions']))
|
||
|
|
record=self.expect('original record create',self.call('POST','/lab/document/record/create',query=dict(taskId=task,executionId=execution)))
|
||
|
|
if record:self.expect('original record append revision',self.call('POST','/lab/document/record/revision',query=dict(id=record,content=self.prefix+'-revision')))
|
||
|
|
pack=self.expect('document ZIP export',self.call('POST','/lab/document/package/export',query=dict(taskId=task,includePointCloud='false')))
|
||
|
|
if pack:
|
||
|
|
packages=self.call('GET','/lab/document/package/page',query=dict(taskId=task,pageNo=1,pageSize=100)).get('data') or {}
|
||
|
|
package=next((p for p in packages.get('list',[]) if str(p['id'])==str(pack)),{})
|
||
|
|
self.record('ZIP package completed',package.get('status')=='SUCCEEDED')
|
||
|
|
url=package.get('fileUrl')
|
||
|
|
if url:
|
||
|
|
path=urllib.parse.urlsplit(url).path
|
||
|
|
req=urllib.request.Request(self.client.base_url+path,headers={'Authorization':'Bearer '+self.client._token,'tenant-id':'1'})
|
||
|
|
with urllib.request.urlopen(req,timeout=15) as response: payload=response.read(5*1024*1024)
|
||
|
|
with zipfile.ZipFile(io.BytesIO(payload)) as zipped:
|
||
|
|
self.record('ZIP contains manifest and published report',{'manifest.txt','report.html'}<=set(zipped.namelist()))
|
||
|
|
self.expect('void report requires reason',self.call('POST','/lab/document/report/void',query=dict(id=report,reason='')),False)
|
||
|
|
self.expect('report void',self.call('POST','/lab/document/report/void',query=dict(id=report,reason=self.prefix)))
|
||
|
|
self.expect('void report cannot be edited',self.call('POST','/lab/document/report/update','bad',query=dict(id=report)),False)
|
||
|
|
self.expect('void report cannot be republished',self.call('POST','/lab/document/report/publish',query=dict(id=report)),False)
|
||
|
|
v.active_tasks.discard(task)
|
||
|
|
|
||
|
|
def run(self):
|
||
|
|
try:
|
||
|
|
self.sweep()
|
||
|
|
self.masters()
|
||
|
|
self.documents_and_results()
|
||
|
|
finally:
|
||
|
|
if self.business:
|
||
|
|
for task in self.business.active_tasks:
|
||
|
|
if self.business.task(task)['task']['status'] not in ('COMPLETED','CANCELLED'):
|
||
|
|
self.business.api('POST','/lab/scan-task/cancel',dict(taskId=task,reason=self.prefix+' cleanup'))
|
||
|
|
cleaned=cleanup([self.prefix],apply=True)
|
||
|
|
remaining=cleanup([self.prefix])['counts']
|
||
|
|
self.record('scoped cleanup',not remaining,remaining=remaining)
|
||
|
|
report=dict(prefix=self.prefix,checks=self.results,routeInventory=getattr(self,'inventory',[]),cleanup=cleaned,
|
||
|
|
passed=all(r['passed'] for r in self.results),failures=[r for r in self.results if not r['passed']])
|
||
|
|
(ROOT/'.local/all-features-blackbox.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
|
||
|
|
print(json.dumps(dict(prefix=self.prefix,passed=report['passed'],checks=len(self.results),failures=len(report['failures'])),ensure_ascii=False),flush=True)
|
||
|
|
return report['passed']
|
||
|
|
|
||
|
|
|
||
|
|
if __name__=='__main__':
|
||
|
|
parser=argparse.ArgumentParser(description=__doc__)
|
||
|
|
parser.add_argument('--review-seconds',type=int,default=0,choices=range(0,301),metavar='0..300')
|
||
|
|
args=parser.parse_args()
|
||
|
|
raise SystemExit(0 if FeatureVerifier(args.review_seconds).run() else 1)
|