693 lines
37 KiB
Python
693 lines
37 KiB
Python
|
|
"""Exercise the original CMVR HTTP/WS contracts against the new local service.
|
|||
|
|
|
|||
|
|
Creates clearly marked verification cases/tasks/instances and cleans them on success. Robot
|
|||
|
|
and map records created for CRUD checks are archived/deleted through their APIs.
|
|||
|
|
No hardware API is called. Database access is SELECT-only and is restricted to
|
|||
|
|
the explicitly designated am-freescan database from .local/runtime.json.
|
|||
|
|
|
|||
|
|
Reusable host-test helpers:
|
|||
|
|
client = Client(); client.login()
|
|||
|
|
verifier = NativeVerifier(client)
|
|||
|
|
case = verifier.create_published_case("host", 42, code=optional_js)
|
|||
|
|
"""
|
|||
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
import argparse
|
|||
|
|
import base64
|
|||
|
|
import datetime as dt
|
|||
|
|
import gzip
|
|||
|
|
import hashlib
|
|||
|
|
import json
|
|||
|
|
import os
|
|||
|
|
from pathlib import Path
|
|||
|
|
import secrets
|
|||
|
|
import socket
|
|||
|
|
import struct
|
|||
|
|
import sys
|
|||
|
|
import threading
|
|||
|
|
import time
|
|||
|
|
import urllib.error
|
|||
|
|
import urllib.parse
|
|||
|
|
import urllib.request
|
|||
|
|
import uuid
|
|||
|
|
|
|||
|
|
|
|||
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|||
|
|
sys.path.insert(0, str(ROOT / ".tools/python"))
|
|||
|
|
NATIVE = "/admin-api/cmvr"
|
|||
|
|
REMARK = "自动化原版CMVR验证记录;无硬件调用;通过后清理"
|
|||
|
|
|
|||
|
|
|
|||
|
|
def stamp():
|
|||
|
|
return dt.datetime.now(dt.timezone.utc).isoformat()
|
|||
|
|
|
|||
|
|
|
|||
|
|
def unique_prefix():
|
|||
|
|
return "CMVR_VERIFY_" + dt.datetime.now().strftime("%Y%m%d%H%M%S_") + secrets.token_hex(3)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def safe(value):
|
|||
|
|
if isinstance(value, dict):
|
|||
|
|
return {k: ("<redacted>" if any(x in k.lower() for x in
|
|||
|
|
("password", "token", "secret", "authorization")) else safe(v))
|
|||
|
|
for k, v in value.items()}
|
|||
|
|
if isinstance(value, (list, tuple)):
|
|||
|
|
return [safe(x) for x in value]
|
|||
|
|
return value
|
|||
|
|
|
|||
|
|
|
|||
|
|
def require(condition, message):
|
|||
|
|
if not condition:
|
|||
|
|
raise AssertionError(message)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def response_identifier(response):
|
|||
|
|
"""Source AjaxResult.success(String) writes returned IDs into msg, not data."""
|
|||
|
|
value = response.get("data")
|
|||
|
|
if value is None and isinstance(response.get("msg"), str):
|
|||
|
|
candidate = response["msg"]
|
|||
|
|
if len(candidate.replace("-", "")) == 32:
|
|||
|
|
try:
|
|||
|
|
uuid.UUID(candidate)
|
|||
|
|
value = candidate
|
|||
|
|
except ValueError:
|
|||
|
|
pass
|
|||
|
|
require(isinstance(value, str) and value, "Original API did not return an instance/copy ID")
|
|||
|
|
return value
|
|||
|
|
|
|||
|
|
|
|||
|
|
class Client:
|
|||
|
|
def __init__(self, base_url="http://127.0.0.1:48090", runtime_path=None):
|
|||
|
|
parsed = urllib.parse.urlparse(base_url)
|
|||
|
|
require(parsed.scheme == "http" and parsed.hostname in ("127.0.0.1", "localhost")
|
|||
|
|
and parsed.port == 48090 and parsed.path in ("", "/"),
|
|||
|
|
"Verification is restricted to the new local service on port 48090")
|
|||
|
|
self.base_url = base_url.rstrip("/")
|
|||
|
|
self.runtime_path = Path(runtime_path) if runtime_path else ROOT / ".local/runtime.json"
|
|||
|
|
self.runtime = json.loads(self.runtime_path.read_text(encoding="utf-8-sig"))
|
|||
|
|
mysql = self.runtime.get("mysql", {})
|
|||
|
|
require(mysql.get("database") == "am-freescan" and mysql.get("host") == "192.168.28.10",
|
|||
|
|
"Refusing a runtime configuration outside the designated target database")
|
|||
|
|
self._token = None
|
|||
|
|
self.user_id = 1
|
|||
|
|
self.events = []
|
|||
|
|
|
|||
|
|
def request(self, method, path, body=None, query=None, expected=(0, 200), auth=True):
|
|||
|
|
require(path.startswith("/admin-api/"), "Only explicit target API paths are allowed")
|
|||
|
|
if query:
|
|||
|
|
path += "?" + urllib.parse.urlencode(query)
|
|||
|
|
headers = {"tenant-id": "1", "Accept": "application/json"}
|
|||
|
|
if auth and self._token:
|
|||
|
|
headers["Authorization"] = "Bearer " + self._token
|
|||
|
|
data = None if body is None else json.dumps(body, ensure_ascii=False).encode("utf-8")
|
|||
|
|
if data is not None:
|
|||
|
|
headers["Content-Type"] = "application/json"
|
|||
|
|
request = urllib.request.Request(self.base_url + path, data=data, headers=headers, method=method)
|
|||
|
|
started = time.monotonic()
|
|||
|
|
try:
|
|||
|
|
with urllib.request.urlopen(request, timeout=25) as response:
|
|||
|
|
status, raw = response.status, response.read()
|
|||
|
|
except urllib.error.HTTPError as error:
|
|||
|
|
status, raw = error.code, error.read()
|
|||
|
|
try:
|
|||
|
|
result = json.loads(raw)
|
|||
|
|
except (ValueError, UnicodeDecodeError):
|
|||
|
|
raise AssertionError(f"{method} {path.split('?')[0]} returned non-JSON HTTP {status}")
|
|||
|
|
# Never record login response bodies or query tokens.
|
|||
|
|
self.events.append({"at": stamp(), "method": method, "path": path.split("?")[0],
|
|||
|
|
"httpStatus": status, "code": result.get("code"),
|
|||
|
|
"elapsedMs": round((time.monotonic() - started) * 1000)})
|
|||
|
|
if expected is not None:
|
|||
|
|
require(status < 400 and result.get("code") in expected,
|
|||
|
|
f"{method} {path.split('?')[0]} failed: HTTP {status}, "
|
|||
|
|
f"code {result.get('code')}, {result.get('msg', '')}")
|
|||
|
|
return result
|
|||
|
|
|
|||
|
|
def native(self, method, path, body=None, query=None, expected=(200,)):
|
|||
|
|
return self.request(method, NATIVE + path, body, query, expected)
|
|||
|
|
|
|||
|
|
def login(self):
|
|||
|
|
result = self.request("POST", "/admin-api/system/auth/login", {
|
|||
|
|
"username": "admin", "password": self.runtime.get("adminPassword", "admin123"),
|
|||
|
|
"captchaVerification": ""}, expected=(0,), auth=False)
|
|||
|
|
self._token = result["data"]["accessToken"]
|
|||
|
|
self.user_id = result["data"].get("userId", 1)
|
|||
|
|
return self
|
|||
|
|
|
|||
|
|
|
|||
|
|
class TargetReadOnlyDb:
|
|||
|
|
def __init__(self, client):
|
|||
|
|
import pymysql
|
|||
|
|
config = client.runtime["mysql"]
|
|||
|
|
self.connection = pymysql.connect(host=config["host"], port=int(config.get("port", 3306)),
|
|||
|
|
user=config["user"], password=config["password"], database=config["database"],
|
|||
|
|
charset="utf8mb4", cursorclass=pymysql.cursors.DictCursor, autocommit=True,
|
|||
|
|
connect_timeout=5, read_timeout=5, init_command="SET SESSION TRANSACTION READ ONLY")
|
|||
|
|
require(self.select("SELECT DATABASE() AS db")[0]["db"] == "am-freescan",
|
|||
|
|
"Connected database does not match the target")
|
|||
|
|
|
|||
|
|
def select(self, sql, params=()):
|
|||
|
|
require(sql.lstrip().upper().startswith("SELECT ") and ";" not in sql,
|
|||
|
|
"The verification database helper permits only one SELECT statement")
|
|||
|
|
with self.connection.cursor() as cursor:
|
|||
|
|
cursor.execute(sql, params)
|
|||
|
|
return cursor.fetchall()
|
|||
|
|
|
|||
|
|
def close(self):
|
|||
|
|
self.connection.close()
|
|||
|
|
|
|||
|
|
|
|||
|
|
class WebSocketProbe:
|
|||
|
|
"""Small RFC6455 client; supports original gzip binary notification messages."""
|
|||
|
|
def __init__(self, client, authenticated=True):
|
|||
|
|
self.client, self.authenticated = client, authenticated
|
|||
|
|
self.sock = None
|
|||
|
|
self.messages = []
|
|||
|
|
self.errors = []
|
|||
|
|
self.stop_event = threading.Event()
|
|||
|
|
self.buffer = bytearray()
|
|||
|
|
|
|||
|
|
def connect(self):
|
|||
|
|
key = base64.b64encode(os.urandom(16)).decode("ascii")
|
|||
|
|
query = {"userId": self.client.user_id}
|
|||
|
|
if self.authenticated:
|
|||
|
|
query["token"] = self.client._token
|
|||
|
|
path = NATIVE + "/ws?" + urllib.parse.urlencode(query)
|
|||
|
|
host = urllib.parse.urlparse(self.client.base_url).hostname
|
|||
|
|
self.sock = socket.create_connection((host, 48090), timeout=5)
|
|||
|
|
packet = (f"GET {path} HTTP/1.1\r\nHost: {host}:48090\r\nUpgrade: websocket\r\n"
|
|||
|
|
f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n"
|
|||
|
|
"tenant-id: 1\r\n\r\n")
|
|||
|
|
self.sock.sendall(packet.encode("ascii"))
|
|||
|
|
header = bytearray()
|
|||
|
|
while b"\r\n\r\n" not in header:
|
|||
|
|
chunk = self.sock.recv(4096)
|
|||
|
|
require(chunk, "WebSocket handshake closed without a response")
|
|||
|
|
header.extend(chunk)
|
|||
|
|
require(len(header) < 65536, "WebSocket response header is too large")
|
|||
|
|
raw_head, initial = bytes(header).split(b"\r\n\r\n", 1)
|
|||
|
|
status = int(raw_head.split(b" ", 2)[1])
|
|||
|
|
if not self.authenticated:
|
|||
|
|
self.sock.close()
|
|||
|
|
self.sock = None
|
|||
|
|
require(status != 101, "Unauthenticated WebSocket connection was accepted")
|
|||
|
|
return status
|
|||
|
|
require(status == 101, f"Authenticated WebSocket handshake returned HTTP {status}")
|
|||
|
|
expected_accept = base64.b64encode(hashlib.sha1(
|
|||
|
|
(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode("ascii")).digest())
|
|||
|
|
require(expected_accept.lower() in raw_head.lower(), "Invalid WebSocket handshake accept value")
|
|||
|
|
self.buffer.extend(initial)
|
|||
|
|
self.sock.settimeout(0.3)
|
|||
|
|
self.thread = threading.Thread(target=self._reader, daemon=True)
|
|||
|
|
self.thread.start()
|
|||
|
|
self.send({"type": "channel_subscription", "action": "subscribe",
|
|||
|
|
"channel": "AimaTaskInstance", "timestamp": int(time.time() * 1000)})
|
|||
|
|
time.sleep(0.1)
|
|||
|
|
return status
|
|||
|
|
|
|||
|
|
def _send_frame(self, opcode, payload):
|
|||
|
|
mask = os.urandom(4)
|
|||
|
|
header = bytes([0x80 | opcode])
|
|||
|
|
length = len(payload)
|
|||
|
|
header += bytes([0x80 | length]) if length < 126 else bytes([0x80 | 126]) + struct.pack("!H", length)
|
|||
|
|
masked = bytes(value ^ mask[index % 4] for index, value in enumerate(payload))
|
|||
|
|
self.sock.sendall(header + mask + masked)
|
|||
|
|
|
|||
|
|
def send(self, value):
|
|||
|
|
self._send_frame(1, json.dumps(value).encode("utf-8"))
|
|||
|
|
|
|||
|
|
def _exact(self, size):
|
|||
|
|
while len(self.buffer) < size:
|
|||
|
|
if self.stop_event.is_set():
|
|||
|
|
raise EOFError()
|
|||
|
|
try:
|
|||
|
|
chunk = self.sock.recv(max(4096, size - len(self.buffer)))
|
|||
|
|
except socket.timeout:
|
|||
|
|
continue
|
|||
|
|
if not chunk:
|
|||
|
|
raise EOFError()
|
|||
|
|
self.buffer.extend(chunk)
|
|||
|
|
result = bytes(self.buffer[:size])
|
|||
|
|
del self.buffer[:size]
|
|||
|
|
return result
|
|||
|
|
|
|||
|
|
def _reader(self):
|
|||
|
|
fragmented = bytearray()
|
|||
|
|
try:
|
|||
|
|
while not self.stop_event.is_set():
|
|||
|
|
first, second = self._exact(2)
|
|||
|
|
opcode, final, masked = first & 15, bool(first & 128), bool(second & 128)
|
|||
|
|
size = second & 127
|
|||
|
|
if size == 126:
|
|||
|
|
size = struct.unpack("!H", self._exact(2))[0]
|
|||
|
|
elif size == 127:
|
|||
|
|
size = struct.unpack("!Q", self._exact(8))[0]
|
|||
|
|
require(size <= 4 * 1024 * 1024, "Unexpected oversized WebSocket frame")
|
|||
|
|
mask = self._exact(4) if masked else None
|
|||
|
|
payload = self._exact(size)
|
|||
|
|
if mask:
|
|||
|
|
payload = bytes(value ^ mask[index % 4] for index, value in enumerate(payload))
|
|||
|
|
if opcode == 8:
|
|||
|
|
return
|
|||
|
|
if opcode == 9:
|
|||
|
|
self._send_frame(10, payload)
|
|||
|
|
continue
|
|||
|
|
if opcode not in (0, 1, 2):
|
|||
|
|
continue
|
|||
|
|
fragmented.extend(payload)
|
|||
|
|
if not final:
|
|||
|
|
continue
|
|||
|
|
data = bytes(fragmented)
|
|||
|
|
fragmented.clear()
|
|||
|
|
if data.startswith(b"\x1f\x8b"):
|
|||
|
|
data = gzip.decompress(data)
|
|||
|
|
try:
|
|||
|
|
self.messages.append(json.loads(data))
|
|||
|
|
except (ValueError, UnicodeDecodeError):
|
|||
|
|
self.errors.append("A notification frame was not JSON/gzip JSON")
|
|||
|
|
except (OSError, EOFError):
|
|||
|
|
pass
|
|||
|
|
except Exception as error:
|
|||
|
|
self.errors.append(str(error))
|
|||
|
|
|
|||
|
|
def close(self):
|
|||
|
|
self.stop_event.set()
|
|||
|
|
if self.sock:
|
|||
|
|
try:
|
|||
|
|
self._send_frame(8, b"")
|
|||
|
|
except OSError:
|
|||
|
|
pass
|
|||
|
|
self.sock.close()
|
|||
|
|
self.sock = None
|
|||
|
|
|
|||
|
|
|
|||
|
|
def make_flow(number, marker, sleep_ms=0, code=None):
|
|||
|
|
if code is None:
|
|||
|
|
code = ("function handler(params) { return {value: " + str(number)
|
|||
|
|
+ ", measurements: [{measurementKey: 'VALUE', featureName: '原生流程计算', value: "
|
|||
|
|
+ str(number) + ", judgment: 'PASS'}], params: params, marker: "
|
|||
|
|
+ json.dumps(marker, ensure_ascii=False) + "}; }")
|
|||
|
|
input_defs = [{"name": "factor", "type": "number", "input": "1", "required": False},
|
|||
|
|
{"name": "seed", "type": "number", "input": "0", "required": False}]
|
|||
|
|
for name in ("phoneId", "vehicleId", "taskInstanceId"):
|
|||
|
|
input_defs.append({"name": name, "type": "string", "input": "", "required": False})
|
|||
|
|
def node(node_id, kind, action, params=()):
|
|||
|
|
return {"id": node_id, "type": kind, "x": 120, "y": 100 + len(nodes) * 120,
|
|||
|
|
"properties": {"name": marker + "-" + node_id, "action": action,
|
|||
|
|
"inputParams": [], "nodeParams": list(params)}}
|
|||
|
|
nodes = []
|
|||
|
|
nodes.append(node("start", "start", "START"))
|
|||
|
|
nodes[0]["properties"]["inputParams"] = input_defs
|
|||
|
|
nodes[0]["properties"]["schemaVersion"] = 2
|
|||
|
|
nodes[0]["properties"]["resourceRoles"] = []
|
|||
|
|
if sleep_ms:
|
|||
|
|
nodes.append(node("sleep", "sleep", "SLEEP", [
|
|||
|
|
{"name": "delayMs", "type": "input", "input": str(sleep_ms)}]))
|
|||
|
|
params = [{"name": "code", "type": "input", "input": code}]
|
|||
|
|
params.extend({"name": name, "type": "quote", "quoteType": "input",
|
|||
|
|
"quote": ["start", "input", name]} for name in
|
|||
|
|
("factor", "seed", "phoneId", "vehicleId", "taskInstanceId"))
|
|||
|
|
nodes.append(node("code", "code", "CODE", params))
|
|||
|
|
nodes.append(node("end", "end", "END"))
|
|||
|
|
edges = [{"id": "edge-" + str(i), "sourceNodeId": nodes[i]["id"],
|
|||
|
|
"targetNodeId": nodes[i + 1]["id"],
|
|||
|
|
"sourceAnchorId": nodes[i]["id"] + "_out", "targetAnchorId": nodes[i + 1]["id"] + "_in"}
|
|||
|
|
for i in range(len(nodes) - 1)]
|
|||
|
|
return {"schemaVersion": 2, "nodes": nodes, "edges": edges}
|
|||
|
|
|
|||
|
|
|
|||
|
|
class NativeVerifier:
|
|||
|
|
def __init__(self, client, prefix=None):
|
|||
|
|
self.client = client
|
|||
|
|
self.prefix = prefix or unique_prefix()
|
|||
|
|
self.report = {"prefix": self.prefix, "startedAt": stamp(), "checks": [],
|
|||
|
|
"artifacts": [], "failures": [], "skipped": [],
|
|||
|
|
"retention": REMARK, "databaseAccess": "SELECT only; am-freescan"}
|
|||
|
|
self._db = None
|
|||
|
|
self.ws = None
|
|||
|
|
|
|||
|
|
@property
|
|||
|
|
def db(self):
|
|||
|
|
if self._db is None:
|
|||
|
|
self._db = TargetReadOnlyDb(self.client)
|
|||
|
|
return self._db
|
|||
|
|
|
|||
|
|
def checked(self, name, condition=True, **detail):
|
|||
|
|
require(condition, name + ": " + json.dumps(safe(detail), ensure_ascii=False, default=str))
|
|||
|
|
self.report["checks"].append({"name": name, "passed": True, **safe(detail)})
|
|||
|
|
print("PASS", name)
|
|||
|
|
|
|||
|
|
def artifact(self, kind, identifier, **detail):
|
|||
|
|
entry = {"kind": kind, "id": identifier, **detail}
|
|||
|
|
self.report["artifacts"].append(entry)
|
|||
|
|
return entry
|
|||
|
|
|
|||
|
|
def create_published_case(self, suffix, number, sleep_ms=0, code=None):
|
|||
|
|
case_id = uuid.uuid4().hex
|
|||
|
|
case_code = (self.prefix + "_" + suffix)[:49]
|
|||
|
|
case_name = case_code + " 原版验证"
|
|||
|
|
self.client.native("POST", "/aima/testcase", {"id": case_id, "caseCode": case_code,
|
|||
|
|
"caseName": case_name, "caseCategory": "功能测试", "testDescription": REMARK,
|
|||
|
|
"precondition": "无需硬件", "testSteps": "原版START/CODE/END流程",
|
|||
|
|
"expectedResult": "JS返回value和measurements", "priority": "2", "enabled": "0",
|
|||
|
|
"sortOrder": 1, "estimatedDuration": max(1, sleep_ms // 1000), "remark": REMARK})
|
|||
|
|
case = self.client.native("GET", "/aima/testcase/" + case_id)["data"]
|
|||
|
|
require(case and case.get("detectItemId"), "Native case did not create its linked detection item")
|
|||
|
|
item_id = case["detectItemId"]
|
|||
|
|
version = self.publish(item_id, make_flow(number, case_code, sleep_ms, code), "initial")
|
|||
|
|
result = {"caseId": case_id, "detectItemId": item_id, "versionId": version["id"],
|
|||
|
|
"versionNo": version["versionNo"], "caseCode": case_code, "caseName": case_name,
|
|||
|
|
"flowData": version["flowData"], "expectedValue": number}
|
|||
|
|
self.artifact("aima-testcase", case_id, detectItemId=item_id, versionId=version["id"], caseCode=case_code)
|
|||
|
|
return result
|
|||
|
|
|
|||
|
|
def publish(self, item_id, graph, note):
|
|||
|
|
item = self.client.native("GET", "/test/detect/" + item_id)["data"]
|
|||
|
|
saved = self.client.native("PUT", "/flow/draft", {"id": item_id,
|
|||
|
|
"flowData": json.dumps(graph, ensure_ascii=False, separators=(",", ":")), "config": {},
|
|||
|
|
"draftRevision": item.get("draftRevision", 0)})["data"]
|
|||
|
|
return self.client.native("POST", "/flow/publish", {"id": item_id,
|
|||
|
|
"draftRevision": saved.get("draftRevision", 0), "publishNote": REMARK + " " + note})["data"]
|
|||
|
|
|
|||
|
|
def create_task(self, suffix, case_ids):
|
|||
|
|
task_id = uuid.uuid4().hex
|
|||
|
|
self.client.native("POST", "/aima/task", {"id": task_id,
|
|||
|
|
"taskCode": (self.prefix + "_" + suffix)[:49], "taskName": self.prefix + " " + suffix,
|
|||
|
|
"taskType": "1", "remark": REMARK})
|
|||
|
|
self.client.native("POST", "/aima/task/bindTestCases/" + task_id, case_ids)
|
|||
|
|
task = self.client.native("GET", "/aima/task/" + task_id)["data"]
|
|||
|
|
self.artifact("aima-task", task_id, taskConfigId=task.get("taskConfigId"))
|
|||
|
|
return task
|
|||
|
|
|
|||
|
|
def create_instance(self, task_id, suffix, execution_number=1):
|
|||
|
|
instance_id = uuid.uuid4().hex
|
|||
|
|
self.client.native("POST", "/aima/taskinstance", {"id": instance_id, "taskId": task_id,
|
|||
|
|
"executionNumber": execution_number, "remark": REMARK + " " + suffix})
|
|||
|
|
self.artifact("aima-instance", instance_id, taskId=task_id)
|
|||
|
|
return instance_id
|
|||
|
|
|
|||
|
|
def wait_instance(self, instance_id, expected=0, timeout=30):
|
|||
|
|
deadline = time.monotonic() + timeout
|
|||
|
|
while time.monotonic() < deadline:
|
|||
|
|
row = self.client.native("GET", "/aima/taskinstance/" + instance_id)["data"]
|
|||
|
|
if row and int(row["status"]) == expected:
|
|||
|
|
return row
|
|||
|
|
if row and int(row["status"]) in (0, 2, 4) and int(row["status"]) != expected:
|
|||
|
|
raise AssertionError(f"AIMA instance {instance_id} ended at unexpected status {row['status']}")
|
|||
|
|
time.sleep(0.15)
|
|||
|
|
raise AssertionError(f"AIMA instance {instance_id} did not reach status {expected} within {timeout}s")
|
|||
|
|
|
|||
|
|
def node_logs(self, instance_id):
|
|||
|
|
return self.client.native("GET", "/test/inst/log/detail", query={
|
|||
|
|
"instId": instance_id, "pageNum": 1, "pageSize": 500})["rows"]
|
|||
|
|
|
|||
|
|
def code_results(self, instance_id):
|
|||
|
|
results = []
|
|||
|
|
for row in sorted(self.node_logs(instance_id), key=lambda item: int(item["id"])):
|
|||
|
|
if row.get("action") == "CODE" and row.get("paramsOut"):
|
|||
|
|
output = row["paramsOut"]
|
|||
|
|
if isinstance(output, str):
|
|||
|
|
output = json.loads(output)
|
|||
|
|
if isinstance(output, dict) and "result" in output:
|
|||
|
|
results.append(output["result"])
|
|||
|
|
return results
|
|||
|
|
|
|||
|
|
def wait_native(self, native_id, expected=0, timeout=30):
|
|||
|
|
deadline = time.monotonic() + timeout
|
|||
|
|
while time.monotonic() < deadline:
|
|||
|
|
rows = self.db.select("SELECT id,status,run_mode,config FROM te_task_inst WHERE id=%s", (native_id,))
|
|||
|
|
if rows and int(rows[0]["status"]) == expected:
|
|||
|
|
return rows[0]
|
|||
|
|
if rows and int(rows[0]["status"]) in (0, 2, 4) and int(rows[0]["status"]) != expected:
|
|||
|
|
raise AssertionError(f"Native workflow {native_id} ended at status {rows[0]['status']}")
|
|||
|
|
time.sleep(0.15)
|
|||
|
|
raise AssertionError(f"Native workflow {native_id} did not reach status {expected}")
|
|||
|
|
|
|||
|
|
def verify_workflow(self):
|
|||
|
|
case = self.create_published_case("case", 42)
|
|||
|
|
case_id, item_id = case["caseId"], case["detectItemId"]
|
|||
|
|
edited = self.client.native("GET", "/aima/testcase/" + case_id)["data"]
|
|||
|
|
edited["testDescription"] = REMARK + " 已通过编辑接口更新"
|
|||
|
|
self.client.native("PUT", "/aima/testcase", edited)
|
|||
|
|
self.checked("原用例新增及编辑同步检测项", self.client.native("GET", "/aima/testcase/" + case_id)
|
|||
|
|
["data"]["testDescription"] == edited["testDescription"], caseId=case_id, itemId=item_id)
|
|||
|
|
copied_id = response_identifier(self.client.native("POST", "/aima/testcase/copy/" + case_id))
|
|||
|
|
copy = self.client.native("GET", "/aima/testcase/" + copied_id)["data"]
|
|||
|
|
copied_item = self.client.native("GET", "/test/detect/" + copy["detectItemId"])["data"]
|
|||
|
|
self.checked("复制用例同时复制独立流程草稿", copied_id != case_id
|
|||
|
|
and copy["detectItemId"] != item_id
|
|||
|
|
and json.loads(copied_item["flowData"]) == json.loads(case["flowData"]))
|
|||
|
|
self.artifact("aima-testcase-copy", copied_id, detectItemId=copy["detectItemId"])
|
|||
|
|
task = self.create_task("duplicate-order", [case_id, case_id])
|
|||
|
|
bound = self.client.native("GET", "/aima/task/testCases/" + task["id"])["data"]
|
|||
|
|
self.checked("原任务保留相同用例的重复顺序", [entry["id"] for entry in bound] == [case_id, case_id])
|
|||
|
|
copied_task_id = response_identifier(self.client.native("POST", "/aima/task/copy/" + task["id"]))
|
|||
|
|
copied_task = self.client.native("GET", "/aima/task/" + copied_task_id)["data"]
|
|||
|
|
copied_bindings = self.client.native("GET", "/aima/task/testCases/" + copied_task_id)["data"]
|
|||
|
|
self.checked("复制原任务保留重复绑定并隔离原生编排", copied_task_id != task["id"]
|
|||
|
|
and copied_task["taskConfigId"] != task["taskConfigId"]
|
|||
|
|
and [entry["id"] for entry in copied_bindings] == [case_id, case_id])
|
|||
|
|
self.artifact("aima-task-copy", copied_task_id, taskConfigId=copied_task["taskConfigId"])
|
|||
|
|
params = {item_id + ":1": {"seed": 101, "factor": 2},
|
|||
|
|
item_id + ":2": {"seed": 202, "factor": 3}}
|
|||
|
|
instance_id = self.create_instance(task["id"], "normal")
|
|||
|
|
self.client.native("PUT", "/aima/taskinstance/start/" + instance_id, {"runParams": params})
|
|||
|
|
finished = self.wait_instance(instance_id)
|
|||
|
|
native_id = finished["taskInsId"]
|
|||
|
|
results = self.code_results(native_id)
|
|||
|
|
self.checked("原NORMAL引擎执行两个JS并保留每次运行参数", len(results) == 2
|
|||
|
|
and [row["value"] for row in results] == [42, 42]
|
|||
|
|
and [row["params"]["seed"] for row in results] == [101, 202]
|
|||
|
|
and [row["params"]["factor"] for row in results] == [2, 3]
|
|||
|
|
and all(row["params"]["taskInstanceId"] == instance_id for row in results),
|
|||
|
|
instanceId=instance_id, nativeId=native_id, results=results)
|
|||
|
|
log_rows = self.client.native("GET", "/aima/testlog/list", query={
|
|||
|
|
"taskInstanceId": instance_id, "pageNum": 1, "pageSize": 500})["rows"]
|
|||
|
|
occurrences = {int(row["itemOccurrence"]) for row in log_rows if row.get("itemOccurrence") is not None}
|
|||
|
|
self.checked("AIMA监听器写入结果和重复用例出现序号", {1, 2}.issubset(occurrences),
|
|||
|
|
logCount=len(log_rows), occurrences=sorted(occurrences))
|
|||
|
|
manifest = self.db.select("SELECT item_id,item_order,item_occurrence,version_id FROM "
|
|||
|
|
"te_task_inst_flow_version WHERE inst_id=%s ORDER BY item_order", (native_id,))
|
|||
|
|
self.checked("正式实例持久化有序发布版本清单", len(manifest) == 2
|
|||
|
|
and [row["item_occurrence"] for row in manifest] == [1, 2]
|
|||
|
|
and all(row["version_id"] == case["versionId"] for row in manifest))
|
|||
|
|
|
|||
|
|
rerun_id = response_identifier(self.client.native("POST", "/aima/taskinstance/rerun/" + instance_id))
|
|||
|
|
rerun = self.wait_instance(rerun_id)
|
|||
|
|
rerun_results = self.code_results(rerun["taskInsId"])
|
|||
|
|
self.checked("原AIMA再次执行创建新实例并复用运行参数快照", rerun_id != instance_id
|
|||
|
|
and rerun["executionNumber"] == 2 and len(rerun_results) == 2
|
|||
|
|
and [row["params"]["seed"] for row in rerun_results] == [101, 202])
|
|||
|
|
self.artifact("aima-rerun-instance", rerun_id, nativeId=rerun["taskInsId"])
|
|||
|
|
if self.ws:
|
|||
|
|
deadline = time.monotonic() + 3
|
|||
|
|
while time.monotonic() < deadline and not any(
|
|||
|
|
message.get("payload", {}).get("taskInstanceId") == instance_id
|
|||
|
|
for message in self.ws.messages if isinstance(message.get("payload"), dict)):
|
|||
|
|
time.sleep(0.1)
|
|||
|
|
notifications = [message for message in self.ws.messages if
|
|||
|
|
isinstance(message.get("payload"), dict) and message["payload"].get("taskInstanceId") == instance_id]
|
|||
|
|
self.checked("原WebSocket订阅收到AIMA执行通知", bool(notifications), messageCount=len(notifications))
|
|||
|
|
|
|||
|
|
def verify_frozen_workflow(self):
|
|||
|
|
# This is independent of AIMA/log assertions so a regression cannot hide frozen execution coverage.
|
|||
|
|
case = self.create_published_case("frozen", 42)
|
|||
|
|
item_id = case["detectItemId"]
|
|||
|
|
task = self.create_task("frozen-order", [case["caseId"], case["caseId"]])
|
|||
|
|
params = {item_id + ":1": {"seed": 101, "factor": 2},
|
|||
|
|
item_id + ":2": {"seed": 202, "factor": 3}}
|
|||
|
|
v2 = self.publish(item_id, make_flow(43, self.prefix + "-v2"), "newer-version")
|
|||
|
|
versions = self.client.native("GET", "/flow/versions/" + item_id)["data"]
|
|||
|
|
self.checked("草稿发布生成独立版本且旧版内容不变", len(versions) >= 2
|
|||
|
|
and v2["id"] != case["versionId"]
|
|||
|
|
and self.client.native("GET", "/flow/version/" + case["versionId"])["data"]["flowData"]
|
|||
|
|
== case["flowData"])
|
|||
|
|
frozen_id = response_identifier(self.client.native("POST", "/flow/execute", {
|
|||
|
|
"taskId": task["taskConfigId"], "moduleCode": "CMVR_NATIVE_VERIFY",
|
|||
|
|
"runParams": params, "frozenVersionIds": [case["versionId"], case["versionId"]]}))
|
|||
|
|
native_row = self.wait_native(frozen_id)
|
|||
|
|
frozen_results = self.code_results(frozen_id)
|
|||
|
|
frozen_manifest = self.db.select("SELECT version_id FROM te_task_inst_flow_version "
|
|||
|
|
"WHERE inst_id=%s ORDER BY item_order", (frozen_id,))
|
|||
|
|
self.checked("存在新发布版时仍以原NORMAL引擎执行冻结旧版", native_row["run_mode"] == "NORMAL"
|
|||
|
|
and len(frozen_results) == 2 and all(row["value"] == 42 for row in frozen_results)
|
|||
|
|
and all(row["version_id"] == case["versionId"] for row in frozen_manifest), nativeId=frozen_id)
|
|||
|
|
self.artifact("frozen-native-instance", frozen_id, versionId=case["versionId"])
|
|||
|
|
frozen_rerun = response_identifier(self.client.native("POST", "/test/inst/rerun/" + frozen_id))
|
|||
|
|
frozen_rerun_row = self.wait_native(frozen_rerun)
|
|||
|
|
frozen_rerun_results = self.code_results(frozen_rerun)
|
|||
|
|
frozen_request = json.loads(frozen_rerun_row["config"])
|
|||
|
|
self.checked("原引擎再次执行保留冻结版本快照", len(frozen_rerun_results) == 2
|
|||
|
|
and all(row["value"] == 42 for row in frozen_rerun_results)
|
|||
|
|
and frozen_request["frozenVersionIds"] == [case["versionId"], case["versionId"]])
|
|||
|
|
self.artifact("frozen-native-rerun", frozen_rerun, versionId=case["versionId"])
|
|||
|
|
|
|||
|
|
def wait_sleep(self, aima_id, timeout=8):
|
|||
|
|
deadline = time.monotonic() + timeout
|
|||
|
|
while time.monotonic() < deadline:
|
|||
|
|
row = self.client.native("GET", "/aima/taskinstance/" + aima_id)["data"]
|
|||
|
|
if row.get("taskInsId") and any(log.get("action") == "SLEEP" and str(log.get("status"))
|
|||
|
|
in ("RUNNING", "1") for log in self.node_logs(row["taskInsId"])):
|
|||
|
|
return row["taskInsId"]
|
|||
|
|
time.sleep(0.1)
|
|||
|
|
raise AssertionError("The control test did not enter the SLEEP node")
|
|||
|
|
|
|||
|
|
def verify_controls(self):
|
|||
|
|
case = self.create_published_case("controls", 77, sleep_ms=6000)
|
|||
|
|
task = self.create_task("controls", [case["caseId"]])
|
|||
|
|
instance_id = self.create_instance(task["id"], "pause-resume")
|
|||
|
|
self.client.native("PUT", "/aima/taskinstance/start/" + instance_id, {})
|
|||
|
|
native_id = self.wait_sleep(instance_id)
|
|||
|
|
self.client.native("PUT", "/aima/taskinstance/pause/" + instance_id)
|
|||
|
|
self.wait_instance(instance_id, expected=3)
|
|||
|
|
time.sleep(0.25)
|
|||
|
|
self.checked("原任务暂停阻止后续代码执行", not self.code_results(native_id), nativeId=native_id)
|
|||
|
|
self.client.native("PUT", "/aima/taskinstance/resume/" + instance_id)
|
|||
|
|
self.wait_instance(instance_id, expected=0, timeout=25)
|
|||
|
|
self.checked("原任务恢复后完成原流程", [row["value"] for row in self.code_results(native_id)] == [77])
|
|||
|
|
stopped_id = self.create_instance(task["id"], "stop")
|
|||
|
|
self.client.native("PUT", "/aima/taskinstance/start/" + stopped_id, {})
|
|||
|
|
stopped_native = self.wait_sleep(stopped_id)
|
|||
|
|
self.client.native("PUT", "/aima/taskinstance/stop/" + stopped_id)
|
|||
|
|
self.wait_instance(stopped_id, expected=4)
|
|||
|
|
self.wait_native(stopped_native, expected=4)
|
|||
|
|
self.checked("原任务终止同时持久化业务及引擎状态", not self.code_results(stopped_native), nativeId=stopped_native)
|
|||
|
|
|
|||
|
|
def verify_resources(self):
|
|||
|
|
robot_id = self.prefix.lower() + "_robot"
|
|||
|
|
self.client.native("POST", "/resource/robots", {"robotId": robot_id, "robotCode": self.prefix,
|
|||
|
|
"robotName": self.prefix + " 离线资源验证", "robotType": "OTHER", "remark": REMARK})
|
|||
|
|
robot = self.client.native("GET", "/resource/robots/" + robot_id)["data"]
|
|||
|
|
self.artifact("archived-test-robot", robot["id"], robotId=robot_id)
|
|||
|
|
self.checked("登记机器人保持离线且没有硬件地址", robot["connectStatus"] == "0"
|
|||
|
|
and not robot.get("ipAddress") and robot.get("port") is None)
|
|||
|
|
robot["robotName"] += " 已编辑"
|
|||
|
|
self.client.native("PUT", "/resource/robots", robot)
|
|||
|
|
self.checked("原机器人业务配置可修改", self.client.native("GET", "/resource/robots/id/" + robot["id"])
|
|||
|
|
["data"]["robotName"] == robot["robotName"])
|
|||
|
|
self.client.native("POST", "/resource/maps", {"mapName": self.prefix + "_map", "mapVersion": "1",
|
|||
|
|
"mapType": "2D", "coordinateSystem": "map", "sourceType": "OTHER", "status": "0", "remark": REMARK})
|
|||
|
|
maps = self.client.native("GET", "/resource/maps", query={"mapName": self.prefix + "_map"})["rows"]
|
|||
|
|
selected = [entry for entry in maps if entry["mapName"] == self.prefix + "_map"]
|
|||
|
|
require(len(selected) == 1, "Created verification map was not found uniquely")
|
|||
|
|
map_row = selected[0]
|
|||
|
|
self.artifact("deleted-test-map", map_row["id"], mapName=map_row["mapName"])
|
|||
|
|
map_row["mapVersion"] = "2"
|
|||
|
|
self.client.native("PUT", "/resource/maps", map_row)
|
|||
|
|
self.checked("原地图新增读取及编辑", self.client.native("GET", "/resource/maps/" + map_row["id"])
|
|||
|
|
["data"]["mapVersion"] == "2")
|
|||
|
|
self.client.native("POST", "/resource/robots/" + robot_id + "/maps/" + map_row["id"])
|
|||
|
|
bound = self.client.native("GET", "/resource/robots/" + robot_id + "/maps")["data"]
|
|||
|
|
self.checked("机器人地图关系可绑定查询", any(row.get("id") == map_row["id"] or row.get("mapId")
|
|||
|
|
== map_row["id"] for row in bound))
|
|||
|
|
self.client.native("DELETE", "/resource/robots/" + robot_id + "/maps/" + map_row["id"])
|
|||
|
|
self.client.native("DELETE", "/resource/maps/" + map_row["id"])
|
|||
|
|
self.client.native("DELETE", "/resource/robots/" + robot["id"])
|
|||
|
|
archived = self.client.native("GET", "/resource/robots/id/" + robot["id"])["data"]
|
|||
|
|
self.checked("原地图删除及机器人归档", archived["archivedStatus"] == "1"
|
|||
|
|
and self.client.native("GET", "/resource/maps/" + map_row["id"]).get("data") is None)
|
|||
|
|
devices = self.client.native("GET", "/resource/devices", query={"onlineOnly": "false",
|
|||
|
|
"pageNum": 1, "pageSize": 100})
|
|||
|
|
self.checked("原设备自动发现资源可读取", isinstance(devices.get("rows"), list))
|
|||
|
|
own_devices = [entry for entry in devices["rows"] if str(entry.get("robotId", "")).startswith(self.prefix.lower())]
|
|||
|
|
if own_devices:
|
|||
|
|
device = own_devices[0]
|
|||
|
|
self.client.native("PUT", "/resource/devices/" + device["id"], {"deviceName": self.prefix + " device",
|
|||
|
|
"deviceRole": "verification", "enabled": "0"})
|
|||
|
|
self.checked("仅修改本轮前缀对应的自动发现设备", self.client.native("GET", "/resource/devices/" + device["id"])
|
|||
|
|
["data"]["enabled"] == "0")
|
|||
|
|
else:
|
|||
|
|
self.report["skipped"].append({"name": "设备业务配置PUT", "reason":
|
|||
|
|
"原设备由真实QUIC发现;没有本轮已发现测试设备。原API没有POST/DELETE,未造设备或改真实设备。"})
|
|||
|
|
|
|||
|
|
def run(self, websocket=True):
|
|||
|
|
self.client.native("GET", "/aima/testcase/list", query={"pageNum": 1, "pageSize": 1})
|
|||
|
|
self.db.select("SELECT COUNT(*) AS count FROM te_detection_item")
|
|||
|
|
self.checked("目标原版API及新数据库就绪")
|
|||
|
|
anonymous = self.client.request("GET", NATIVE + "/aima/testcase/list", expected=None, auth=False)
|
|||
|
|
self.checked("原版接口拒绝匿名访问", anonymous.get("code") == 401)
|
|||
|
|
if websocket:
|
|||
|
|
try:
|
|||
|
|
status = WebSocketProbe(self.client, authenticated=False).connect()
|
|||
|
|
self.checked("WebSocket拒绝匿名握手", status != 101, httpStatus=status)
|
|||
|
|
self.ws = WebSocketProbe(self.client)
|
|||
|
|
self.checked("WebSocket用宿主token完成认证握手", self.ws.connect() == 101)
|
|||
|
|
except Exception as error:
|
|||
|
|
self.report["failures"].append({"scenario": "WebSocket认证", "error": str(error)})
|
|||
|
|
self.ws = None
|
|||
|
|
for label, callback in (("原智能检测闭环", self.verify_workflow),
|
|||
|
|
("独立冻结发布版本与再次执行", self.verify_frozen_workflow),
|
|||
|
|
("原暂停恢复终止", self.verify_controls),
|
|||
|
|
("原资源中心CRUD", self.verify_resources)):
|
|||
|
|
try:
|
|||
|
|
callback()
|
|||
|
|
except Exception as error:
|
|||
|
|
self.report["failures"].append({"scenario": label, "error": str(error)})
|
|||
|
|
print("FAIL", label, str(error))
|
|||
|
|
return self.report
|
|||
|
|
|
|||
|
|
def close(self):
|
|||
|
|
if self.ws:
|
|||
|
|
self.ws.close()
|
|||
|
|
if self._db:
|
|||
|
|
self._db.close()
|
|||
|
|
|
|||
|
|
|
|||
|
|
def create_published_case(suffix, number, client=None, prefix=None, sleep_ms=0, code=None):
|
|||
|
|
client = client or Client().login()
|
|||
|
|
return NativeVerifier(client, prefix).create_published_case(suffix, number, sleep_ms, code)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def main():
|
|||
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|||
|
|
parser.add_argument("--base-url", default="http://127.0.0.1:48090")
|
|||
|
|
parser.add_argument("--runtime", type=Path, default=ROOT / ".local/runtime.json")
|
|||
|
|
parser.add_argument("--report", type=Path)
|
|||
|
|
parser.add_argument("--no-websocket", action="store_true")
|
|||
|
|
parser.add_argument("--wait-ready", type=float, default=0,
|
|||
|
|
help="Retry local login during server startup for this many seconds")
|
|||
|
|
args = parser.parse_args()
|
|||
|
|
verifier = None
|
|||
|
|
prefix = unique_prefix()
|
|||
|
|
report_path = args.report or ROOT / ".local" / (prefix.lower() + ".json")
|
|||
|
|
report = {"prefix": prefix, "startedAt": stamp(), "failures": []}
|
|||
|
|
try:
|
|||
|
|
client = Client(args.base_url, args.runtime)
|
|||
|
|
deadline = time.monotonic() + args.wait_ready
|
|||
|
|
while True:
|
|||
|
|
try:
|
|||
|
|
client.login()
|
|||
|
|
break
|
|||
|
|
except (urllib.error.URLError, TimeoutError, ConnectionError):
|
|||
|
|
if time.monotonic() >= deadline:
|
|||
|
|
raise
|
|||
|
|
time.sleep(1)
|
|||
|
|
verifier = NativeVerifier(client, prefix)
|
|||
|
|
report = verifier.run(websocket=not args.no_websocket)
|
|||
|
|
if not report.get('failures'):
|
|||
|
|
from cleanup_verification import cleanup
|
|||
|
|
report['cleanup'] = cleanup([prefix], apply=True)
|
|||
|
|
except Exception as error:
|
|||
|
|
if verifier:
|
|||
|
|
report = verifier.report
|
|||
|
|
report["failures"].append({"scenario": "preflight", "error": str(error)})
|
|||
|
|
print("FAIL preflight", str(error))
|
|||
|
|
finally:
|
|||
|
|
if verifier:
|
|||
|
|
verifier.close()
|
|||
|
|
report["requests"] = verifier.client.events
|
|||
|
|
report["finishedAt"] = stamp()
|
|||
|
|
report["passed"] = not report["failures"]
|
|||
|
|
report_path.parent.mkdir(parents=True, exist_ok=True)
|
|||
|
|
if not report['passed'] or args.report:
|
|||
|
|
report_path.write_text(json.dumps(safe(report), ensure_ascii=False, indent=2, default=str), encoding="utf-8")
|
|||
|
|
else:
|
|||
|
|
report_path.unlink(missing_ok=True)
|
|||
|
|
print(json.dumps({"passed": report["passed"], "checks": len(report.get("checks", [])),
|
|||
|
|
"failures": len(report["failures"]), "report": str(report_path)}, ensure_ascii=False))
|
|||
|
|
return 0 if report["passed"] else 1
|
|||
|
|
|
|||
|
|
|
|||
|
|
if __name__ == "__main__":
|
|||
|
|
raise SystemExit(main())
|