您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

test_code.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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 import GraphInitParams, GraphRuntimeState, VariablePool
  7. from core.workflow.enums import WorkflowNodeExecutionStatus
  8. from core.workflow.graph import Graph
  9. from core.workflow.node_events import NodeRunResult
  10. from core.workflow.nodes.code.code_node import CodeNode
  11. from core.workflow.nodes.node_factory import DifyNodeFactory
  12. from core.workflow.system_variable import SystemVariable
  13. from models.enums import UserFrom
  14. from tests.integration_tests.workflow.nodes.__mock.code_executor import setup_code_executor_mock
  15. CODE_MAX_STRING_LENGTH = int(getenv("CODE_MAX_STRING_LENGTH", "10000"))
  16. def init_code_node(code_config: dict):
  17. graph_config = {
  18. "edges": [
  19. {
  20. "id": "start-source-code-target",
  21. "source": "start",
  22. "target": "code",
  23. },
  24. ],
  25. "nodes": [{"data": {"type": "start", "title": "Start"}, "id": "start"}, code_config],
  26. }
  27. init_params = GraphInitParams(
  28. tenant_id="1",
  29. app_id="1",
  30. workflow_id="1",
  31. graph_config=graph_config,
  32. user_id="1",
  33. user_from=UserFrom.ACCOUNT,
  34. invoke_from=InvokeFrom.DEBUGGER,
  35. call_depth=0,
  36. )
  37. # construct variable pool
  38. variable_pool = VariablePool(
  39. system_variables=SystemVariable(user_id="aaa", files=[]),
  40. user_inputs={},
  41. environment_variables=[],
  42. conversation_variables=[],
  43. )
  44. variable_pool.add(["code", "args1"], 1)
  45. variable_pool.add(["code", "args2"], 2)
  46. graph_runtime_state = GraphRuntimeState(variable_pool=variable_pool, start_at=time.perf_counter())
  47. # Create node factory
  48. node_factory = DifyNodeFactory(
  49. graph_init_params=init_params,
  50. graph_runtime_state=graph_runtime_state,
  51. )
  52. graph = Graph.init(graph_config=graph_config, node_factory=node_factory)
  53. node = CodeNode(
  54. id=str(uuid.uuid4()),
  55. config=code_config,
  56. graph_init_params=init_params,
  57. graph_runtime_state=graph_runtime_state,
  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 == ""
  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 result must be a string, got int instead"
  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. # validate
  215. node._transform_result(result, node._node_data.outputs)
  216. # construct result
  217. result = {
  218. "number_validator": "1",
  219. "string_validator": 1,
  220. "number_array_validator": ["1", "2", "3", "3.333"],
  221. "string_array_validator": [1, 2, 3],
  222. "object_validator": {"result": "1", "depth": {"depth": {"depth": "1"}}},
  223. }
  224. # validate
  225. with pytest.raises(ValueError):
  226. node._transform_result(result, node._node_data.outputs)
  227. # construct result
  228. result = {
  229. "number_validator": 1,
  230. "string_validator": (CODE_MAX_STRING_LENGTH + 1) * "1",
  231. "number_array_validator": [1, 2, 3, 3.333],
  232. "string_array_validator": ["1", "2", "3"],
  233. "object_validator": {"result": 1, "depth": {"depth": {"depth": 1}}},
  234. }
  235. # validate
  236. with pytest.raises(ValueError):
  237. node._transform_result(result, node._node_data.outputs)
  238. # construct result
  239. result = {
  240. "number_validator": 1,
  241. "string_validator": "1",
  242. "number_array_validator": [1, 2, 3, 3.333] * 2000,
  243. "string_array_validator": ["1", "2", "3"],
  244. "object_validator": {"result": 1, "depth": {"depth": {"depth": 1}}},
  245. }
  246. # validate
  247. with pytest.raises(ValueError):
  248. node._transform_result(result, node._node_data.outputs)
  249. def test_execute_code_output_object_list():
  250. code = """
  251. def main(args1: int, args2: int) -> dict:
  252. return {
  253. "result": {
  254. "result": args1 + args2,
  255. }
  256. }
  257. """
  258. # trim first 4 spaces at the beginning of each line
  259. code = "\n".join([line[4:] for line in code.split("\n")])
  260. code_config = {
  261. "id": "code",
  262. "data": {
  263. "outputs": {
  264. "object_list": {
  265. "type": "array[object]",
  266. },
  267. },
  268. "title": "123",
  269. "variables": [
  270. {
  271. "variable": "args1",
  272. "value_selector": ["1", "args1"],
  273. },
  274. {"variable": "args2", "value_selector": ["1", "args2"]},
  275. ],
  276. "answer": "123",
  277. "code_language": "python3",
  278. "code": code,
  279. },
  280. }
  281. node = init_code_node(code_config)
  282. # construct result
  283. result = {
  284. "object_list": [
  285. {
  286. "result": 1,
  287. },
  288. {
  289. "result": 2,
  290. },
  291. {
  292. "result": [1, 2, 3],
  293. },
  294. ]
  295. }
  296. # validate
  297. node._transform_result(result, node._node_data.outputs)
  298. # construct result
  299. result = {
  300. "object_list": [
  301. {
  302. "result": 1,
  303. },
  304. {
  305. "result": 2,
  306. },
  307. {
  308. "result": [1, 2, 3],
  309. },
  310. 1,
  311. ]
  312. }
  313. # validate
  314. with pytest.raises(ValueError):
  315. node._transform_result(result, node._node_data.outputs)
  316. def test_execute_code_scientific_notation():
  317. code = """
  318. def main() -> dict:
  319. return {
  320. "result": -8.0E-5
  321. }
  322. """
  323. code = "\n".join([line[4:] for line in code.split("\n")])
  324. code_config = {
  325. "id": "code",
  326. "data": {
  327. "outputs": {
  328. "result": {
  329. "type": "number",
  330. },
  331. },
  332. "title": "123",
  333. "variables": [],
  334. "answer": "123",
  335. "code_language": "python3",
  336. "code": code,
  337. },
  338. }
  339. node = init_code_node(code_config)
  340. # execute node
  341. result = node._run()
  342. assert isinstance(result, NodeRunResult)
  343. assert result.status == WorkflowNodeExecutionStatus.SUCCEEDED