Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

refactor(api): enable strict typing for core variables tests (#43878)

Eddy ZHANG6e002605dc1a
diff --git a/api/tests/unit_tests/core/variables/test_segment.py b/api/tests/unit_tests/core/variables/test_segment.py
index f65e5bbde75..5d4c6e56873 100644
--- a/api/tests/unit_tests/core/variables/test_segment.py
+++ b/api/tests/unit_tests/core/variables/test_segment.py
@@ -88,7 +88,7 @@ def _build_variable_pool(
return variable_pool
-def test_segment_group_to_text():
+def test_segment_group_to_text() -> None:
variable_pool = _build_variable_pool(
system_variables=build_system_variables(user_id="fake-user-id"),
environment_variables=[
@@ -108,7 +108,7 @@ def test_segment_group_to_text():
)
-def test_convert_constant_to_segment_group():
+def test_convert_constant_to_segment_group() -> None:
variable_pool = _build_variable_pool(
system_variables=build_system_variables(user_id="1", app_id="1", workflow_id="1"),
)
@@ -118,7 +118,7 @@ def test_convert_constant_to_segment_group():
assert segments_group.log == "Hello, world!"
-def test_convert_variable_to_segment_group():
+def test_convert_variable_to_segment_group() -> None:
variable_pool = _build_variable_pool(system_variables=build_system_variables(user_id="fake-user-id"))
template = "{{#sys.user_id#}}"
segments_group = convert_template(variable_pool, template)
@@ -161,28 +161,28 @@ def create_test_file(
class TestSegmentDumpAndLoad:
"""Test suite for segment and variable serialization/deserialization"""
- def test_segments(self):
+ def test_segments(self) -> None:
"""Test basic segment serialization compatibility"""
model = _Segments(segments=[IntegerSegment(value=1), StringSegment(value="a")])
json = model.model_dump_json()
loaded = _Segments.model_validate_json(json)
assert loaded == model
- def test_segment_number(self):
+ def test_segment_number(self) -> None:
"""Test number segment serialization compatibility"""
model = _Segments(segments=[IntegerSegment(value=1), FloatSegment(value=1.0)])
json = model.model_dump_json()
loaded = _Segments.model_validate_json(json)
assert loaded == model
- def test_variables(self):
+ def test_variables(self) -> None:
"""Test variable serialization compatibility"""
model = _Variables(variables=[IntegerVariable(value=1, name="int"), StringVariable(value="a", name="str")])
json = model.model_dump_json()
restored = _Variables.model_validate_json(json)
assert restored == model
- def test_all_segments_serialization(self):
+ def test_all_segments_serialization(self) -> None:
"""Test file-aware segment serialization through Dify's model boundary."""
# Create one instance of each segment type
test_file = create_test_file()
@@ -224,7 +224,7 @@ class TestSegmentDumpAndLoad:
else:
assert loaded_segment.value == original.value
- def test_all_variables_serialization(self):
+ def test_all_variables_serialization(self) -> None:
"""Test file-aware variable serialization through Dify's model boundary."""
# Create one instance of each variable type
test_file = create_test_file()
@@ -267,7 +267,7 @@ class TestSegmentDumpAndLoad:
else:
assert loaded_variable.value == original.value
- def test_segment_discriminator_function_for_segment_types(self):
+ def test_segment_discriminator_function_for_segment_types(self) -> None:
"""Test the segment discriminator function"""
@dataclasses.dataclass
@@ -335,7 +335,7 @@ class TestSegmentDumpAndLoad:
f"get_segment_discriminator failed for serialized form of type {type(segment)}"
)
- def test_variable_discriminator_function_for_variable_types(self):
+ def test_variable_discriminator_function_for_variable_types(self) -> None:
"""Test the variable discriminator function"""
@dataclasses.dataclass
@@ -407,7 +407,7 @@ class TestSegmentDumpAndLoad:
f"get_segment_discriminator failed for serialized form of type {type(variable)}"
)
- def test_invalid_value_for_discriminator(self):
+ def test_invalid_value_for_discriminator(self) -> None:
# Test invalid cases
assert get_segment_discriminator({"value_type": "invalid"}) is None
assert get_segment_discriminator({}) is None
@@ -417,7 +417,7 @@ class TestSegmentDumpAndLoad:
class TestSegmentAdditionalProperties:
- def test_base_segment_text_log_markdown_size_and_to_object(self):
+ def test_base_segment_text_log_markdown_size_and_to_object(self) -> None:
"""Ensure StringSegment exposes text, log, markdown, size and to_object."""
segment = StringSegment(value="hello")
@@ -427,7 +427,7 @@ class TestSegmentAdditionalProperties:
assert segment.size > 0
assert segment.to_object() == "hello"
- def test_none_segment_empty_outputs(self):
+ def test_none_segment_empty_outputs(self) -> None:
"""Ensure NoneSegment renders empty text, log and markdown."""
segment = NoneSegment()
@@ -435,7 +435,7 @@ class TestSegmentAdditionalProperties:
assert segment.log == ""
assert segment.markdown == ""
- def test_object_segment_json_outputs(self):
+ def test_object_segment_json_outputs(self) -> None:
"""Ensure ObjectSegment renders JSON output for text, log and markdown."""
segment = ObjectSegment(value={"key": "值", "n": 1})
@@ -443,7 +443,7 @@ class TestSegmentAdditionalProperties:
assert segment.log == '{\n "key": "值",\n "n": 1\n}'
assert segment.markdown == '{\n "key": "值",\n "n": 1\n}'
- def test_array_segment_text_and_markdown(self):
+ def test_array_segment_text_and_markdown(self) -> None:
"""Ensure ArrayAnySegment handles empty/non-empty text and markdown rendering."""
empty_segment = ArrayAnySegment(value=[])
non_empty_segment = ArrayAnySegment(value=[1, "two"])
@@ -452,7 +452,7 @@ class TestSegmentAdditionalProperties:
assert non_empty_segment.text == "[1, 'two']"
assert non_empty_segment.markdown == "- 1\n- two"
- def test_file_segment_properties(self):
+ def test_file_segment_properties(self) -> None:
"""Ensure FileSegment markdown, text and log fields match expected behavior."""
file = create_test_file(transfer_method=FileTransferMethod.REMOTE_URL, filename="doc.txt")
segment = FileSegment(value=file)
@@ -461,7 +461,7 @@ class TestSegmentAdditionalProperties:
assert segment.log == ""
assert segment.text == ""
- def test_array_string_segment_text_branches(self):
+ def test_array_string_segment_text_branches(self) -> None:
"""Ensure ArrayStringSegment text handling for empty and non-empty values."""
empty_segment = ArrayStringSegment(value=[])
non_empty_segment = ArrayStringSegment(value=["hello", "世界"])
@@ -469,7 +469,7 @@ class TestSegmentAdditionalProperties:
assert empty_segment.text == ""
assert non_empty_segment.text == '["hello", "世界"]'
- def test_array_file_segment_markdown_and_empty_text_log(self):
+ def test_array_file_segment_markdown_and_empty_text_log(self) -> None:
"""Ensure ArrayFileSegment markdown renders links and text/log stay empty."""
file1 = create_test_file(transfer_method=FileTransferMethod.REMOTE_URL, filename="a.txt")
file2 = create_test_file(transfer_method=FileTransferMethod.REMOTE_URL, filename="b.txt")
@@ -481,7 +481,7 @@ class TestSegmentAdditionalProperties:
class TestSegmentGroupAdditional:
- def test_segment_group_markdown_and_to_object(self):
+ def test_segment_group_markdown_and_to_object(self) -> None:
group = SegmentGroup(value=[StringSegment(value="A"), NoneSegment(), StringSegment(value="B")])
assert group.markdown == "AB"
@@ -489,41 +489,43 @@ class TestSegmentGroupAdditional:
class TestSegmentUtils:
- def test_to_selector_without_paths(self):
+ def test_to_selector_without_paths(self) -> None:
assert to_selector("node-1", "output") == ["node-1", "output"]
- def test_to_selector_with_paths(self):
+ def test_to_selector_with_paths(self) -> None:
assert to_selector("node-1", "output", ("a", "b")) == ["node-1", "output", "a", "b"]
- def test_array_file_segment_serialization(self):
+ def test_array_file_segment_serialization(self) -> None:
file1 = create_test_file(transfer_method=FileTransferMethod.REMOTE_URL, filename="a.txt")
file2 = create_test_file(transfer_method=FileTransferMethod.REMOTE_URL, filename="b.txt")
result = segment_orjson_default(ArrayFileSegment(value=[file1, file2]))
+ assert isinstance(result, list)
assert len(result) == 2
assert result[0]["filename"] == "a.txt"
assert result[1]["filename"] == "b.txt"
- def test_file_segment_serialization(self):
+ def test_file_segment_serialization(self) -> None:
file = create_test_file(transfer_method=FileTransferMethod.REMOTE_URL, filename="single.txt")
result = segment_orjson_default(FileSegment(value=file))
+ assert isinstance(result, dict)
assert result["filename"] == "single.txt"
assert result["remote_url"] == "https://example.com/file.txt"
- def test_segment_group_and_segment_serialization(self):
+ def test_segment_group_and_segment_serialization(self) -> None:
group = SegmentGroup(value=[StringSegment(value="a"), StringSegment(value="b")])
assert segment_orjson_default(group) == ["a", "b"]
assert segment_orjson_default(StringSegment(value="value")) == "value"
- def test_segment_orjson_default_unsupported_type(self):
+ def test_segment_orjson_default_unsupported_type(self) -> None:
with pytest.raises(TypeError, match="not JSON serializable"):
segment_orjson_default(object())
- def test_dumps_with_segments(self):
+ def test_dumps_with_segments(self) -> None:
data = {
"segment": StringSegment(value="hello"),
"group": SegmentGroup(value=[StringSegment(value="x"), StringSegment(value="y")]),
diff --git a/api/tests/unit_tests/core/variables/test_segment_type.py b/api/tests/unit_tests/core/variables/test_segment_type.py
index 009899a92d2..d8637440927 100644
--- a/api/tests/unit_tests/core/variables/test_segment_type.py
+++ b/api/tests/unit_tests/core/variables/test_segment_type.py
@@ -13,7 +13,7 @@ class TestSegmentTypeIsArrayType:
correct identification of array and non-array types.
"""
- def test_is_array_type(self):
+ def test_is_array_type(self) -> None:
"""
Test that all SegmentType enum values are covered in our test cases.
@@ -52,7 +52,7 @@ class TestSegmentTypeIsArrayType:
covered_types = set(expected_array_types) | set(expected_non_array_types)
assert covered_types == set(SegmentType), "All SegmentType values should be covered in tests"
- def test_all_enum_values_are_supported(self):
+ def test_all_enum_values_are_supported(self) -> None:
"""
Test that all enum values are supported and return boolean values.
@@ -70,7 +70,7 @@ class TestSegmentTypeIsValidArrayValidation:
Test SegmentType.is_valid with array types using different validation strategies.
"""
- def test_array_validation_all_success(self):
+ def test_array_validation_all_success(self) -> None:
# Arrange
value = ["hello", "world", "foo"]
# Act
@@ -78,7 +78,7 @@ class TestSegmentTypeIsValidArrayValidation:
# Assert
assert is_valid
- def test_array_validation_all_fail(self):
+ def test_array_validation_all_fail(self) -> None:
# Arrange
value = ["hello", 123, "world"]
# Act
@@ -86,7 +86,7 @@ class TestSegmentTypeIsValidArrayValidation:
# Assert
assert not is_valid
- def test_array_validation_first(self):
+ def test_array_validation_first(self) -> None:
# Arrange
value = ["hello", 123, None]
# Act
@@ -94,7 +94,7 @@ class TestSegmentTypeIsValidArrayValidation:
# Assert
assert is_valid
- def test_array_validation_none(self):
+ def test_array_validation_none(self) -> None:
# Arrange
value = [1, 2, 3]
# Act
@@ -111,7 +111,7 @@ class TestSegmentTypeGetZeroValue:
correct zero value generation for each type.
"""
- def test_array_types_return_empty_list(self):
+ def test_array_types_return_empty_list(self) -> None:
"""Test that all array types return empty list segments."""
array_types = [
SegmentType.ARRAY_ANY,
@@ -126,31 +126,31 @@ class TestSegmentTypeGetZeroValue:
assert result.value == []
assert result.value_type == seg_type
- def test_object_returns_empty_dict(self):
+ def test_object_returns_empty_dict(self) -> None:
"""Test that OBJECT type returns empty dictionary segment."""
result = SegmentType.get_zero_value(SegmentType.OBJECT)
assert result.value == {}
assert result.value_type == SegmentType.OBJECT
- def test_string_returns_empty_string(self):
+ def test_string_returns_empty_string(self) -> None:
"""Test that STRING type returns empty string segment."""
result = SegmentType.get_zero_value(SegmentType.STRING)
assert result.value == ""
assert result.value_type == SegmentType.STRING
- def test_integer_returns_zero(self):
+ def test_integer_returns_zero(self) -> None:
"""Test that INTEGER type returns zero segment."""
result = SegmentType.get_zero_value(SegmentType.INTEGER)
assert result.value == 0
assert result.value_type == SegmentType.INTEGER
- def test_float_returns_zero_point_zero(self):
+ def test_float_returns_zero_point_zero(self) -> None:
"""Test that FLOAT type returns 0.0 segment."""
result = SegmentType.get_zero_value(SegmentType.FLOAT)
assert result.value == 0.0
assert result.value_type == SegmentType.FLOAT
- def test_number_returns_zero(self):
+ def test_number_returns_zero(self) -> None:
"""Test that NUMBER type returns zero segment."""
result = SegmentType.get_zero_value(SegmentType.NUMBER)
assert result.value == 0
@@ -160,13 +160,13 @@ class TestSegmentTypeGetZeroValue:
# Verify that exposed_type returns NUMBER for frontend compatibility
assert result.value_type.exposed_type() == SegmentType.NUMBER
- def test_boolean_returns_false(self):
+ def test_boolean_returns_false(self) -> None:
"""Test that BOOLEAN type returns False segment."""
result = SegmentType.get_zero_value(SegmentType.BOOLEAN)
assert result.value is False
assert result.value_type == SegmentType.BOOLEAN
- def test_unsupported_types_raise_value_error(self):
+ def test_unsupported_types_raise_value_error(self) -> None:
"""Test that unsupported types raise ValueError."""
unsupported_types = [
SegmentType.SECRET,
@@ -202,12 +202,12 @@ class TestSegmentTypeInferSegmentType:
({"k": "v"}, SegmentType.OBJECT),
],
)
- def test_infer_segment_type_supported_values(self, value, expected):
+ def test_infer_segment_type_supported_values(self, value: object, expected: SegmentType) -> None:
assert SegmentType.infer_segment_type(value) == expected
class TestSegmentTypeAdditionalMethods:
- def test_cast_value_for_bool_number_and_array_number(self):
+ def test_cast_value_for_bool_number_and_array_number(self) -> None:
assert SegmentType.cast_value(True, SegmentType.INTEGER) == 1
assert SegmentType.cast_value(False, SegmentType.NUMBER) == 0
assert SegmentType.cast_value([True, False], SegmentType.ARRAY_NUMBER) == [1, 0]
@@ -216,7 +216,7 @@ class TestSegmentTypeAdditionalMethods:
assert SegmentType.cast_value(mixed, SegmentType.ARRAY_NUMBER) is mixed
assert SegmentType.cast_value("x", SegmentType.STRING) == "x"
- def test_exposed_type_and_element_type(self):
+ def test_exposed_type_and_element_type(self) -> None:
assert SegmentType.INTEGER.exposed_type() == SegmentType.NUMBER
assert SegmentType.FLOAT.exposed_type() == SegmentType.NUMBER
assert SegmentType.STRING.exposed_type() == SegmentType.STRING
@@ -227,12 +227,12 @@ class TestSegmentTypeAdditionalMethods:
with pytest.raises(ValueError, match="element_type is only supported by array type"):
SegmentType.STRING.element_type()
- def test_group_validation_for_segment_group_and_list(self):
+ def test_group_validation_for_segment_group_and_list(self) -> None:
valid_group = SegmentGroup(value=[StringSegment(value="a")])
assert SegmentType.GROUP.is_valid(valid_group) is True
assert SegmentType.GROUP.is_valid([StringSegment(value="b")]) is True
assert SegmentType.GROUP.is_valid(["not-segment"]) is False
- def test_unreachable_assertion_branch(self):
+ def test_unreachable_assertion_branch(self) -> None:
with pytest.raises(AssertionError, match="Expected code to be unreachable"):
SegmentType.is_valid("not-a-segment-type", None) # type: ignore[arg-type]
diff --git a/api/tests/unit_tests/core/variables/test_variables.py b/api/tests/unit_tests/core/variables/test_variables.py
index dae5e1ce984..417db78cc8f 100644
--- a/api/tests/unit_tests/core/variables/test_variables.py
+++ b/api/tests/unit_tests/core/variables/test_variables.py
@@ -14,25 +14,25 @@ from graphon.variables import (
from graphon.variables.variables import VariableBase
-def test_frozen_variables():
+def test_frozen_variables() -> None:
var = StringVariable(name="text", value="text")
with pytest.raises(ValidationError):
- var.value = "new value"
+ var.value = "new value" # pyrefly: ignore[read-only]
int_var = IntegerVariable(name="integer", value=42)
with pytest.raises(ValidationError):
- int_var.value = 100
+ int_var.value = 100 # pyrefly: ignore[read-only]
float_var = FloatVariable(name="float", value=3.14)
with pytest.raises(ValidationError):
- float_var.value = 2.718
+ float_var.value = 2.718 # pyrefly: ignore[read-only]
secret_var = SecretVariable(name="secret", value="secret_value")
with pytest.raises(ValidationError):
- secret_var.value = "new_secret_value"
+ secret_var.value = "new_secret_value" # pyrefly: ignore[read-only]
-def test_variable_value_type_immutable():
+def test_variable_value_type_immutable() -> None:
with pytest.raises(ValidationError):
StringVariable(value_type=SegmentType.ARRAY_ANY, name="text", value="text")
@@ -52,7 +52,7 @@ def test_variable_value_type_immutable():
SecretVariable(value_type=SegmentType.ARRAY_ANY, name=var.name, value=var.value)
-def test_object_variable_to_object():
+def test_object_variable_to_object() -> None:
var = ObjectVariable(
name="object",
value={
@@ -75,7 +75,7 @@ def test_object_variable_to_object():
}
-def test_variable_to_object():
+def test_variable_to_object() -> None:
var: VariableBase = StringVariable(name="text", value="text")
assert var.to_object() == "text"
var = IntegerVariable(name="integer", value=42)
@@ -86,6 +86,6 @@ def test_variable_to_object():
assert var.to_object() == "secret_value"
-def test_array_file_variable_is_array_variable():
+def test_array_file_variable_is_array_variable() -> None:
var = ArrayFileVariable(name="files", value=[])
assert isinstance(var, ArrayVariable)
diff --git a/api/tests/unit_tests/pyrefly.toml b/api/tests/unit_tests/pyrefly.toml
index 39b0dd20447..90112bf29a3 100644
--- a/api/tests/unit_tests/pyrefly.toml
+++ b/api/tests/unit_tests/pyrefly.toml
@@ -507,9 +507,6 @@ project-excludes = [
"core/trigger/utils/test_utils_encryption.py",
"core/trigger/utils/test_utils_endpoint.py",
"core/trigger/utils/test_utils_locks.py",
- "core/variables/test_segment.py",
- "core/variables/test_segment_type.py",
- "core/variables/test_variables.py",
"core/workflow/context/test_execution_context.py",
"core/workflow/context/test_flask_app_context.py",
"core/workflow/entities/test_private_workflow_pause.py",