180 lines
11 KiB
Python
180 lines
11 KiB
Python
|
|
"""通过新项目实际 API 验证独立库上的导入、双检测项执行、成果和业务完结。"""
|
|||
|
|
import concurrent.futures
|
|||
|
|
import csv
|
|||
|
|
import io
|
|||
|
|
import json
|
|||
|
|
import time
|
|||
|
|
import urllib.error
|
|||
|
|
import urllib.parse
|
|||
|
|
import urllib.request
|
|||
|
|
from datetime import datetime, timedelta
|
|||
|
|
from pathlib import Path
|
|||
|
|
|
|||
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|||
|
|
BASE = 'http://127.0.0.1:48090/admin-api'
|
|||
|
|
TOKEN = None
|
|||
|
|
|
|||
|
|
|
|||
|
|
def call(path, data=None, method=None, raw=None, content_type=None, expect_error=False):
|
|||
|
|
"""统一鉴权调用,不输出 Token 或初始口令。"""
|
|||
|
|
headers = {'tenant-id': '1'}
|
|||
|
|
if TOKEN:
|
|||
|
|
headers['Authorization'] = 'Bearer ' + TOKEN
|
|||
|
|
if data is not None:
|
|||
|
|
raw = json.dumps(data, ensure_ascii=False).encode('utf-8')
|
|||
|
|
content_type = 'application/json'
|
|||
|
|
if content_type:
|
|||
|
|
headers['Content-Type'] = content_type
|
|||
|
|
request = urllib.request.Request(BASE + path, data=raw, headers=headers, method=method or ('POST' if raw is not None else 'GET'))
|
|||
|
|
try:
|
|||
|
|
with urllib.request.urlopen(request, timeout=35) as response:
|
|||
|
|
body = response.read()
|
|||
|
|
except urllib.error.HTTPError as ex:
|
|||
|
|
body = ex.read()
|
|||
|
|
result = json.loads(body)
|
|||
|
|
if expect_error:
|
|||
|
|
if result.get('code') == 0:
|
|||
|
|
raise AssertionError('Expected rejection: ' + path)
|
|||
|
|
return result
|
|||
|
|
if result.get('code') != 0:
|
|||
|
|
raise AssertionError(path + ': ' + str(result.get('msg', result)))
|
|||
|
|
return result.get('data')
|
|||
|
|
|
|||
|
|
|
|||
|
|
def flow(code):
|
|||
|
|
"""CMVR 参数与引用格式的可执行图,输入必须来自正式运行参数。"""
|
|||
|
|
return {'schemaVersion': 2, 'nodes': [
|
|||
|
|
{'id': 'start', 'type': 'start', 'x': 100, 'y': 150, 'properties': {
|
|||
|
|
'name': '开始', 'action': 'START', 'inputParams': [{'name': 'factor', 'type': 'number', 'required': True}]}},
|
|||
|
|
{'id': 'code', 'type': 'code', 'x': 350, 'y': 150, 'properties': {
|
|||
|
|
'name': '真实脚本计算', 'action': 'CODE', 'nodeParams': [
|
|||
|
|
{'name': 'code', 'type': 'string', 'input': code},
|
|||
|
|
{'name': 'factor', 'type': 'quote', 'quote': ['start', 'OUTPUT', 'factor'], 'quoteType': 'output'}]}},
|
|||
|
|
{'id': 'end', 'type': 'end', 'x': 600, 'y': 150, 'properties': {
|
|||
|
|
'name': '结束', 'action': 'END', 'nodeParams': [
|
|||
|
|
{'name': 'result', 'type': 'quote', 'quote': ['code', 'OUTPUT', 'result'], 'quoteType': 'output'}]}}
|
|||
|
|
], 'edges': [{'id': 'e1', 'sourceNodeId': 'start', 'targetNodeId': 'code'},
|
|||
|
|
{'id': 'e2', 'sourceNodeId': 'code', 'targetNodeId': 'end'}]}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def create_item(suffix, number):
|
|||
|
|
script = "function handler(params) { var value = params.factor * 21; return {measurements: [{measurementKey: 'VALUE', featureName: '真实脚本计算', value: value, judgment: value === 42 ? 'PASS' : 'FAIL'}]}; }"
|
|||
|
|
item = call('/lab/detection-item/save', {'code': f'E2E-{suffix}-{number}', 'name': f'验证检测项 {number}',
|
|||
|
|
'description': '独立项目 API 闭环验证,可在列表中查看与编辑', 'flowData': json.dumps(flow(script), ensure_ascii=False),
|
|||
|
|
'inputSchema': '[{"name":"factor","type":"number","required":true}]'})
|
|||
|
|
item = call('/lab/detection-item/publish?id=' + str(item['id']), {}, 'POST')
|
|||
|
|
return item
|
|||
|
|
|
|||
|
|
|
|||
|
|
def upload_task(suffix, method_code):
|
|||
|
|
"""真实 multipart 上传,不绕过导入校验与提交。"""
|
|||
|
|
csv_file = io.StringIO(newline='')
|
|||
|
|
writer = csv.writer(csv_file)
|
|||
|
|
writer.writerow(['外部任务编号','试验名称','项目名称','车型/产品','试验类型','试验要求','优先级','计划完成日期','申请人','样品编号','样品数量','方法编号','备注'])
|
|||
|
|
planned_finish = (datetime.now() + timedelta(days=7)).strftime('%Y-%m-%d')
|
|||
|
|
writer.writerow([f'E2E-{suffix}', '双检测项任务闭环验证', 'AM FreeScan', '', 'OTHER', '执行两个已发布检测项并确认真实结果', 'NORMAL', planned_finish, 'admin', 'DEMO-SAMPLE', '1', method_code, '由 verify_workflow.py 创建'])
|
|||
|
|
boundary = '----AMFreeScan' + suffix
|
|||
|
|
payload = (f'--{boundary}\r\nContent-Disposition: form-data; name="templateVersion"\r\n\r\nv1.0\r\n'
|
|||
|
|
f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="workflow.csv"\r\nContent-Type: text/csv\r\n\r\n').encode()
|
|||
|
|
payload += csv_file.getvalue().encode('utf-8-sig') + f'\r\n--{boundary}--\r\n'.encode()
|
|||
|
|
batch = call('/lab/task/import/upload', raw=payload, method='POST', content_type='multipart/form-data; boundary=' + boundary)
|
|||
|
|
if batch.get('errorRows', 0):
|
|||
|
|
rows = call('/lab/task/import/' + str(batch['id']) + '/rows/page?pageNo=1&pageSize=100')
|
|||
|
|
raise AssertionError('Import validation failed: ' + json.dumps(rows, ensure_ascii=False))
|
|||
|
|
result = call('/lab/task/import/' + str(batch['id']) + '/commit', {'importValidOnly': False})
|
|||
|
|
if result['generatedCount'] != 1:
|
|||
|
|
raise AssertionError('Expected one imported task')
|
|||
|
|
tasks = call('/lab/task/page?' + urllib.parse.urlencode({'pageNo': 1, 'pageSize': 10, 'externalTaskNo': f'E2E-{suffix}'}))
|
|||
|
|
return next(task for task in tasks['list'] if task['externalTaskNo'] == f'E2E-{suffix}')
|
|||
|
|
|
|||
|
|
|
|||
|
|
def main():
|
|||
|
|
global TOKEN
|
|||
|
|
runtime = json.loads((ROOT / '.local/runtime.json').read_text(encoding='utf-8'))
|
|||
|
|
login = call('/system/auth/login', {'username': 'admin', 'password': runtime['adminPassword']})
|
|||
|
|
TOKEN = login['accessToken']
|
|||
|
|
permissions = call('/system/auth/get-permission-info')
|
|||
|
|
assert permissions['user']['id'] is not None
|
|||
|
|
suffix = str(int(time.time()))
|
|||
|
|
items = [create_item(suffix, number) for number in (1, 2)]
|
|||
|
|
trial_id = call('/lab/detection-item/trial', {'itemId': items[0]['id'], 'runParams': {'factor': 2}})
|
|||
|
|
for _ in range(60):
|
|||
|
|
trial = call('/lab/detection-item/run/get?id=' + str(trial_id))
|
|||
|
|
if trial['status'] in ('SUCCESS', 'FAILED'):
|
|||
|
|
break
|
|||
|
|
time.sleep(0.3)
|
|||
|
|
assert trial['status'] == 'SUCCESS', trial.get('errorMessage')
|
|||
|
|
task = upload_task(suffix, items[0]['code'])
|
|||
|
|
task_id = task['id']
|
|||
|
|
call(f'/lab/task/{task_id}/confirm', {'comment': 'API 验证确认'})
|
|||
|
|
call(f'/lab/task/{task_id}/claim', {'comment': 'API 验证领取'})
|
|||
|
|
call(f'/lab/scan-plan/task/{task_id}/select', {'scanPlanRefIds': [item['methodRefId'] for item in items]})
|
|||
|
|
call('/lab/resource/sample-transfer/receive', {'taskId': task_id, 'sampleId': 900001, 'toLocation': 'DEMO-LAB'})
|
|||
|
|
# 每次验证使用独立时间段,避免上次中断验证遗留的预约冲突。
|
|||
|
|
start = datetime.now() + timedelta(days=1, seconds=int(suffix[-3:]) * 60)
|
|||
|
|
reservation = {'taskId': task_id, 'resourceId': 900001, 'startAt': int(start.timestamp() * 1000),
|
|||
|
|
'endAt': int((start + timedelta(seconds=30)).timestamp() * 1000), 'purpose': 'DEMO 软件检测验证'}
|
|||
|
|
device_reservation = call('/lab/resource/device-reservation/create', reservation)
|
|||
|
|
lab_reservation = call('/lab/resource/lab-reservation/create', reservation)
|
|||
|
|
readiness = call(f'/lab/resource/task/{task_id}/ready', {})
|
|||
|
|
assert readiness['taskStatus'] == 'READY', readiness
|
|||
|
|
call('/lab/execution/create', {'taskId': task_id, 'idempotencyKey': 'E2E-CREATE-' + suffix, 'runParams': {'factor': 2}})
|
|||
|
|
executions = call(f'/lab/execution/page?pageNo=1&pageSize=100&taskId={task_id}')['list']
|
|||
|
|
assert len(executions) == 2, len(executions)
|
|||
|
|
for execution in executions:
|
|||
|
|
precheck = call('/lab/execution/precheck?id=' + str(execution['id']), {}, 'POST')
|
|||
|
|
assert precheck['passed'], precheck
|
|||
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
|
|||
|
|
list(pool.map(lambda execution: call('/lab/execution/dispatch?id=' + str(execution['id']), {}, 'POST'), executions))
|
|||
|
|
for _ in range(120):
|
|||
|
|
current = [call('/lab/execution/get?id=' + str(execution['id'])) for execution in executions]
|
|||
|
|
if all(execution['status'] in ('SUCCEEDED', 'FAILED', 'CANCELLED') for execution in current):
|
|||
|
|
break
|
|||
|
|
time.sleep(0.5)
|
|||
|
|
assert all(execution['status'] == 'SUCCEEDED' for execution in current), [(x['status'], x.get('failureReason')) for x in current]
|
|||
|
|
for execution in executions:
|
|||
|
|
run = call('/lab/detection-item/run/by-execution?executionId=' + str(execution['id']))
|
|||
|
|
start_output = json.loads(run['outputData'])['start']
|
|||
|
|
assert start_output['executionId'] == str(execution['id']), '执行ID必须以完整字符串传入脚本,避免JS精度丢失'
|
|||
|
|
assert start_output['taskId'] == str(task_id)
|
|||
|
|
assert start_output['factor'] == 2, '普通数值参数仍应保留数值类型'
|
|||
|
|
call('/lab/execution/precheck?id=' + str(executions[0]['id']), {}, 'POST', expect_error=True)
|
|||
|
|
task = call('/lab/task/' + str(task_id))
|
|||
|
|
assert task['status'] == 'RESULT_PENDING', task['status']
|
|||
|
|
batches = call(f'/lab/result/page?pageNo=1&pageSize=100&taskId={task_id}')['list']
|
|||
|
|
assert len(batches) == 2
|
|||
|
|
for batch in batches:
|
|||
|
|
detail = call('/lab/result/get?id=' + str(batch['id']))
|
|||
|
|
assert len(detail['items']) == 1, '重复节点输出不应生成重复测量项'
|
|||
|
|
assert detail['items'][0]['measuredValue'] == 42
|
|||
|
|
assert detail['items'][0]['sourceJudgment'] == 'PASS'
|
|||
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
|
|||
|
|
list(pool.map(lambda batch: call('/lab/result/confirm?id=' + str(batch['id']), {}, 'POST'), batches))
|
|||
|
|
assert call('/lab/task/' + str(task_id))['status'] == 'REPORT_PENDING'
|
|||
|
|
artifacts = call(f'/lab/data/file/page?pageNo=1&pageSize=100&taskId={task_id}')['list']
|
|||
|
|
assert len(artifacts) == 2
|
|||
|
|
for artifact in artifacts:
|
|||
|
|
request = urllib.request.Request(BASE + '/lab/data/file/content?id=' + str(artifact['id']),
|
|||
|
|
headers={'tenant-id': '1', 'Authorization': 'Bearer ' + TOKEN})
|
|||
|
|
with urllib.request.urlopen(request, timeout=10) as response:
|
|||
|
|
json.loads(response.read())
|
|||
|
|
report_id = call('/lab/document/report/create', {'taskId': task_id, 'title': 'AM FreeScan API 验证报告', 'reportType': 'TEST'})
|
|||
|
|
call('/lab/document/report/publish?id=' + str(report_id), {}, 'POST')
|
|||
|
|
call(f'/lab/task/{task_id}/complete', {'comment': 'API 全流程验证完成'})
|
|||
|
|
task = call('/lab/task/' + str(task_id))
|
|||
|
|
assert task['status'] == 'COMPLETED'
|
|||
|
|
for kind, reservation_id in [('device', device_reservation), ('lab', lab_reservation)]:
|
|||
|
|
rows = call(f'/lab/resource/{kind}-reservation/page?pageNo=1&pageSize=100&taskId={task_id}')['list']
|
|||
|
|
assert any(str(row['id']) == str(reservation_id) and row['status'] == 'FINISHED' for row in rows)
|
|||
|
|
result = {'passed': True, 'taskId': task_id, 'status': task['status'], 'detectionItemIds': [item['id'] for item in items],
|
|||
|
|
'executionIds': [execution['id'] for execution in executions], 'resultBatchCount': len(batches),
|
|||
|
|
'artifactCount': len(artifacts), 'reportId': report_id}
|
|||
|
|
from cleanup_verification import cleanup
|
|||
|
|
result['cleanup'] = cleanup(['E2E-' + suffix], apply=True)
|
|||
|
|
(ROOT / '.local/workflow-verification.json').unlink(missing_ok=True)
|
|||
|
|
print(json.dumps(result, ensure_ascii=False))
|
|||
|
|
|
|||
|
|
|
|||
|
|
if __name__ == '__main__':
|
|||
|
|
main()
|