verify-node.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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 otherwise.
  5. """
  6. import json
  7. import sys
  8. import time
  9. import urllib.error
  10. import urllib.request
  11. BASE = "http://localhost:8090/api/v1"
  12. def call(method, path, token=None, body=None):
  13. data = json.dumps(body).encode() if body is not None else None
  14. req = urllib.request.Request(BASE + path, data=data, method=method)
  15. req.add_header("Content-Type", "application/json")
  16. if token:
  17. req.add_header("Authorization", "Bearer " + token)
  18. try:
  19. with urllib.request.urlopen(req, timeout=30) as res:
  20. raw = res.read()
  21. return json.loads(raw) if raw else {}
  22. except urllib.error.HTTPError as e:
  23. raise SystemExit(f"{method} {path} failed: {e.code} {e.read().decode()[:400]}")
  24. def login():
  25. return call("POST", "/auth/login", body={"username": "admin", "password": "admin"})["accessToken"]
  26. def subset_matches(expected, actual, path):
  27. """Every key in expected must be present and equal in actual. Returns list of failures."""
  28. fails = []
  29. if isinstance(expected, dict):
  30. if not isinstance(actual, dict):
  31. return [f"{path}: expected an object, got {type(actual).__name__}"]
  32. for key, want in expected.items():
  33. if key not in actual:
  34. fails.append(f"{path}.{key}: missing")
  35. else:
  36. fails += subset_matches(want, actual[key], f"{path}.{key}")
  37. elif isinstance(expected, list):
  38. if not isinstance(actual, list):
  39. return [f"{path}: expected a list, got {type(actual).__name__}"]
  40. if len(expected) != len(actual):
  41. fails.append(f"{path}: expected {len(expected)} items, got {len(actual)}")
  42. else:
  43. for i, want in enumerate(expected):
  44. fails += subset_matches(want, actual[i], f"{path}[{i}]")
  45. elif expected != actual:
  46. fails.append(f"{path}: expected {expected!r}, got {actual!r}")
  47. return fails
  48. def run_http_case(case, token, workflow_id):
  49. """A webhook case asserts on the HTTP response, not on node outputs."""
  50. spec = case["http"]
  51. url = BASE.replace("/api/v1", "") + spec["path"].replace("{workflowId}", workflow_id)
  52. data = json.dumps(spec.get("body", {})).encode()
  53. req = urllib.request.Request(url, data=data, method=spec.get("method", "POST"))
  54. req.add_header("Content-Type", "application/json")
  55. failures = []
  56. try:
  57. with urllib.request.urlopen(req, timeout=45) as res:
  58. status, headers, raw = res.status, dict(res.headers), res.read().decode()
  59. except urllib.error.HTTPError as e:
  60. status, headers, raw = e.code, dict(e.headers), e.read().decode()
  61. print("http: %s %s -> %s" % (spec.get("method", "POST"), spec["path"], status))
  62. print(" body: %s" % raw[:200])
  63. if "expectStatus" in spec and status != spec["expectStatus"]:
  64. failures.append("status: expected %s, got %s" % (spec["expectStatus"], status))
  65. for name, want in spec.get("expectHeaders", {}).items():
  66. got = headers.get(name)
  67. if got is None:
  68. failures.append("header %s: missing" % name)
  69. elif want not in got:
  70. failures.append("header %s: expected to contain %r, got %r" % (name, want, got))
  71. for fragment in spec.get("expectBodyContains", []):
  72. if fragment not in raw:
  73. failures.append("body: expected to contain %r" % fragment)
  74. return failures
  75. def run_resume_case(case, token, execution_id):
  76. """Wait for the execution to pause, answer it, then let it finish."""
  77. spec = case["resume"]
  78. want_status = spec.get("waitForStatus", "waiting")
  79. execution = {}
  80. for _ in range(60):
  81. time.sleep(0.5)
  82. execution = call("GET", "/executions/%s" % execution_id, token)
  83. if execution.get("status") == want_status:
  84. break
  85. if execution.get("status") in ("completed", "failed", "cancelled"):
  86. raise SystemExit(
  87. "execution %s reached %s without pausing" % (execution_id, execution.get("status")))
  88. else:
  89. raise SystemExit("execution %s never reached %s" % (execution_id, want_status))
  90. by_id = {n["nodeId"]: n for n in execution.get("nodeExecutions", [])}
  91. source = by_id.get(spec["tokenFrom"])
  92. if not source:
  93. raise SystemExit("resume: node %s did not run" % spec["tokenFrom"])
  94. resume_token = (source.get("output") or {}).get("token")
  95. if not resume_token:
  96. raise SystemExit("resume: node %s produced no token" % spec["tokenFrom"])
  97. body = dict(spec.get("payload", {}))
  98. body["token"] = resume_token
  99. call("POST", "/executions/%s/resume" % execution_id, token, body)
  100. print("resumed %s with token %s" % (execution_id, resume_token))
  101. def main():
  102. if len(sys.argv) != 2:
  103. raise SystemExit("usage: verify-node.py <case.json>")
  104. case = json.load(open(sys.argv[1]))
  105. token = login()
  106. call("POST", "/nodes/migrate", token, {"nodesPath": "./nodes"})
  107. # Workflows the case needs to exist before it runs - a sub-workflow it
  108. # calls. Created here rather than named by id, so a case is not silently
  109. # tied to a row someone made by hand once and can delete.
  110. helper_ids = []
  111. for helper in case.get("helpers", []):
  112. made = call("POST", "/workflows", token, {
  113. "name": helper["name"],
  114. "nodes": helper["nodes"],
  115. "connections": helper.get("connections", []),
  116. })
  117. helper_id = made.get("id") or made.get("_id")
  118. if not helper_id:
  119. raise SystemExit(f"no id for helper {helper['key']}")
  120. helper_ids.append(helper_id)
  121. if helper.get("active", True):
  122. call("POST", f"/workflows/{helper_id}/activate", token, {})
  123. # Substituted everywhere, so the case refers to it by name.
  124. case = json.loads(json.dumps(case).replace("{{helper:" + helper["key"] + "}}", helper_id))
  125. created = call("POST", "/workflows", token, {
  126. "name": case["name"],
  127. "nodes": case["nodes"],
  128. "connections": case["connections"],
  129. "settings": case.get("settings", {}),
  130. })
  131. workflow_id = created.get("id") or created.get("_id")
  132. if not workflow_id:
  133. raise SystemExit(f"no workflow id in create response: {json.dumps(created)[:300]}")
  134. try:
  135. if "http" in case:
  136. call("POST", f"/workflows/{workflow_id}/activate", token, {})
  137. failures = run_http_case(case, token, workflow_id)
  138. print("\nFAIL" if failures else "\nPASS")
  139. for f in failures:
  140. print(" " + f)
  141. return 1 if failures else 0
  142. started = call("POST", f"/workflows/{workflow_id}/execute", token, {})
  143. execution_id = started["executionId"]
  144. if "resume" in case:
  145. run_resume_case(case, token, execution_id)
  146. execution = None
  147. for _ in range(60):
  148. time.sleep(0.5)
  149. execution = call("GET", f"/executions/{execution_id}", token)
  150. if execution.get("status") in ("completed", "failed", "cancelled"):
  151. break
  152. else:
  153. raise SystemExit(f"execution {execution_id} did not finish in 30s")
  154. by_id = {n["nodeId"]: n for n in execution.get("nodeExecutions", [])}
  155. failures = []
  156. for node_id, want in case.get("expect", {}).items():
  157. got = by_id.get(node_id)
  158. if got is None:
  159. failures.append(f"{node_id}: did not run")
  160. continue
  161. if "status" in want and got.get("status") != want["status"]:
  162. failures.append(
  163. f"{node_id}: status {got.get('status')!r}, expected {want['status']!r}"
  164. + (f" (error: {got.get('error')})" if got.get("error") else "")
  165. )
  166. if "errorContains" in want:
  167. actual_error = got.get("error") or ""
  168. if want["errorContains"] not in actual_error:
  169. failures.append(
  170. f"{node_id}: error does not contain {want['errorContains']!r}, "
  171. f"got {actual_error!r}"
  172. )
  173. if "output" in want:
  174. failures += subset_matches(want["output"], got.get("output"), node_id)
  175. for node_id in case.get("expectMissing", []):
  176. got = by_id.get(node_id)
  177. if got is not None and got.get("status") != "skipped":
  178. failures.append(
  179. f"{node_id}: ran, but should not have (status: {got.get('status')!r})"
  180. )
  181. print(f"case: {case['name']} execution: {execution_id} status: {execution.get('status')}")
  182. for node_id, node in sorted(by_id.items()):
  183. print(f" {node_id:24} {node.get('status'):10} {json.dumps(node.get('output'))[:120]}")
  184. if failures:
  185. print("\nFAIL")
  186. for f in failures:
  187. print(" " + f)
  188. return 1
  189. print("\nPASS")
  190. return 0
  191. finally:
  192. call("DELETE", f"/workflows/{workflow_id}", token)
  193. for helper_id in helper_ids:
  194. call("DELETE", f"/workflows/{helper_id}", token)
  195. if __name__ == "__main__":
  196. sys.exit(main())