test_code.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. # execute node
  92. result = node._run()
  93. assert isinstance(result, NodeRunResult)
  94. assert result.status == WorkflowNodeExecutionStatus.SUCCEEDED
  95. assert result.outputs is not None
  96. assert result.outputs["result"] == 3
  97. assert result.error is None
  98. @pytest.mark.parametrize("setup_code_executor_mock", [["none"]], indirect=True)
  99. def test_execute_code_output_validator(setup_code_executor_mock):
  100. code = """
  101. def main(args1: int, args2: int) -> dict:
  102. return {
  103. "result": args1 + args2,
  104. }
  105. """
  106. # trim first 4 spaces at the beginning of each line
  107. code = "\n".join([line[4:] for line in code.split("\n")])
  108. code_config = {
  109. "id": "code",
  110. "data": {
  111. "outputs": {
  112. "result": {
  113. "type": "string",
  114. },
  115. },
  116. "title": "123",
  117. "variables": [
  118. {
  119. "variable": "args1",
  120. "value_selector": ["1", "123", "args1"],
  121. },
  122. {"variable": "args2", "value_selector": ["1", "123", "args2"]},
  123. ],
  124. "answer": "123",
  125. "code_language": "python3",
  126. "code": code,
  127. },
  128. }
  129. node = init_code_node(code_config)
  130. # execute node
  131. result = node._run()
  132. assert isinstance(result, NodeRunResult)
  133. assert result.status == WorkflowNodeExecutionStatus.FAILED
  134. assert result.error == "Output variable `result` must be a string"
  135. def test_execute_code_output_validator_depth():
  136. code = """
  137. def main(args1: int, args2: int) -> dict:
  138. return {
  139. "result": {
  140. "result": args1 + args2,
  141. }
  142. }
  143. """
  144. # trim first 4 spaces at the beginning of each line
  145. code = "\n".join([line[4:] for line in code.split("\n")])
  146. code_config = {
  147. "id": "code",
  148. "data": {
  149. "outputs": {
  150. "string_validator": {
  151. "type": "string",
  152. },
  153. "number_validator": {
  154. "type": "number",
  155. },
  156. "number_array_validator": {
  157. "type": "array[number]",
  158. },
  159. "string_array_validator": {
  160. "type": "array[string]",
  161. },
  162. "object_validator": {
  163. "type": "object",
  164. "children": {
  165. "result": {
  166. "type": "number",
  167. },
  168. "depth": {
  169. "type": "object",
  170. "children": {
  171. "depth": {
  172. "type": "object",
  173. "children": {
  174. "depth": {
  175. "type": "number",
  176. }
  177. },
  178. }
  179. },
  180. },
  181. },
  182. },
  183. },
  184. "title": "123",
  185. "variables": [
  186. {
  187. "variable": "args1",
  188. "value_selector": ["1", "123", "args1"],
  189. },
  190. {"variable": "args2", "value_selector": ["1", "123", "args2"]},
  191. ],
  192. "answer": "123",
  193. "code_language": "python3",
  194. "code": code,
  195. },
  196. }
  197. node = init_code_node(code_config)
  198. # construct result
  199. result = {
  200. "number_validator": 1,
  201. "string_validator": "1",
  202. "number_array_validator": [1, 2, 3, 3.333],
  203. "string_array_validator": ["1", "2", "3"],
  204. "object_validator": {"result": 1, "depth": {"depth": {"depth": 1}}},
  205. }
  206. node.node_data = cast(CodeNodeData, node.node_data)
  207. # validate
  208. node._transform_result(result, node.node_data.outputs)
  209. # construct result
  210. result = {
  211. "number_validator": "1",
  212. "string_validator": 1,
  213. "number_array_validator": ["1", "2", "3", "3.333"],
  214. "string_array_validator": [1, 2, 3],
  215. "object_validator": {"result": "1", "depth": {"depth": {"depth": "1"}}},
  216. }
  217. # validate
  218. with pytest.raises(ValueError):
  219. node._transform_result(result, node.node_data.outputs)
  220. # construct result
  221. result = {
  222. "number_validator": 1,
  223. "string_validator": (CODE_MAX_STRING_LENGTH + 1) * "1",
  224. "number_array_validator": [1, 2, 3, 3.333],
  225. "string_array_validator": ["1", "2", "3"],
  226. "object_validator": {"result": 1, "depth": {"depth": {"depth": 1}}},
  227. }
  228. # validate
  229. with pytest.raises(ValueError):
  230. node._transform_result(result, node.node_data.outputs)
  231. # construct result
  232. result = {
  233. "number_validator": 1,
  234. "string_validator": "1",
  235. "number_array_validator": [1, 2, 3, 3.333] * 2000,
  236. "string_array_validator": ["1", "2", "3"],
  237. "object_validator": {"result": 1, "depth": {"depth": {"depth": 1}}},
  238. }
  239. # validate
  240. with pytest.raises(ValueError):
  241. node._transform_result(result, node.node_data.outputs)
  242. def test_execute_code_output_object_list():
  243. code = """
  244. def main(args1: int, args2: int) -> dict:
  245. return {
  246. "result": {
  247. "result": args1 + args2,
  248. }
  249. }
  250. """
  251. # trim first 4 spaces at the beginning of each line
  252. code = "\n".join([line[4:] for line in code.split("\n")])
  253. code_config = {
  254. "id": "code",
  255. "data": {
  256. "outputs": {
  257. "object_list": {
  258. "type": "array[object]",
  259. },
  260. },
  261. "title": "123",
  262. "variables": [
  263. {
  264. "variable": "args1",
  265. "value_selector": ["1", "123", "args1"],
  266. },
  267. {"variable": "args2", "value_selector": ["1", "123", "args2"]},
  268. ],
  269. "answer": "123",
  270. "code_language": "python3",
  271. "code": code,
  272. },
  273. }
  274. node = init_code_node(code_config)
  275. # construct result
  276. result = {
  277. "object_list": [
  278. {
  279. "result": 1,
  280. },
  281. {
  282. "result": 2,
  283. },
  284. {
  285. "result": [1, 2, 3],
  286. },
  287. ]
  288. }
  289. node.node_data = cast(CodeNodeData, node.node_data)
  290. # validate
  291. node._transform_result(result, node.node_data.outputs)
  292. # construct result
  293. result = {
  294. "object_list": [
  295. {
  296. "result": 1,
  297. },
  298. {
  299. "result": 2,
  300. },
  301. {
  302. "result": [1, 2, 3],
  303. },
  304. 1,
  305. ]
  306. }
  307. # validate
  308. with pytest.raises(ValueError):
  309. node._transform_result(result, node.node_data.outputs)