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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. import time
  2. import uuid
  3. from os import getenv
  4. import pytest
  5. from core.app.entities.app_invoke_entities import InvokeFrom
  6. from core.workflow.entities.node_entities import NodeRunResult
  7. from core.workflow.entities.variable_pool import VariablePool
  8. from core.workflow.entities.workflow_node_execution import WorkflowNodeExecutionStatus
  9. from core.workflow.graph_engine.entities.graph import Graph
  10. from core.workflow.graph_engine.entities.graph_init_params import GraphInitParams
  11. from core.workflow.graph_engine.entities.graph_runtime_state import GraphRuntimeState
  12. from core.workflow.nodes.code.code_node import CodeNode
  13. from core.workflow.system_variable import SystemVariable
  14. from models.enums import UserFrom
  15. from models.workflow import 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=SystemVariable(user_id="aaa", files=[]),
  44. user_inputs={},
  45. environment_variables=[],
  46. conversation_variables=[],
  47. )
  48. variable_pool.add(["code", "args1"], 1)
  49. variable_pool.add(["code", "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. # Initialize node data
  58. if "data" in code_config:
  59. node.init_node_data(code_config["data"])
  60. return node
  61. @pytest.mark.parametrize("setup_code_executor_mock", [["none"]], indirect=True)
  62. def test_execute_code(setup_code_executor_mock):
  63. code = """
  64. def main(args1: int, args2: int) -> dict:
  65. return {
  66. "result": args1 + args2,
  67. }
  68. """
  69. # trim first 4 spaces at the beginning of each line
  70. code = "\n".join([line[4:] for line in code.split("\n")])
  71. code_config = {
  72. "id": "code",
  73. "data": {
  74. "outputs": {
  75. "result": {
  76. "type": "number",
  77. },
  78. },
  79. "title": "123",
  80. "variables": [
  81. {
  82. "variable": "args1",
  83. "value_selector": ["1", "args1"],
  84. },
  85. {"variable": "args2", "value_selector": ["1", "args2"]},
  86. ],
  87. "answer": "123",
  88. "code_language": "python3",
  89. "code": code,
  90. },
  91. }
  92. node = init_code_node(code_config)
  93. node.graph_runtime_state.variable_pool.add(["1", "args1"], 1)
  94. node.graph_runtime_state.variable_pool.add(["1", "args2"], 2)
  95. # execute node
  96. result = node._run()
  97. assert isinstance(result, NodeRunResult)
  98. assert result.status == WorkflowNodeExecutionStatus.SUCCEEDED
  99. assert result.outputs is not None
  100. assert result.outputs["result"] == 3
  101. assert result.error is None
  102. @pytest.mark.parametrize("setup_code_executor_mock", [["none"]], indirect=True)
  103. def test_execute_code_output_validator(setup_code_executor_mock):
  104. code = """
  105. def main(args1: int, args2: int) -> dict:
  106. return {
  107. "result": args1 + args2,
  108. }
  109. """
  110. # trim first 4 spaces at the beginning of each line
  111. code = "\n".join([line[4:] for line in code.split("\n")])
  112. code_config = {
  113. "id": "code",
  114. "data": {
  115. "outputs": {
  116. "result": {
  117. "type": "string",
  118. },
  119. },
  120. "title": "123",
  121. "variables": [
  122. {
  123. "variable": "args1",
  124. "value_selector": ["1", "args1"],
  125. },
  126. {"variable": "args2", "value_selector": ["1", "args2"]},
  127. ],
  128. "answer": "123",
  129. "code_language": "python3",
  130. "code": code,
  131. },
  132. }
  133. node = init_code_node(code_config)
  134. node.graph_runtime_state.variable_pool.add(["1", "args1"], 1)
  135. node.graph_runtime_state.variable_pool.add(["1", "args2"], 2)
  136. # execute node
  137. result = node._run()
  138. assert isinstance(result, NodeRunResult)
  139. assert result.status == WorkflowNodeExecutionStatus.FAILED
  140. assert result.error == "Output variable `result` must be a string"
  141. def test_execute_code_output_validator_depth():
  142. code = """
  143. def main(args1: int, args2: int) -> dict:
  144. return {
  145. "result": {
  146. "result": args1 + args2,
  147. }
  148. }
  149. """
  150. # trim first 4 spaces at the beginning of each line
  151. code = "\n".join([line[4:] for line in code.split("\n")])
  152. code_config = {
  153. "id": "code",
  154. "data": {
  155. "outputs": {
  156. "string_validator": {
  157. "type": "string",
  158. },
  159. "number_validator": {
  160. "type": "number",
  161. },
  162. "number_array_validator": {
  163. "type": "array[number]",
  164. },
  165. "string_array_validator": {
  166. "type": "array[string]",
  167. },
  168. "object_validator": {
  169. "type": "object",
  170. "children": {
  171. "result": {
  172. "type": "number",
  173. },
  174. "depth": {
  175. "type": "object",
  176. "children": {
  177. "depth": {
  178. "type": "object",
  179. "children": {
  180. "depth": {
  181. "type": "number",
  182. }
  183. },
  184. }
  185. },
  186. },
  187. },
  188. },
  189. },
  190. "title": "123",
  191. "variables": [
  192. {
  193. "variable": "args1",
  194. "value_selector": ["1", "args1"],
  195. },
  196. {"variable": "args2", "value_selector": ["1", "args2"]},
  197. ],
  198. "answer": "123",
  199. "code_language": "python3",
  200. "code": code,
  201. },
  202. }
  203. node = init_code_node(code_config)
  204. # construct result
  205. result = {
  206. "number_validator": 1,
  207. "string_validator": "1",
  208. "number_array_validator": [1, 2, 3, 3.333],
  209. "string_array_validator": ["1", "2", "3"],
  210. "object_validator": {"result": 1, "depth": {"depth": {"depth": 1}}},
  211. }
  212. # validate
  213. node._transform_result(result, node._node_data.outputs)
  214. # construct result
  215. result = {
  216. "number_validator": "1",
  217. "string_validator": 1,
  218. "number_array_validator": ["1", "2", "3", "3.333"],
  219. "string_array_validator": [1, 2, 3],
  220. "object_validator": {"result": "1", "depth": {"depth": {"depth": "1"}}},
  221. }
  222. # validate
  223. with pytest.raises(ValueError):
  224. node._transform_result(result, node._node_data.outputs)
  225. # construct result
  226. result = {
  227. "number_validator": 1,
  228. "string_validator": (CODE_MAX_STRING_LENGTH + 1) * "1",
  229. "number_array_validator": [1, 2, 3, 3.333],
  230. "string_array_validator": ["1", "2", "3"],
  231. "object_validator": {"result": 1, "depth": {"depth": {"depth": 1}}},
  232. }
  233. # validate
  234. with pytest.raises(ValueError):
  235. node._transform_result(result, node._node_data.outputs)
  236. # construct result
  237. result = {
  238. "number_validator": 1,
  239. "string_validator": "1",
  240. "number_array_validator": [1, 2, 3, 3.333] * 2000,
  241. "string_array_validator": ["1", "2", "3"],
  242. "object_validator": {"result": 1, "depth": {"depth": {"depth": 1}}},
  243. }
  244. # validate
  245. with pytest.raises(ValueError):
  246. node._transform_result(result, node._node_data.outputs)
  247. def test_execute_code_output_object_list():
  248. code = """
  249. def main(args1: int, args2: int) -> dict:
  250. return {
  251. "result": {
  252. "result": args1 + args2,
  253. }
  254. }
  255. """
  256. # trim first 4 spaces at the beginning of each line
  257. code = "\n".join([line[4:] for line in code.split("\n")])
  258. code_config = {
  259. "id": "code",
  260. "data": {
  261. "outputs": {
  262. "object_list": {
  263. "type": "array[object]",
  264. },
  265. },
  266. "title": "123",
  267. "variables": [
  268. {
  269. "variable": "args1",
  270. "value_selector": ["1", "args1"],
  271. },
  272. {"variable": "args2", "value_selector": ["1", "args2"]},
  273. ],
  274. "answer": "123",
  275. "code_language": "python3",
  276. "code": code,
  277. },
  278. }
  279. node = init_code_node(code_config)
  280. # construct result
  281. result = {
  282. "object_list": [
  283. {
  284. "result": 1,
  285. },
  286. {
  287. "result": 2,
  288. },
  289. {
  290. "result": [1, 2, 3],
  291. },
  292. ]
  293. }
  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)
  314. def test_execute_code_scientific_notation():
  315. code = """
  316. def main() -> dict:
  317. return {
  318. "result": -8.0E-5
  319. }
  320. """
  321. code = "\n".join([line[4:] for line in code.split("\n")])
  322. code_config = {
  323. "id": "code",
  324. "data": {
  325. "outputs": {
  326. "result": {
  327. "type": "number",
  328. },
  329. },
  330. "title": "123",
  331. "variables": [],
  332. "answer": "123",
  333. "code_language": "python3",
  334. "code": code,
  335. },
  336. }
  337. node = init_code_node(code_config)
  338. # execute node
  339. result = node._run()
  340. assert isinstance(result, NodeRunResult)
  341. assert result.status == WorkflowNodeExecutionStatus.SUCCEEDED