verify-node.py 10 KB

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