test_code.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. import time
  2. import uuid
  3. from os import getenv
  4. from typing import cast
  5. import pytest
  6. from core.app.entities.app_invoke_entities import InvokeFrom
  7. from core.workflow.entities.node_entities import NodeRunResult, UserFrom
  8. from core.workflow.entities.variable_pool import VariablePool
  9. from core.workflow.enums import SystemVariableKey
  10. from core.workflow.graph_engine.entities.graph import Graph
  11. from core.workflow.graph_engine.entities.graph_init_params import GraphInitParams
  12. from core.workflow.graph_engine.entities.graph_runtime_state import GraphRuntimeState
  13. from core.workflow.nodes.code.code_node import CodeNode
  14. from core.workflow.nodes.code.entities import CodeNodeData
  15. from models.workflow import WorkflowNodeExecutionStatus, WorkflowType
  16. from tests.integration_tests.workflow.nodes.__mock.code_executor import setup_code_executor_mock
  17. CODE_MAX_STRING_LENGTH = int(getenv("CODE_MAX_STRING_LENGTH", "10000"))
  18. def init_code_node(code_config: dict):
  19. graph_config = {
  20. "edges": [
  21. {
  22. "id": "start-source-code-target",
  23. "source": "start",
  24. "target": "code",
  25. },
  26. ],
  27. "nodes": [{"data": {"type": "start"}, "id": "start"}, code_config],
  28. }
  29. graph = Graph.init(graph_config=graph_config)
  30. init_params = GraphInitParams(
  31. tenant_id="1",
  32. app_id="1",
  33. workflow_type=WorkflowType.WORKFLOW,
  34. workflow_id="1",
  35. graph_config=graph_config,
  36. user_id="1",
  37. user_from=UserFrom.ACCOUNT,
  38. invoke_from=InvokeFrom.DEBUGGER,
  39. call_depth=0,
  40. )
  41. # construct variable pool
  42. variable_pool = VariablePool(
  43. system_variables={SystemVariableKey.FILES: [], SystemVariableKey.USER_ID: "aaa"},
  44. user_inputs={},
  45. environment_variables=[],
  46. conversation_variables=[],
  47. )
  48. variable_pool.add(["code", "123", "args1"], 1)
  49. variable_pool.add(["code", "123", "args2"], 2)
  50. node = CodeNode(
  51. id=str(uuid.uuid4()),
  52. graph_init_params=init_params,
  53. graph=graph,
  54. graph_runtime_state=GraphRuntimeState(variable_pool=variable_pool, start_at=time.perf_counter()),
  55. config=code_config,
  56. )
  57. return node
  58. @pytest.mark.parametrize("setup_code_executor_mock", [["none"]], indirect=True)
  59. def test_execute_code(setup_code_executor_mock):
  60. code = """
  61. def main(args1: int, args2: int) -> dict:
  62. return {
  63. "result": args1 + args2,
  64. }
  65. """
  66. # trim first 4 spaces at the beginning of each line
  67. code = "\n".join([line[4:] for line in code.split("\n")])
  68. code_config = {
  69. "id": "code",
  70. "data": {
  71. "outputs": {
  72. "result": {
  73. "type": "number",
  74. },
  75. },
  76. "title": "123",
  77. "variables": [
  78. {
  79. "variable": "args1",
  80. "value_selector": ["1", "123", "args1"],
  81. },
  82. {"variable": "args2", "value_selector": ["1", "123", "args2"]},
  83. ],
  84. "answer": "123",
  85. "code_language": "python3",
  86. "code": code,
  87. },
  88. }
  89. node = init_code_node(code_config)
  90. # execute node
  91. result = node._run()
  92. assert isinstance(result, NodeRunResult)
  93. assert result.status == WorkflowNodeExecutionStatus.SUCCEEDED
  94. assert result.outputs is not None
  95. assert result.outputs["result"] == 3
  96. assert result.error is None
  97. @pytest.mark.parametrize("setup_code_executor_mock", [["none"]], indirect=True)
  98. def test_execute_code_output_validator(setup_code_executor_mock):
  99. code = """
  100. def main(args1: int, args2: int) -> dict:
  101. return {
  102. "result": args1 + args2,
  103. }
  104. """
  105. # trim first 4 spaces at the beginning of each line
  106. code = "\n".join([line[4:] for line in code.split("\n")])
  107. code_config = {
  108. "id": "code",
  109. "data": {
  110. "outputs": {
  111. "result": {
  112. "type": "string",
  113. },
  114. },
  115. "title": "123",
  116. "variables": [
  117. {
  118. "variable": "args1",
  119. "value_selector": ["1", "123", "args1"],
  120. },
  121. {"variable": "args2", "value_selector": ["1", "123", "args2"]},
  122. ],
  123. "answer": "123",
  124. "code_language": "python3",
  125. "code": code,
  126. },
  127. }
  128. node = init_code_node(code_config)
  129. # execute node
  130. result = node._run()
  131. assert isinstance(result, NodeRunResult)
  132. assert result.status == WorkflowNodeExecutionStatus.FAILED
  133. assert result.error == "Output variable `result` must be a string"
  134. def test_execute_code_output_validator_depth():
  135. code = """
  136. def main(args1: int, args2: int) -> dict:
  137. return {
  138. "result": {
  139. "result": args1 + args2,
  140. }
  141. }
  142. """
  143. # trim first 4 spaces at the beginning of each line
  144. code = "\n".join([line[4:] for line in code.split("\n")])
  145. code_config = {
  146. "id": "code",
  147. "data": {
  148. "outputs": {
  149. "string_validator": {
  150. "type": "string",
  151. },
  152. "number_validator": {
  153. "type": "number",
  154. },
  155. "number_array_validator": {
  156. "type": "array[number]",
  157. },
  158. "string_array_validator": {
  159. "type": "array[string]",
  160. },
  161. "object_validator": {
  162. "type": "object",
  163. "children": {
  164. "result": {
  165. "type": "number",
  166. },
  167. "depth": {
  168. "type": "object",
  169. "children": {
  170. "depth": {
  171. "type": "object",
  172. "children": {
  173. "depth": {
  174. "type": "number",
  175. }
  176. },
  177. }
  178. },
  179. },
  180. },
  181. },
  182. },
  183. "title": "123",
  184. "variables": [
  185. {
  186. "variable": "args1",
  187. "value_selector": ["1", "123", "args1"],
  188. },
  189. {"variable": "args2", "value_selector": ["1", "123", "args2"]},
  190. ],
  191. "answer": "123",
  192. "code_language": "python3",
  193. "code": code,
  194. },
  195. }
  196. node = init_code_node(code_config)
  197. # construct result
  198. result = {
  199. "number_validator": 1,
  200. "string_validator": "1",
  201. "number_array_validator": [1, 2, 3, 3.333],
  202. "string_array_validator": ["1", "2", "3"],
  203. "object_validator": {"result": 1, "depth": {"depth": {"depth": 1}}},
  204. }
  205. node.node_data = cast(CodeNodeData, node.node_data)
  206. # validate
  207. node._transform_result(result, node.node_data.outputs)
  208. # construct result
  209. result = {
  210. "number_validator": "1",
  211. "string_validator": 1,
  212. "number_array_validator": ["1", "2", "3", "3.333"],
  213. "string_array_validator": [1, 2, 3],
  214. "object_validator": {"result": "1", "depth": {"depth": {"depth": "1"}}},
  215. }
  216. # validate
  217. with pytest.raises(ValueError):
  218. node._transform_result(result, node.node_data.outputs)
  219. # construct result
  220. result = {
  221. "number_validator": 1,
  222. "string_validator": (CODE_MAX_STRING_LENGTH + 1) * "1",
  223. "number_array_validator": [1, 2, 3, 3.333],
  224. "string_array_validator": ["1", "2", "3"],
  225. "object_validator": {"result": 1, "depth": {"depth": {"depth": 1}}},
  226. }
  227. # validate
  228. with pytest.raises(ValueError):
  229. node._transform_result(result, node.node_data.outputs)
  230. # construct result
  231. result = {
  232. "number_validator": 1,
  233. "string_validator": "1",
  234. "number_array_validator": [1, 2, 3, 3.333] * 2000,
  235. "string_array_validator": ["1", "2", "3"],
  236. "object_validator": {"result": 1, "depth": {"depth": {"depth": 1}}},
  237. }
  238. # validate
  239. with pytest.raises(ValueError):
  240. node._transform_result(result, node.node_data.outputs)
  241. def test_execute_code_output_object_list():
  242. code = """
  243. def main(args1: int, args2: int) -> dict:
  244. return {
  245. "result": {
  246. "result": args1 + args2,
  247. }
  248. }
  249. """
  250. # trim first 4 spaces at the beginning of each line
  251. code = "\n".join([line[4:] for line in code.split("\n")])
  252. code_config = {
  253. "id": "code",
  254. "data": {
  255. "outputs": {
  256. "object_list": {
  257. "type": "array[object]",
  258. },
  259. },
  260. "title": "123",
  261. "variables": [
  262. {
  263. "variable": "args1",
  264. "value_selector": ["1", "123", "args1"],
  265. },
  266. {"variable": "args2", "value_selector": ["1", "123", "args2"]},
  267. ],
  268. "answer": "123",
  269. "code_language": "python3",
  270. "code": code,
  271. },
  272. }
  273. node = init_code_node(code_config)
  274. # construct result
  275. result = {
  276. "object_list": [
  277. {
  278. "result": 1,
  279. },
  280. {
  281. "result": 2,
  282. },
  283. {
  284. "result": [1, 2, 3],
  285. },
  286. ]
  287. }
  288. node.node_data = cast(CodeNodeData, node.node_data)
  289. # validate
  290. node._transform_result(result, node.node_data.outputs)
  291. # construct result
  292. result = {
  293. "object_list": [
  294. {
  295. "result": 1,
  296. },
  297. {
  298. "result": 2,
  299. },
  300. {
  301. "result": [1, 2, 3],
  302. },
  303. 1,
  304. ]
  305. }
  306. # validate
  307. with pytest.raises(ValueError):
  308. node._transform_result(result, node.node_data.outputs)