verify-node.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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 json
  8. import sys
  9. import time
  10. import urllib.error
  11. import urllib.request
  12. BASE = "http://localhost:8090/api/v1"
  13. def call(method, path, token=None, body=None):
  14. data = json.dumps(body).encode() if body is not None else None
  15. req = urllib.request.Request(BASE + path, data=data, method=method)
  16. req.add_header("Content-Type", "application/json")
  17. if token:
  18. req.add_header("Authorization", "Bearer " + token)
  19. try:
  20. with urllib.request.urlopen(req, timeout=30) as res:
  21. raw = res.read()
  22. return json.loads(raw) if raw else {}
  23. except urllib.error.HTTPError as e:
  24. raise SystemExit(f"{method} {path} failed: {e.code} {e.read().decode()[:400]}")
  25. def login():
  26. return call("POST", "/auth/login", body={"username": "admin", "password": "admin"})["accessToken"]
  27. def subset_matches(expected, actual, path):
  28. """Every key in expected must be present and equal in actual. Returns list of failures."""
  29. fails = []
  30. if isinstance(expected, dict):
  31. if not isinstance(actual, dict):
  32. return [f"{path}: expected an object, got {type(actual).__name__}"]
  33. for key, want in expected.items():
  34. if key not in actual:
  35. fails.append(f"{path}.{key}: missing")
  36. else:
  37. fails += subset_matches(want, actual[key], f"{path}.{key}")
  38. elif isinstance(expected, list):
  39. if not isinstance(actual, list):
  40. return [f"{path}: expected a list, got {type(actual).__name__}"]
  41. if len(expected) != len(actual):
  42. fails.append(f"{path}: expected {len(expected)} items, got {len(actual)}")
  43. else:
  44. for i, want in enumerate(expected):
  45. fails += subset_matches(want, actual[i], f"{path}[{i}]")
  46. elif expected != actual:
  47. fails.append(f"{path}: expected {expected!r}, got {actual!r}")
  48. return fails
  49. def run_http_case(case, token, workflow_id):
  50. """A webhook case asserts on the HTTP response, not on node outputs."""
  51. spec = case["http"]
  52. url = BASE.replace("/api/v1", "") + spec["path"].replace("{workflowId}", workflow_id)
  53. body = spec.get("body", {})
  54. pad = spec.get("bodyPadBytes", 0)
  55. if pad:
  56. body = dict(body)
  57. body["_pad"] = "x" * pad
  58. data = json.dumps(body).encode()
  59. req = urllib.request.Request(url, data=data, method=spec.get("method", "POST"))
  60. req.add_header("Content-Type", "application/json")
  61. failures = []
  62. try:
  63. with urllib.request.urlopen(req, timeout=45) as res:
  64. status, headers, raw = res.status, dict(res.headers), res.read().decode()
  65. except urllib.error.HTTPError as e:
  66. status, headers, raw = e.code, dict(e.headers), e.read().decode()
  67. print("http: %s %s -> %s" % (spec.get("method", "POST"), spec["path"], status))
  68. print(" body: %s" % raw[:200])
  69. if "expectStatus" in spec and status != spec["expectStatus"]:
  70. failures.append("status: expected %s, got %s" % (spec["expectStatus"], status))
  71. for name, want in spec.get("expectHeaders", {}).items():
  72. got = headers.get(name)
  73. if got is None:
  74. failures.append("header %s: missing" % name)
  75. elif want not in got:
  76. failures.append("header %s: expected to contain %r, got %r" % (name, want, got))
  77. for fragment in spec.get("expectBodyContains", []):
  78. if fragment not in raw:
  79. failures.append("body: expected to contain %r" % fragment)
  80. return failures
  81. def run_resume_case(case, token, execution_id):
  82. """Wait for the execution to pause, answer it, then let it finish."""
  83. spec = case["resume"]
  84. want_status = spec.get("waitForStatus", "waiting")
  85. execution = {}
  86. for _ in range(60):
  87. time.sleep(0.5)
  88. execution = call("GET", "/executions/%s" % execution_id, token)
  89. if execution.get("status") == want_status:
  90. break
  91. if execution.get("status") in ("completed", "failed", "cancelled"):
  92. raise SystemExit(
  93. "execution %s reached %s without pausing" % (execution_id, execution.get("status")))
  94. else:
  95. raise SystemExit("execution %s never reached %s" % (execution_id, want_status))
  96. by_id = {n["nodeId"]: n for n in execution.get("nodeExecutions", [])}
  97. source = by_id.get(spec["tokenFrom"])
  98. if not source:
  99. raise SystemExit("resume: node %s did not run" % spec["tokenFrom"])
  100. resume_token = (source.get("output") or {}).get("token")
  101. if not resume_token:
  102. raise SystemExit("resume: node %s produced no token" % spec["tokenFrom"])
  103. body = dict(spec.get("payload", {}))
  104. body["token"] = resume_token
  105. call("POST", "/executions/%s/resume" % execution_id, token, body)
  106. print("resumed %s with token %s" % (execution_id, resume_token))
  107. def precondition_unmet(case):
  108. """Why this case cannot run here, or None if it can.
  109. A couple of cases need a model loaded on the SD.cpp server, which unloads
  110. itself when idle. Without this they fail for a reason that has nothing to do
  111. with the code, and a failure everyone learns to ignore is worse than no
  112. test. Skipping is only honest because it is reported as a skip - never as a
  113. pass.
  114. """
  115. needs = case.get("requires")
  116. if not needs:
  117. return None
  118. probe = needs.get("http")
  119. if probe:
  120. try:
  121. with urllib.request.urlopen(probe, timeout=10) as response:
  122. body = json.loads(response.read().decode())
  123. except Exception as exc:
  124. return f"{probe} could not be read ({exc})"
  125. for path, expected in (needs.get("expect") or {}).items():
  126. actual = body
  127. for part in path.split("."):
  128. actual = (actual or {}).get(part) if isinstance(actual, dict) else None
  129. if actual != expected:
  130. return f"{probe} reports {path}={actual!r}, this case needs {expected!r}"
  131. return None
  132. def main():
  133. if len(sys.argv) != 2:
  134. raise SystemExit("usage: verify-node.py <case.json>")
  135. case = json.load(open(sys.argv[1]))
  136. unmet = precondition_unmet(case)
  137. if unmet:
  138. print(f"SKIP {case['name']}: {unmet}")
  139. return 2
  140. token = login()
  141. call("POST", "/nodes/migrate", token, {"nodesPath": "./nodes"})
  142. # Workflows the case needs to exist before it runs - a sub-workflow it
  143. # calls. Created here rather than named by id, so a case is not silently
  144. # tied to a row someone made by hand once and can delete.
  145. helper_ids = []
  146. for helper in case.get("helpers", []):
  147. made = call("POST", "/workflows", token, {
  148. "name": helper["name"],
  149. "nodes": helper["nodes"],
  150. "connections": helper.get("connections", []),
  151. })
  152. helper_id = made.get("id") or made.get("_id")
  153. if not helper_id:
  154. raise SystemExit(f"no id for helper {helper['key']}")
  155. helper_ids.append(helper_id)
  156. if helper.get("active", True):
  157. call("POST", f"/workflows/{helper_id}/activate", token, {})
  158. # Substituted everywhere, so the case refers to it by name.
  159. case = json.loads(json.dumps(case).replace("{{helper:" + helper["key"] + "}}", helper_id))
  160. created = call("POST", "/workflows", token, {
  161. "name": case["name"],
  162. "nodes": case["nodes"],
  163. "connections": case["connections"],
  164. "settings": case.get("settings", {}),
  165. })
  166. workflow_id = created.get("id") or created.get("_id")
  167. if not workflow_id:
  168. raise SystemExit(f"no workflow id in create response: {json.dumps(created)[:300]}")
  169. try:
  170. if "http" in case:
  171. call("POST", f"/workflows/{workflow_id}/activate", token, {})
  172. failures = run_http_case(case, token, workflow_id)
  173. print("\nFAIL" if failures else "\nPASS")
  174. for f in failures:
  175. print(" " + f)
  176. return 1 if failures else 0
  177. started = call("POST", f"/workflows/{workflow_id}/execute", token, {})
  178. execution_id = started["executionId"]
  179. if "resume" in case:
  180. run_resume_case(case, token, execution_id)
  181. execution = None
  182. for _ in range(60):
  183. time.sleep(0.5)
  184. execution = call("GET", f"/executions/{execution_id}", token)
  185. if execution.get("status") in ("completed", "failed", "cancelled"):
  186. break
  187. else:
  188. raise SystemExit(f"execution {execution_id} did not finish in 30s")
  189. by_id = {n["nodeId"]: n for n in execution.get("nodeExecutions", [])}
  190. failures = []
  191. for node_id, want in case.get("expect", {}).items():
  192. got = by_id.get(node_id)
  193. if got is None:
  194. failures.append(f"{node_id}: did not run")
  195. continue
  196. if "status" in want and got.get("status") != want["status"]:
  197. failures.append(
  198. f"{node_id}: status {got.get('status')!r}, expected {want['status']!r}"
  199. + (f" (error: {got.get('error')})" if got.get("error") else "")
  200. )
  201. if "errorContains" in want:
  202. actual_error = got.get("error") or ""
  203. if want["errorContains"] not in actual_error:
  204. failures.append(
  205. f"{node_id}: error does not contain {want['errorContains']!r}, "
  206. f"got {actual_error!r}"
  207. )
  208. if "output" in want:
  209. failures += subset_matches(want["output"], got.get("output"), node_id)
  210. # What a watcher is told when the run fails. "Loop iteration failed" on
  211. # its own passed every assertion that looked at nodes, because the nodes
  212. # were all correct - the message was the broken part.
  213. wanted_error = case.get("expectExecutionError")
  214. if wanted_error and wanted_error not in (execution.get("error") or ""):
  215. failures.append(
  216. f"execution error does not contain {wanted_error!r}, "
  217. f"got {execution.get('error')!r}"
  218. )
  219. for node_id in case.get("expectMissing", []):
  220. got = by_id.get(node_id)
  221. if got is not None and got.get("status") != "skipped":
  222. failures.append(
  223. f"{node_id}: ran, but should not have (status: {got.get('status')!r})"
  224. )
  225. print(f"case: {case['name']} execution: {execution_id} status: {execution.get('status')}")
  226. for node_id, node in sorted(by_id.items()):
  227. print(f" {node_id:24} {node.get('status'):10} {json.dumps(node.get('output'))[:120]}")
  228. if failures:
  229. print("\nFAIL")
  230. for f in failures:
  231. print(" " + f)
  232. return 1
  233. print("\nPASS")
  234. return 0
  235. finally:
  236. call("DELETE", f"/workflows/{workflow_id}", token)
  237. for helper_id in helper_ids:
  238. call("DELETE", f"/workflows/{helper_id}", token)
  239. if __name__ == "__main__":
  240. sys.exit(main())