1
0

feat: 增强模板条件渲染表达式支持

使用 simpleeval 库替换原有的简单正则匹配,支持复杂的条件表达式评估。新增 ConditionEvaluator 类处理条件逻辑,支持比较运算、逻辑运算、成员测试、数学计算和内置函数,同时保持向后兼容性。
This commit is contained in:
2026-03-03 17:28:23 +08:00
parent 01a93ce13b
commit 16ca9d77cd
16 changed files with 1437 additions and 31 deletions

View File

@@ -145,15 +145,36 @@ class TestEvaluateCondition:
assert result is False
def test_evaluate_condition_with_missing_variable(self, sample_template):
"""测试缺失变量条件为假"""
"""测试缺失变量会抛出错误"""
template = Template("title-slide", templates_dir=sample_template)
result = template.evaluate_condition("{subtitle != ''}", {})
assert result is False
with pytest.raises(YAMLError, match="条件表达式中的变量未定义"):
template.evaluate_condition("{subtitle != ''}", {})
def test_evaluate_condition_unrecognized_format_returns_true(self, sample_template):
"""测试无法识别的条件格式默认返回 True"""
def test_evaluate_condition_complex_logic(self, sample_template):
"""测试复杂逻辑表达式"""
template = Template("title-slide", templates_dir=sample_template)
result = template.evaluate_condition("some other format", {})
result = template.evaluate_condition(
"{count > 0 and status == 'active'}",
{"count": 5, "status": "active"}
)
assert result is True
def test_evaluate_condition_member_test(self, sample_template):
"""测试成员测试表达式"""
template = Template("title-slide", templates_dir=sample_template)
result = template.evaluate_condition(
"{status in ['draft', 'review']}",
{"status": "draft"}
)
assert result is True
def test_evaluate_condition_math_operation(self, sample_template):
"""测试数学运算表达式"""
template = Template("title-slide", templates_dir=sample_template)
result = template.evaluate_condition(
"{(price * discount) > 50}",
{"price": 100, "discount": 0.8}
)
assert result is True