verify-node.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. #!/usr/bin/env python3
  2. """Run one node verification case against the live SmartBotic services.
  3. Usage: scripts/verify-node.py tests/nodes/<case>.json
  4. Exit 0 if every assertion holds, 1 if one does not, 2 if the case declares a
  5. precondition this machine does not meet - reported as a skip, never as a pass.
  6. """
  7. import base64
  8. import json
  9. import sys
  10. import time
  11. import urllib.error
  12. import urllib.parse
  13. import urllib.request
  14. BASE = "http://localhost:8090/api/v1"
  15. def call(method, path, token=None, body=None):
  16. data = json.dumps(body).encode() if body is not None else None
  17. req = urllib.request.Request(BASE + path, data=data, method=method)
  18. req.add_header("Content-Type", "application/json")
  19. if token:
  20. req.add_header("Authorization", "Bearer " + token)
  21. try:
  22. with urllib.request.urlopen(req, timeout=30) as res:
  23. raw = res.read()
  24. return json.loads(raw) if raw else {}
  25. except urllib.error.HTTPError as e:
  26. raise SystemExit(f"{method} {path} failed: {e.code} {e.read().decode()[:400]}")
  27. def login():
  28. return call("POST", "/auth/login", body={"username": "admin", "password": "admin"})["accessToken"]
  29. def subset_matches(expected, actual, path):
  30. """Every key in expected must be present and equal in actual. Returns list of failures."""
  31. fails = []
  32. if isinstance(expected, dict):
  33. if not isinstance(actual, dict):
  34. return [f"{path}: expected an object, got {type(actual).__name__}"]
  35. for key, want in expected.items():
  36. if key not in actual:
  37. fails.append(f"{path}.{key}: missing")
  38. else:
  39. fails += subset_matches(want, actual[key], f"{path}.{key}")
  40. elif isinstance(expected, list):
  41. if not isinstance(actual, list):
  42. return [f"{path}: expected a list, got {type(actual).__name__}"]
  43. if len(expected) != len(actual):
  44. fails.append(f"{path}: expected {len(expected)} items, got {len(actual)}")
  45. else:
  46. for i, want in enumerate(expected):
  47. fails += subset_matches(want, actual[i], f"{path}[{i}]")
  48. elif expected != actual:
  49. fails.append(f"{path}: expected {expected!r}, got {actual!r}")
  50. return fails
  51. def run_http_case(case, token, workflow_id):
  52. """A webhook case asserts on the HTTP response, not on node outputs."""
  53. spec = case["http"]
  54. url = BASE.replace("/api/v1", "") + spec["path"].replace("{workflowId}", workflow_id)
  55. method = spec.get("method", "POST")
  56. multipart = spec.get("multipart")
  57. form_body = spec.get("formBody")
  58. if form_body is not None:
  59. # application/x-www-form-urlencoded, not JSON - cpp-httplib only
  60. # fills req.params (what handleWebhook's password check reads via
  61. # req.has_param) from a urlencoded body. A JSON body never reaches
  62. # that check, and multipart puts non-file parts in req.files instead
  63. # of req.params, so neither can exercise the password gate's
  64. # success path - only this can.
  65. payload = urllib.parse.urlencode(form_body).encode()
  66. req = urllib.request.Request(url, data=payload, method="POST")
  67. req.add_header("Content-Type", "application/x-www-form-urlencoded")
  68. elif multipart:
  69. boundary = "----smartboticverify"
  70. parts = []
  71. for name, value in multipart.get("fields", {}).items():
  72. parts.append(
  73. '--%s\r\nContent-Disposition: form-data; name="%s"\r\n\r\n%s\r\n' % (boundary, name, value))
  74. for name, f in multipart.get("files", {}).items():
  75. # A tiny real PNG, so the payload is genuinely binary rather than text
  76. # that happens to be labelled as an image.
  77. blob = base64.b64decode(
  78. "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==")
  79. head = ('--%s\r\nContent-Disposition: form-data; name="%s"; filename="%s"\r\n'
  80. 'Content-Type: %s\r\n\r\n' % (boundary, name, f.get("filename", "upload.png"),
  81. f.get("contentType", "image/png")))
  82. parts.append(head.encode() + blob + b"\r\n")
  83. payload = b"".join(p.encode() if isinstance(p, str) else p for p in parts)
  84. payload += ("--%s--\r\n" % boundary).encode()
  85. req = urllib.request.Request(url, data=payload, method="POST")
  86. req.add_header("Content-Type", "multipart/form-data; boundary=%s" % boundary)
  87. else:
  88. data = None
  89. if method in ("POST", "PUT", "PATCH"):
  90. body = spec.get("body", {})
  91. pad = spec.get("bodyPadBytes", 0)
  92. if pad:
  93. body = dict(body)
  94. body["_pad"] = "x" * pad
  95. data = json.dumps(body).encode()
  96. req = urllib.request.Request(url, data=data, method=method)
  97. if data is not None:
  98. req.add_header("Content-Type", "application/json")
  99. failures = []
  100. try:
  101. with urllib.request.urlopen(req, timeout=45) as res:
  102. status, headers, raw = res.status, dict(res.headers), res.read().decode()
  103. except urllib.error.HTTPError as e:
  104. status, headers, raw = e.code, dict(e.headers), e.read().decode()
  105. print("http: %s %s -> %s" % (spec.get("method", "POST"), spec["path"], status))
  106. print(" body: %s" % raw[:200])
  107. if "expectStatus" in spec and status != spec["expectStatus"]:
  108. failures.append("status: expected %s, got %s" % (spec["expectStatus"], status))
  109. for name, want in spec.get("expectHeaders", {}).items():
  110. got = headers.get(name)
  111. if got is None:
  112. failures.append("header %s: missing" % name)
  113. elif want not in got:
  114. failures.append("header %s: expected to contain %r, got %r" % (name, want, got))
  115. for fragment in spec.get("expectBodyContains", []):
  116. if fragment not in raw:
  117. failures.append("body: expected to contain %r" % fragment)
  118. for fragment in spec.get("expectBodyExcludes", []):
  119. if fragment in raw:
  120. failures.append("body: expected NOT to contain %r" % fragment)
  121. return failures
  122. def run_resume_case(case, token, execution_id):
  123. """Wait for the execution to pause, answer it, then let it finish."""
  124. spec = case["resume"]
  125. want_status = spec.get("waitForStatus", "waiting")
  126. execution = {}
  127. for _ in range(60):
  128. time.sleep(0.5)
  129. execution = call("GET", "/executions/%s" % execution_id, token)
  130. if execution.get("status") == want_status:
  131. break
  132. if execution.get("status") in ("completed", "failed", "cancelled"):
  133. raise SystemExit(
  134. "execution %s reached %s without pausing" % (execution_id, execution.get("status")))
  135. else:
  136. raise SystemExit("execution %s never reached %s" % (execution_id, want_status))
  137. by_id = {n["nodeId"]: n for n in execution.get("nodeExecutions", [])}
  138. source = by_id.get(spec["tokenFrom"])
  139. if not source:
  140. raise SystemExit("resume: node %s did not run" % spec["tokenFrom"])
  141. resume_token = (source.get("output") or {}).get("token")
  142. if not resume_token:
  143. raise SystemExit("resume: node %s produced no token" % spec["tokenFrom"])
  144. body = dict(spec.get("payload", {}))
  145. body["token"] = resume_token
  146. call("POST", "/executions/%s/resume" % execution_id, token, body)
  147. print("resumed %s with token %s" % (execution_id, resume_token))
  148. def precondition_unmet(case):
  149. """Why this case cannot run here, or None if it can.
  150. A couple of cases need a model loaded on the SD.cpp server, which unloads
  151. itself when idle. Without this they fail for a reason that has nothing to do
  152. with the code, and a failure everyone learns to ignore is worse than no
  153. test. Skipping is only honest because it is reported as a skip - never as a
  154. pass.
  155. """
  156. needs = case.get("requires")
  157. if not needs:
  158. return None
  159. probe = needs.get("http")
  160. if probe:
  161. try:
  162. with urllib.request.urlopen(probe, timeout=10) as response:
  163. body = json.loads(response.read().decode())
  164. except Exception as exc:
  165. return f"{probe} could not be read ({exc})"
  166. for path, expected in (needs.get("expect") or {}).items():
  167. actual = body
  168. for part in path.split("."):
  169. actual = (actual or {}).get(part) if isinstance(actual, dict) else None
  170. if actual != expected:
  171. return f"{probe} reports {path}={actual!r}, this case needs {expected!r}"
  172. return None
  173. def main():
  174. if len(sys.argv) != 2:
  175. raise SystemExit("usage: verify-node.py <case.json>")
  176. case = json.load(open(sys.argv[1]))
  177. unmet = precondition_unmet(case)
  178. if unmet:
  179. print(f"SKIP {case['name']}: {unmet}")
  180. return 2
  181. token = login()
  182. call("POST", "/nodes/migrate", token, {"nodesPath": "./nodes"})
  183. # Workflows the case needs to exist before it runs - a sub-workflow it
  184. # calls. Created here rather than named by id, so a case is not silently
  185. # tied to a row someone made by hand once and can delete.
  186. helper_ids = []
  187. for helper in case.get("helpers", []):
  188. made = call("POST", "/workflows", token, {
  189. "name": helper["name"],
  190. "nodes": helper["nodes"],
  191. "connections": helper.get("connections", []),
  192. })
  193. helper_id = made.get("id") or made.get("_id")
  194. if not helper_id:
  195. raise SystemExit(f"no id for helper {helper['key']}")
  196. helper_ids.append(helper_id)
  197. if helper.get("active", True):
  198. call("POST", f"/workflows/{helper_id}/activate", token, {})
  199. # Substituted everywhere, so the case refers to it by name.
  200. case = json.loads(json.dumps(case).replace("{{helper:" + helper["key"] + "}}", helper_id))
  201. created = call("POST", "/workflows", token, {
  202. "name": case["name"],
  203. "nodes": case["nodes"],
  204. "connections": case["connections"],
  205. "settings": case.get("settings", {}),
  206. })
  207. workflow_id = created.get("id") or created.get("_id")
  208. if not workflow_id:
  209. raise SystemExit(f"no workflow id in create response: {json.dumps(created)[:300]}")
  210. try:
  211. if "http" in case:
  212. call("POST", f"/workflows/{workflow_id}/activate", token, {})
  213. failures = run_http_case(case, token, workflow_id)
  214. print("\nFAIL" if failures else "\nPASS")
  215. for f in failures:
  216. print(" " + f)
  217. return 1 if failures else 0
  218. started = call("POST", f"/workflows/{workflow_id}/execute", token, case.get("trigger", {}))
  219. execution_id = started["executionId"]
  220. if "resume" in case:
  221. run_resume_case(case, token, execution_id)
  222. execution = None
  223. for _ in range(60):
  224. time.sleep(0.5)
  225. execution = call("GET", f"/executions/{execution_id}", token)
  226. if execution.get("status") in ("completed", "failed", "cancelled"):
  227. break
  228. else:
  229. raise SystemExit(f"execution {execution_id} did not finish in 30s")
  230. by_id = {n["nodeId"]: n for n in execution.get("nodeExecutions", [])}
  231. failures = []
  232. for node_id, want in case.get("expect", {}).items():
  233. got = by_id.get(node_id)
  234. if got is None:
  235. failures.append(f"{node_id}: did not run")
  236. continue
  237. if "status" in want and got.get("status") != want["status"]:
  238. failures.append(
  239. f"{node_id}: status {got.get('status')!r}, expected {want['status']!r}"
  240. + (f" (error: {got.get('error')})" if got.get("error") else "")
  241. )
  242. if "errorContains" in want:
  243. actual_error = got.get("error") or ""
  244. if want["errorContains"] not in actual_error:
  245. failures.append(
  246. f"{node_id}: error does not contain {want['errorContains']!r}, "
  247. f"got {actual_error!r}"
  248. )
  249. if "output" in want:
  250. failures += subset_matches(want["output"], got.get("output"), node_id)
  251. if "loopNodeId" in want and got.get("loopNodeId") != want["loopNodeId"]:
  252. failures.append(
  253. f"{node_id}: loopNodeId {got.get('loopNodeId')!r}, expected {want['loopNodeId']!r}"
  254. )
  255. if "loopIteration" in want and got.get("loopIteration") != want["loopIteration"]:
  256. failures.append(
  257. f"{node_id}: loopIteration {got.get('loopIteration')!r}, "
  258. f"expected {want['loopIteration']!r}"
  259. )
  260. if want.get("noLoopTag") and (
  261. "loopNodeId" in got or "loopIteration" in got
  262. ):
  263. failures.append(
  264. f"{node_id}: expected no loop tag, got loopNodeId={got.get('loopNodeId')!r} "
  265. f"loopIteration={got.get('loopIteration')!r}"
  266. )
  267. # How many raw nodeExecutions entries carry a given node id - the
  268. # count itself is the assertion for things like "a disabled node
  269. # inside a loop body is recorded once, not once per iteration" and
  270. # "a loop body node's per-iteration records are not shadowed by a
  271. # duplicate mirror entry".
  272. all_node_executions = execution.get("nodeExecutions", [])
  273. for node_id, want_count in case.get("expectCounts", {}).items():
  274. got_count = sum(1 for n in all_node_executions if n.get("nodeId") == node_id)
  275. if got_count != want_count:
  276. failures.append(
  277. f"{node_id}: {got_count} nodeExecutions entries, expected {want_count}"
  278. )
  279. # nodeExecutions has to come back sorted by startedAt - the array
  280. # order is the contract, not something callers are meant to re-sort.
  281. if case.get("expectChronological"):
  282. starts = [n.get("startedAt", 0) for n in all_node_executions]
  283. if starts != sorted(starts):
  284. failures.append(
  285. f"nodeExecutions is not in startedAt order: {starts}"
  286. )
  287. # What a watcher is told when the run fails. "Loop iteration failed" on
  288. # its own passed every assertion that looked at nodes, because the nodes
  289. # were all correct - the message was the broken part.
  290. wanted_error = case.get("expectExecutionError")
  291. if wanted_error and wanted_error not in (execution.get("error") or ""):
  292. failures.append(
  293. f"execution error does not contain {wanted_error!r}, "
  294. f"got {execution.get('error')!r}"
  295. )
  296. # Assertions against the execution record itself, not a node inside it -
  297. # e.g. "singleNodeTarget" naming which node a 'test this node' run
  298. # targeted, absent entirely on an ordinary run.
  299. failures += subset_matches(case.get("expectExecution", {}), execution, "execution")
  300. for key in case.get("expectExecutionAbsent", []):
  301. if key in execution:
  302. failures.append(f"execution.{key}: expected absent, got {execution[key]!r}")
  303. for node_id in case.get("expectMissing", []):
  304. got = by_id.get(node_id)
  305. if got is not None and got.get("status") != "skipped":
  306. failures.append(
  307. f"{node_id}: ran, but should not have (status: {got.get('status')!r})"
  308. )
  309. print(f"case: {case['name']} execution: {execution_id} status: {execution.get('status')}")
  310. for node_id, node in sorted(by_id.items()):
  311. print(f" {node_id:24} {node.get('status'):10} {json.dumps(node.get('output'))[:120]}")
  312. if failures:
  313. print("\nFAIL")
  314. for f in failures:
  315. print(" " + f)
  316. return 1
  317. print("\nPASS")
  318. return 0
  319. finally:
  320. call("DELETE", f"/workflows/{workflow_id}", token)
  321. for helper_id in helper_ids:
  322. call("DELETE", f"/workflows/{helper_id}", token)
  323. if __name__ == "__main__":
  324. sys.exit(main())