Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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