test_code.py 10 KB

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