"""Verify CSV import -> original CMVR cases -> frozen native execution -> host business completion. Runs against the new localhost service and cleans its own verification records on success. """ import concurrent.futures import json import time import urllib.request from datetime import datetime, timedelta import verify_workflow as host from verify_cmvr_native import Client, NativeVerifier, ROOT def verify_host_controls(native, suffix): case = native.create_published_case('host-controls', 77, sleep_ms=12000) task = host.upload_task('CMVR-CONTROL-' + suffix, '') task_id = task['id'] host.call(f'/lab/task/{task_id}/confirm', {'comment': '原生执行控制验证'}) host.call(f'/lab/task/{task_id}/claim', {'comment': '原生执行控制验证'}) host.call(f'/lab/resource/task/{task_id}/bind-cmvr-testcases', {'testCaseIds': [case['caseId']]}) host.call('/lab/resource/sample-transfer/receive', {'taskId': task_id, 'sampleId': 900001, 'toLocation': 'DEMO-LAB'}) start = datetime.now() + timedelta(days=6, seconds=int(suffix[-4:]) * 61) reservation = {'taskId': task_id, 'resourceId': 900001, 'startAt': int(start.timestamp() * 1000), 'endAt': int((start + timedelta(seconds=30)).timestamp() * 1000), 'purpose': 'CMVR 暂停恢复取消验证'} for kind in ('device', 'lab'): host.call('/lab/resource/' + kind + '-reservation/create', reservation) assert host.call(f'/lab/resource/task/{task_id}/ready', {})['taskStatus'] == 'READY' host.call('/lab/execution/create', {'taskId': task_id, 'idempotencyKey': 'CMVR-CONTROL-' + suffix, 'runParams': {'factor': 2}}) execution = host.call(f'/lab/execution/page?pageNo=1&pageSize=100&taskId={task_id}')['list'][0] execution_id = execution['id'] assert host.call('/lab/execution/precheck?id=' + str(execution_id), {}, 'POST')['passed'] host.call('/lab/execution/dispatch?id=' + str(execution_id), {}, 'POST') for _ in range(60): current = host.call('/lab/execution/get?id=' + str(execution_id)) if current['status'] == 'RUNNING' and len(current['steps']) >= 2: break time.sleep(0.1) assert current['status'] == 'RUNNING' host.call('/lab/execution/pause?id=' + str(execution_id), {}, 'POST') assert host.call('/lab/execution/get?id=' + str(execution_id))['status'] == 'PAUSED' host.call('/lab/execution/resume?id=' + str(execution_id), {}, 'POST') assert host.call('/lab/execution/get?id=' + str(execution_id))['status'] == 'RUNNING' host.call('/lab/execution/cancel?id=' + str(execution_id) + '&reason=CMVR-control-verification', {}, 'POST') assert host.call('/lab/execution/get?id=' + str(execution_id))['status'] == 'CANCELLED' mapping = host.call('/lab/execution/cmvr-binding?executionId=' + str(execution_id)) row = native.db.select('SELECT status FROM te_task_inst WHERE id=%s', (mapping['cmvrInstId'],))[0] assert str(row['status']) == '4', 'Native cancellation must commit even when called after the host commit' assert mapping['cmvrStatus'] == '4' return {'taskId': task_id, 'executionId': execution_id, 'nativeInstanceId': mapping['cmvrInstId'], 'pauseResumeCancelPassed': True} def main(): client = Client().login() host.TOKEN = client._token suffix = str(int(time.time())) native = NativeVerifier(client, prefix='CMVR_HOST_' + suffix) cases = [native.create_published_case('host-' + str(number), 42) for number in (1, 2)] task = host.upload_task('CMVR-' + suffix, '') task_id = task['id'] host.call(f'/lab/task/{task_id}/confirm', {'comment': '原版 CMVR 接入验证'}) host.call(f'/lab/task/{task_id}/claim', {'comment': '原版 CMVR 接入验证'}) case_ids = [row['caseId'] for row in cases] host.call(f'/lab/resource/task/{task_id}/bind-cmvr-testcases', {'testCaseIds': case_ids}) assert set(host.call(f'/lab/resource/task/{task_id}/bind-cmvr-testcases')) == set(case_ids) host.call('/lab/resource/sample-transfer/receive', {'taskId': task_id, 'sampleId': 900001, 'toLocation': 'DEMO-LAB'}) start = datetime.now() + timedelta(days=3, seconds=int(suffix[-4:]) * 61) reservation = {'taskId': task_id, 'resourceId': 900001, 'startAt': int(start.timestamp() * 1000), 'endAt': int((start + timedelta(seconds=30)).timestamp() * 1000), 'purpose': 'CMVR 原生执行软件验证'} reservation_ids = {kind: host.call('/lab/resource/' + kind + '-reservation/create', reservation) for kind in ('device', 'lab')} assert host.call(f'/lab/resource/task/{task_id}/ready', {})['taskStatus'] == 'READY' host.call('/lab/execution/create', {'taskId': task_id, 'idempotencyKey': 'CMVR-HOST-' + suffix, 'runParams': {'factor': 2, 'seed': 1}}) executions = host.call(f'/lab/execution/page?pageNo=1&pageSize=100&taskId={task_id}')['list'] assert len(executions) == 2 original_versions = {} for execution in executions: mapping = host.call('/lab/execution/cmvr-binding?executionId=' + str(execution['id'])) assert mapping['testCaseId'] in case_ids and mapping['versionId'] original_versions[str(execution['id'])] = mapping['versionId'] assert host.call('/lab/execution/precheck?id=' + str(execution['id']), {}, 'POST')['passed'] # Publish a new graph after execution creation; the host must still run the previously frozen graph. item_id = cases[0]['detectItemId'] current = client.native('GET', '/test/detect/' + item_id)['data'] changed = json.loads(current['flowData']) for node in changed['nodes']: if node.get('properties', {}).get('action') == 'CODE': for param in node['properties'].get('nodeParams', []): if param.get('name') == 'code': param['input'] = "function handler(params) { return {value: 999, measurements:[{measurementKey:'VALUE',value:999,judgment:'FAIL'}]}; }" native.publish(item_id, changed, 'new release after host snapshot') with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: list(pool.map(lambda row: host.call('/lab/execution/dispatch?id=' + str(row['id']), {}, 'POST'), executions)) for _ in range(120): current_executions = [host.call('/lab/execution/get?id=' + str(row['id'])) for row in executions] if all(row['status'] in ('SUCCEEDED', 'FAILED', 'CANCELLED') for row in current_executions): break time.sleep(0.5) assert all(row['status'] == 'SUCCEEDED' for row in current_executions), [(row['status'], row.get('failureReason')) for row in current_executions] native_ids = [] for execution in current_executions: assert len(execution['steps']) >= 3, execution['steps'] mapping = host.call('/lab/execution/cmvr-binding?executionId=' + str(execution['id'])) assert mapping['versionId'] == original_versions[str(execution['id'])] assert mapping['cmvrInstId'] and execution['externalJobId'] == 'CMVR:' + mapping['cmvrInstId'] native_ids.append(mapping['cmvrInstId']) assert host.call('/lab/task/' + str(task_id))['status'] == 'RESULT_PENDING' batches = host.call(f'/lab/result/page?pageNo=1&pageSize=100&taskId={task_id}')['list'] assert len(batches) == 2 for batch in batches: result = host.call('/lab/result/get?id=' + str(batch['id'])) assert len(result['items']) == 1 assert result['items'][0]['measuredValue'] == 42, result['items'] assert result['items'][0]['sourceJudgment'] == 'PASS' with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: list(pool.map(lambda row: host.call('/lab/result/confirm?id=' + str(row['id']), {}, 'POST'), batches)) artifacts = host.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(host.BASE + '/lab/data/file/content?id=' + str(artifact['id']), headers={'tenant-id': '1', 'Authorization': 'Bearer ' + host.TOKEN}) with urllib.request.urlopen(request, timeout=10) as response: output = json.loads(response.read()) assert output['cmvrInstanceId'] in native_ids code_outputs = [row['paramsOut']['result'] for row in output['nodes'] if isinstance(row.get('paramsOut'), dict) and isinstance(row['paramsOut'].get('result'), dict) and 'params' in row['paramsOut']['result']] assert code_outputs, output params = code_outputs[0]['params'] assert params['factor'] == 2 # START has all task parameters; CODE receives only explicitly configured references. starts = [row['paramsOut'] for row in output['nodes'] if row.get('nodeId') == 'start'] assert starts and starts[0]['executionId'] in {str(row['id']) for row in executions} assert starts[0]['taskId'] == str(task_id) report_id = host.call('/lab/document/report/create', {'taskId': task_id, 'title': '原版 CMVR 正式执行验证', 'reportType': 'TEST'}) host.call('/lab/document/report/publish?id=' + str(report_id), {}, 'POST') host.call(f'/lab/task/{task_id}/complete', {'comment': '原版检测项与导入任务完整闭环验证完成'}) assert host.call('/lab/task/' + str(task_id))['status'] == 'COMPLETED' for kind, reservation_id in reservation_ids.items(): rows = host.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) evidence = {'passed': True, 'taskId': task_id, 'status': 'COMPLETED', 'caseIds': case_ids, 'executionIds': [row['id'] for row in executions], 'nativeInstanceIds': native_ids, 'frozenVersions': original_versions, 'resultBatchCount': len(batches), 'artifactCount': len(artifacts), 'reportId': report_id} evidence['controls'] = verify_host_controls(native, suffix) from cleanup_verification import cleanup evidence['cleanup'] = cleanup(['CMVR_HOST_' + suffix, 'E2E-CMVR-' + suffix, 'E2E-CMVR-CONTROL-' + suffix], apply=True) (ROOT / '.local/cmvr-host-verification.json').unlink(missing_ok=True) print(json.dumps(evidence, ensure_ascii=False)) if __name__ == '__main__': main()