You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_code.py 11KB

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