Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

test_workflow.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import dataclasses
  2. import json
  3. from unittest import mock
  4. from uuid import uuid4
  5. from constants import HIDDEN_VALUE
  6. from core.file.enums import FileTransferMethod, FileType
  7. from core.file.models import File
  8. from core.variables import FloatVariable, IntegerVariable, SecretVariable, StringVariable
  9. from core.variables.segments import IntegerSegment, Segment
  10. from factories.variable_factory import build_segment
  11. from models.model import EndUser
  12. from models.workflow import Workflow, WorkflowDraftVariable, WorkflowNodeExecutionModel, is_system_variable_editable
  13. def test_environment_variables():
  14. # tenant_id context variable removed - using current_user.current_tenant_id directly
  15. # Create a Workflow instance
  16. workflow = Workflow(
  17. tenant_id="tenant_id",
  18. app_id="app_id",
  19. type="workflow",
  20. version="draft",
  21. graph="{}",
  22. features="{}",
  23. created_by="account_id",
  24. environment_variables=[],
  25. conversation_variables=[],
  26. )
  27. # Create some EnvironmentVariable instances
  28. variable1 = StringVariable.model_validate(
  29. {"name": "var1", "value": "value1", "id": str(uuid4()), "selector": ["env", "var1"]}
  30. )
  31. variable2 = IntegerVariable.model_validate(
  32. {"name": "var2", "value": 123, "id": str(uuid4()), "selector": ["env", "var2"]}
  33. )
  34. variable3 = SecretVariable.model_validate(
  35. {"name": "var3", "value": "secret", "id": str(uuid4()), "selector": ["env", "var3"]}
  36. )
  37. variable4 = FloatVariable.model_validate(
  38. {"name": "var4", "value": 3.14, "id": str(uuid4()), "selector": ["env", "var4"]}
  39. )
  40. # Mock current_user as an EndUser
  41. mock_user = mock.Mock(spec=EndUser)
  42. mock_user.tenant_id = "tenant_id"
  43. with (
  44. mock.patch("core.helper.encrypter.encrypt_token", return_value="encrypted_token"),
  45. mock.patch("core.helper.encrypter.decrypt_token", return_value="secret"),
  46. mock.patch("models.workflow.current_user", mock_user),
  47. ):
  48. # Set the environment_variables property of the Workflow instance
  49. variables = [variable1, variable2, variable3, variable4]
  50. workflow.environment_variables = variables
  51. # Get the environment_variables property and assert its value
  52. assert workflow.environment_variables == variables
  53. def test_update_environment_variables():
  54. # tenant_id context variable removed - using current_user.current_tenant_id directly
  55. # Create a Workflow instance
  56. workflow = Workflow(
  57. tenant_id="tenant_id",
  58. app_id="app_id",
  59. type="workflow",
  60. version="draft",
  61. graph="{}",
  62. features="{}",
  63. created_by="account_id",
  64. environment_variables=[],
  65. conversation_variables=[],
  66. )
  67. # Create some EnvironmentVariable instances
  68. variable1 = StringVariable.model_validate(
  69. {"name": "var1", "value": "value1", "id": str(uuid4()), "selector": ["env", "var1"]}
  70. )
  71. variable2 = IntegerVariable.model_validate(
  72. {"name": "var2", "value": 123, "id": str(uuid4()), "selector": ["env", "var2"]}
  73. )
  74. variable3 = SecretVariable.model_validate(
  75. {"name": "var3", "value": "secret", "id": str(uuid4()), "selector": ["env", "var3"]}
  76. )
  77. variable4 = FloatVariable.model_validate(
  78. {"name": "var4", "value": 3.14, "id": str(uuid4()), "selector": ["env", "var4"]}
  79. )
  80. # Mock current_user as an EndUser
  81. mock_user = mock.Mock(spec=EndUser)
  82. mock_user.tenant_id = "tenant_id"
  83. with (
  84. mock.patch("core.helper.encrypter.encrypt_token", return_value="encrypted_token"),
  85. mock.patch("core.helper.encrypter.decrypt_token", return_value="secret"),
  86. mock.patch("models.workflow.current_user", mock_user),
  87. ):
  88. variables = [variable1, variable2, variable3, variable4]
  89. # Set the environment_variables property of the Workflow instance
  90. workflow.environment_variables = variables
  91. assert workflow.environment_variables == [variable1, variable2, variable3, variable4]
  92. # Update the name of variable3 and keep the value as it is
  93. variables[2] = variable3.model_copy(
  94. update={
  95. "name": "new name",
  96. "value": HIDDEN_VALUE,
  97. }
  98. )
  99. workflow.environment_variables = variables
  100. assert workflow.environment_variables[2].name == "new name"
  101. assert workflow.environment_variables[2].value == variable3.value
  102. def test_to_dict():
  103. # tenant_id context variable removed - using current_user.current_tenant_id directly
  104. # Create a Workflow instance
  105. workflow = Workflow(
  106. tenant_id="tenant_id",
  107. app_id="app_id",
  108. type="workflow",
  109. version="draft",
  110. graph="{}",
  111. features="{}",
  112. created_by="account_id",
  113. environment_variables=[],
  114. conversation_variables=[],
  115. )
  116. # Create some EnvironmentVariable instances
  117. # Mock current_user as an EndUser
  118. mock_user = mock.Mock(spec=EndUser)
  119. mock_user.tenant_id = "tenant_id"
  120. with (
  121. mock.patch("core.helper.encrypter.encrypt_token", return_value="encrypted_token"),
  122. mock.patch("core.helper.encrypter.decrypt_token", return_value="secret"),
  123. mock.patch("models.workflow.current_user", mock_user),
  124. ):
  125. # Set the environment_variables property of the Workflow instance
  126. workflow.environment_variables = [
  127. SecretVariable.model_validate({"name": "secret", "value": "secret", "id": str(uuid4())}),
  128. StringVariable.model_validate({"name": "text", "value": "text", "id": str(uuid4())}),
  129. ]
  130. workflow_dict = workflow.to_dict()
  131. assert workflow_dict["environment_variables"][0]["value"] == ""
  132. assert workflow_dict["environment_variables"][1]["value"] == "text"
  133. workflow_dict = workflow.to_dict(include_secret=True)
  134. assert workflow_dict["environment_variables"][0]["value"] == "secret"
  135. assert workflow_dict["environment_variables"][1]["value"] == "text"
  136. class TestWorkflowNodeExecution:
  137. def test_execution_metadata_dict(self):
  138. node_exec = WorkflowNodeExecutionModel()
  139. node_exec.execution_metadata = None
  140. assert node_exec.execution_metadata_dict == {}
  141. original = {"a": 1, "b": ["2"]}
  142. node_exec.execution_metadata = json.dumps(original)
  143. assert node_exec.execution_metadata_dict == original
  144. class TestIsSystemVariableEditable:
  145. def test_is_system_variable(self):
  146. cases = [
  147. ("query", True),
  148. ("files", True),
  149. ("dialogue_count", False),
  150. ("conversation_id", False),
  151. ("user_id", False),
  152. ("app_id", False),
  153. ("workflow_id", False),
  154. ("workflow_run_id", False),
  155. ]
  156. for name, editable in cases:
  157. assert editable == is_system_variable_editable(name)
  158. assert is_system_variable_editable("invalid_or_new_system_variable") == False
  159. class TestWorkflowDraftVariableGetValue:
  160. def test_get_value_by_case(self):
  161. @dataclasses.dataclass
  162. class TestCase:
  163. name: str
  164. value: Segment
  165. tenant_id = "test_tenant_id"
  166. test_file = File(
  167. tenant_id=tenant_id,
  168. type=FileType.IMAGE,
  169. transfer_method=FileTransferMethod.REMOTE_URL,
  170. remote_url="https://example.com/example.jpg",
  171. filename="example.jpg",
  172. extension=".jpg",
  173. mime_type="image/jpeg",
  174. size=100,
  175. )
  176. cases: list[TestCase] = [
  177. TestCase(
  178. name="number/int",
  179. value=build_segment(1),
  180. ),
  181. TestCase(
  182. name="number/float",
  183. value=build_segment(1.0),
  184. ),
  185. TestCase(
  186. name="string",
  187. value=build_segment("a"),
  188. ),
  189. TestCase(
  190. name="object",
  191. value=build_segment({}),
  192. ),
  193. TestCase(
  194. name="file",
  195. value=build_segment(test_file),
  196. ),
  197. TestCase(
  198. name="array[any]",
  199. value=build_segment([1, "a"]),
  200. ),
  201. TestCase(
  202. name="array[string]",
  203. value=build_segment(["a", "b"]),
  204. ),
  205. TestCase(
  206. name="array[number]/int",
  207. value=build_segment([1, 2]),
  208. ),
  209. TestCase(
  210. name="array[number]/float",
  211. value=build_segment([1.0, 2.0]),
  212. ),
  213. TestCase(
  214. name="array[number]/mixed",
  215. value=build_segment([1, 2.0]),
  216. ),
  217. TestCase(
  218. name="array[object]",
  219. value=build_segment([{}, {"a": 1}]),
  220. ),
  221. TestCase(
  222. name="none",
  223. value=build_segment(None),
  224. ),
  225. ]
  226. for idx, c in enumerate(cases, 1):
  227. fail_msg = f"test case {c.name} failed, index={idx}"
  228. draft_var = WorkflowDraftVariable()
  229. draft_var.set_value(c.value)
  230. assert c.value == draft_var.get_value(), fail_msg
  231. def test_file_variable_preserves_all_fields(self):
  232. """Test that File type variables preserve all fields during encoding/decoding."""
  233. tenant_id = "test_tenant_id"
  234. # Create a File with specific field values
  235. test_file = File(
  236. id="test_file_id",
  237. tenant_id=tenant_id,
  238. type=FileType.IMAGE,
  239. transfer_method=FileTransferMethod.REMOTE_URL,
  240. remote_url="https://example.com/test.jpg",
  241. filename="test.jpg",
  242. extension=".jpg",
  243. mime_type="image/jpeg",
  244. size=12345, # Specific size to test preservation
  245. storage_key="test_storage_key",
  246. )
  247. # Create a FileSegment and WorkflowDraftVariable
  248. file_segment = build_segment(test_file)
  249. draft_var = WorkflowDraftVariable()
  250. draft_var.set_value(file_segment)
  251. # Retrieve the value and verify all fields are preserved
  252. retrieved_segment = draft_var.get_value()
  253. retrieved_file = retrieved_segment.value
  254. # Verify all important fields are preserved
  255. assert retrieved_file.id == test_file.id
  256. assert retrieved_file.tenant_id == test_file.tenant_id
  257. assert retrieved_file.type == test_file.type
  258. assert retrieved_file.transfer_method == test_file.transfer_method
  259. assert retrieved_file.remote_url == test_file.remote_url
  260. assert retrieved_file.filename == test_file.filename
  261. assert retrieved_file.extension == test_file.extension
  262. assert retrieved_file.mime_type == test_file.mime_type
  263. assert retrieved_file.size == test_file.size # This was the main issue being fixed
  264. # Note: storage_key is not serialized in model_dump() so it won't be preserved
  265. # Verify the segments have the same type and the important fields match
  266. assert file_segment.value_type == retrieved_segment.value_type
  267. def test_get_and_set_value(self):
  268. draft_var = WorkflowDraftVariable()
  269. int_var = IntegerSegment(value=1)
  270. draft_var.set_value(int_var)
  271. value = draft_var.get_value()
  272. assert value == int_var