feat: 添加模板变量验证功能
- 在 ResourceValidator 中添加 validate_template_vars 方法 - 在验证阶段检查用户是否提供了模板所需的必需变量 - 缺少必需变量时返回 ERROR 级别错误 - 添加 9 个单元测试用例验证功能 - 同步更新 OpenSpec 规格文档
This commit is contained in:
@@ -0,0 +1,2 @@
|
|||||||
|
schema: spec-driven
|
||||||
|
created: 2026-03-02
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
## Context
|
||||||
|
|
||||||
|
当前验证器 (`validators/validator.py`) 已具备以下验证能力:
|
||||||
|
- YAML 结构验证(slides 字段)
|
||||||
|
- 元素类型和属性验证
|
||||||
|
- 几何验证(元素位置和尺寸)
|
||||||
|
- 资源验证(图片文件、模板文件存在性)
|
||||||
|
|
||||||
|
但缺少对模板变量完整性的验证。当 YAML 使用模板时,如果用户没有提供模板所需的必需变量(如 `title`),验证器仍会返回成功,直到转换阶段才发现问题。
|
||||||
|
|
||||||
|
## Goals / Non-Goals
|
||||||
|
|
||||||
|
**Goals:**
|
||||||
|
- 在验证阶段检查用户是否提供了模板所需的必需变量
|
||||||
|
- 当缺少必需变量时返回 ERROR 级别错误,阻止转换
|
||||||
|
- 提供清晰的错误信息,指出缺少哪个必需变量
|
||||||
|
|
||||||
|
**Non-Goals:**
|
||||||
|
- 不验证模板变量值的类型正确性(由渲染阶段处理)
|
||||||
|
- 不验证模板变量值的业务逻辑有效性
|
||||||
|
- 不修改现有的验证错误格式
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
### 方案:在 ResourceValidator 中添加 validate_template_vars 方法
|
||||||
|
|
||||||
|
**选择理由:**
|
||||||
|
1. ResourceValidator 已负责模板相关的验证(validate_template),职责匹配
|
||||||
|
2. 可以复用现有的模板加载逻辑
|
||||||
|
3. 对主验证器的影响最小,只需在现有验证流程中调用新方法
|
||||||
|
|
||||||
|
**替代方案考虑:**
|
||||||
|
- 在主验证器中直接实现:会导致主验证器代码膨胀
|
||||||
|
- 新增专门的 TemplateVarValidator:增加复杂度,与现有架构不符
|
||||||
|
|
||||||
|
### 实现要点:
|
||||||
|
1. 在 ResourceValidator 中添加 `validate_template_vars` 方法
|
||||||
|
2. 加载模板文件后,检查模板的 `vars` 字段中的 `required: true` 变量
|
||||||
|
3. 从幻灯片数据中获取 `vars` 字段,与模板要求的必需变量对比
|
||||||
|
4. 缺少必需变量时,添加 ERROR 级别问题
|
||||||
|
|
||||||
|
## Risks / Trade-offs
|
||||||
|
|
||||||
|
**潜在风险:**
|
||||||
|
- [风险] 重复加载模板文件 → [缓解] ResourceValidator 已在 validate_template 中加载一次,可复用加载结果或缓存
|
||||||
|
- [风险] vars 字段嵌套层级复杂 → [缓解] 仅检查顶层 vars 字段,不处理嵌套引用
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
## Why
|
||||||
|
|
||||||
|
当前验证器(`yaml2pptx.py check` 命令)只验证 YAML 语法和元素有效性,但不验证模板变量的完整性。用户在使用模板时如果缺少必需变量(如 title),验证器仍然返回成功,导致用户在转换阶段才发现问题。需要在验证阶段提前发现这类问题,提升用户体验。
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
|
||||||
|
在 `validators/validator.py` 的验证流程中添加模板变量验证功能:
|
||||||
|
1. 检测 YAML 是否使用模板(检查 `slides[].template` 字段)
|
||||||
|
2. 加载模板定义(读取模板 YAML 文件)
|
||||||
|
3. 检查模板中的必需变量是否在 `vars` 中提供
|
||||||
|
4. 如缺少必需变量,添加验证错误
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
### New Capabilities
|
||||||
|
- `template-variable-validation`: 验证器在检查阶段验证模板必需变量是否提供
|
||||||
|
|
||||||
|
### Modified Capabilities
|
||||||
|
- `yaml-validation`: 需要扩展验证范围,加入模板变量完整性检查(新增需求,不是修改现有需求)
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
|
||||||
|
- 主要影响:`validators/validator.py` 的验证逻辑
|
||||||
|
- 次要影响:可能需要调整验证错误信息的格式
|
||||||
|
- 无 API 变更,仅内部验证逻辑增强
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: 验证器必须检查模板必需变量
|
||||||
|
|
||||||
|
当 YAML 使用模板时,系统 SHALL 验证用户是否提供了模板所需的必需变量。
|
||||||
|
|
||||||
|
#### Scenario: 提供所有必需变量
|
||||||
|
|
||||||
|
- **WHEN** 模板定义了 `vars: [{name: title, required: true}]`,且用户 YAML 提供了 `vars: {title: "Hello"}`
|
||||||
|
- **THEN** 验证通过,不报错
|
||||||
|
|
||||||
|
#### Scenario: 缺少必需变量
|
||||||
|
|
||||||
|
- **WHEN** 模板定义了 `vars: [{name: title, required: true}]`,但用户 YAML 的 `vars` 中没有提供 `title`
|
||||||
|
- **THEN** 验证器报告 ERROR 级别错误:"缺少模板必需变量: title"
|
||||||
|
|
||||||
|
#### Scenario: 多个必需变量部分缺失
|
||||||
|
|
||||||
|
- **WHEN** 模板定义了 `vars: [{name: title, required: true}, {name: subtitle, required: true}]`,但用户只提供了 `vars: {title: "Hello"}`
|
||||||
|
- **THEN** 验证器报告 ERROR 级别错误,包含所有缺少的必需变量
|
||||||
|
|
||||||
|
#### Scenario: 可选变量缺失
|
||||||
|
|
||||||
|
- **WHEN** 模板定义了 `vars: [{name: subtitle, required: false}]`,用户没有提供该变量
|
||||||
|
- **THEN** 验证通过,不报错
|
||||||
|
|
||||||
|
#### Scenario: 提供默认值时缺少可选变量
|
||||||
|
|
||||||
|
- **WHEN** 模板定义了 `vars: [{name: subtitle, required: false, default: ""}]`,用户没有提供该变量
|
||||||
|
- **THEN** 验证通过,不报错(使用默认值)
|
||||||
|
|
||||||
|
### Requirement: 验证器必须支持多幻灯片模板变量检查
|
||||||
|
|
||||||
|
系统 SHALL 检查每个使用模板的幻灯片,确保其提供了模板所需的必需变量。
|
||||||
|
|
||||||
|
#### Scenario: 不同幻灯片使用不同模板
|
||||||
|
|
||||||
|
- **WHEN** 幻灯片 1 使用模板 A(需要变量 title),幻灯片 2 使用模板 B(需要变量 image)
|
||||||
|
- **THEN** 验证器分别检查每个幻灯片的变量,提供独立的错误信息
|
||||||
|
|
||||||
|
#### Scenario: 多个幻灯片使用同一模板
|
||||||
|
|
||||||
|
- **WHEN** 幻灯片 1 和幻灯片 2 都使用同一模板,都缺少必需变量
|
||||||
|
- **THEN** 验证器报告两个错误,分别对应各自的幻灯片位置
|
||||||
|
|
||||||
|
### Requirement: 验证器必须提供清晰的错误位置信息
|
||||||
|
|
||||||
|
当缺少必需变量时,验证器 SHALL 在错误信息中包含幻灯片位置。
|
||||||
|
|
||||||
|
#### Scenario: 错误信息包含幻灯片位置
|
||||||
|
|
||||||
|
- **WHEN** 幻灯片 2 使用模板但缺少必需变量
|
||||||
|
- **THEN** 错误信息包含位置:"幻灯片 2: 缺少模板必需变量: title"
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
## 1. 扩展 ResourceValidator
|
||||||
|
|
||||||
|
- [x] 1.1 在 ResourceValidator 中添加 `validate_template_vars` 方法
|
||||||
|
- [x] 1.2 实现加载模板 vars 定义逻辑
|
||||||
|
- [x] 1.3 实现检查用户提供的 vars 是否满足模板必需变量逻辑
|
||||||
|
- [x] 1.4 返回缺少必需变量的验证错误
|
||||||
|
|
||||||
|
## 2. 集成到主验证器
|
||||||
|
|
||||||
|
- [x] 2.1 在 Validator.validate() 中调用 validate_template_vars 方法
|
||||||
|
- [x] 2.2 确保在模板文件验证通过后再进行变量验证
|
||||||
|
|
||||||
|
## 3. 测试
|
||||||
|
|
||||||
|
- [x] 3.1 编写单元测试:提供所有必需变量时验证通过
|
||||||
|
- [x] 3.2 编写单元测试:缺少必需变量时验证失败并返回错误
|
||||||
|
- [x] 3.3 编写单元测试:多个必需变量部分缺失时报告所有缺失变量
|
||||||
|
- [x] 3.4 编写单元测试:可选变量缺失时验证通过
|
||||||
|
- [x] 3.5 编写集成测试:运行 yaml2pptx.py check 命令验证功能
|
||||||
59
openspec/specs/template-variable-validation/spec.md
Normal file
59
openspec/specs/template-variable-validation/spec.md
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
# Template Variable Validation
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
验证器在检查阶段验证模板必需变量是否提供。当 YAML 使用模板时,系统验证用户是否提供了模板所需的必需变量,避免在转换阶段才发现问题。
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
### Requirement: 验证器必须检查模板必需变量
|
||||||
|
|
||||||
|
当 YAML 使用模板时,系统 SHALL 验证用户是否提供了模板所需的必需变量。
|
||||||
|
|
||||||
|
#### Scenario: 提供所有必需变量
|
||||||
|
|
||||||
|
- **WHEN** 模板定义了 `vars: [{name: title, required: true}]`,且用户 YAML 提供了 `vars: {title: "Hello"}`
|
||||||
|
- **THEN** 验证通过,不报错
|
||||||
|
|
||||||
|
#### Scenario: 缺少必需变量
|
||||||
|
|
||||||
|
- **WHEN** 模板定义了 `vars: [{name: title, required: true}]`,但用户 YAML 的 `vars` 中没有提供 `title`
|
||||||
|
- **THEN** 验证器报告 ERROR 级别错误:"缺少模板必需变量: title"
|
||||||
|
|
||||||
|
#### Scenario: 多个必需变量部分缺失
|
||||||
|
|
||||||
|
- **WHEN** 模板定义了 `vars: [{name: title, required: true}, {name: subtitle, required: true}]`,但用户只提供了 `vars: {title: "Hello"}`
|
||||||
|
- **THEN** 验证器报告 ERROR 级别错误,包含所有缺少的必需变量
|
||||||
|
|
||||||
|
#### Scenario: 可选变量缺失
|
||||||
|
|
||||||
|
- **WHEN** 模板定义了 `vars: [{name: subtitle, required: false}]`,用户没有提供该变量
|
||||||
|
- **THEN** 验证通过,不报错
|
||||||
|
|
||||||
|
#### Scenario: 提供默认值时缺少可选变量
|
||||||
|
|
||||||
|
- **WHEN** 模板定义了 `vars: [{name: subtitle, required: false, default: ""}]`,用户没有提供该变量
|
||||||
|
- **THEN** 验证通过,不报错(使用默认值)
|
||||||
|
|
||||||
|
### Requirement: 验证器必须支持多幻灯片模板变量检查
|
||||||
|
|
||||||
|
系统 SHALL 检查每个使用模板的幻灯片,确保其提供了模板所需的必需变量。
|
||||||
|
|
||||||
|
#### Scenario: 不同幻灯片使用不同模板
|
||||||
|
|
||||||
|
- **WHEN** 幻灯片 1 使用模板 A(需要变量 title),幻灯片 2 使用模板 B(需要变量 image)
|
||||||
|
- **THEN** 验证器分别检查每个幻灯片的变量,提供独立的错误信息
|
||||||
|
|
||||||
|
#### Scenario: 多个幻灯片使用同一模板
|
||||||
|
|
||||||
|
- **WHEN** 幻灯片 1 和幻灯片 2 都使用同一模板,都缺少必需变量
|
||||||
|
- **THEN** 验证器报告两个错误,分别对应各自的幻灯片位置
|
||||||
|
|
||||||
|
### Requirement: 验证器必须提供清晰的错误位置信息
|
||||||
|
|
||||||
|
当缺少必需变量时,验证器 SHALL 在错误信息中包含幻灯片位置。
|
||||||
|
|
||||||
|
#### Scenario: 错误信息包含幻灯片位置
|
||||||
|
|
||||||
|
- **WHEN** 幻灯片 2 使用模板但缺少必需变量
|
||||||
|
- **THEN** 错误信息包含位置:"幻灯片 2: 缺少模板必需变量: title"
|
||||||
@@ -21,10 +21,7 @@ class TestResourceValidator:
|
|||||||
def test_init_with_template_dir(self, temp_dir):
|
def test_init_with_template_dir(self, temp_dir):
|
||||||
"""测试带模板目录初始化"""
|
"""测试带模板目录初始化"""
|
||||||
template_dir = temp_dir / "templates"
|
template_dir = temp_dir / "templates"
|
||||||
validator = ResourceValidator(
|
validator = ResourceValidator(yaml_dir=temp_dir, template_dir=template_dir)
|
||||||
yaml_dir=temp_dir,
|
|
||||||
template_dir=template_dir
|
|
||||||
)
|
|
||||||
assert validator.template_dir == template_dir
|
assert validator.template_dir == template_dir
|
||||||
|
|
||||||
|
|
||||||
@@ -34,14 +31,14 @@ class TestValidateImage:
|
|||||||
def test_existing_image(self, temp_dir, sample_image):
|
def test_existing_image(self, temp_dir, sample_image):
|
||||||
"""测试存在的图片文件"""
|
"""测试存在的图片文件"""
|
||||||
validator = ResourceValidator(yaml_dir=temp_dir)
|
validator = ResourceValidator(yaml_dir=temp_dir)
|
||||||
elem = type('Element', (), {'src': sample_image.name})()
|
elem = type("Element", (), {"src": sample_image.name})()
|
||||||
issues = validator.validate_image(elem, 1, 1)
|
issues = validator.validate_image(elem, 1, 1)
|
||||||
assert len(issues) == 0
|
assert len(issues) == 0
|
||||||
|
|
||||||
def test_nonexistent_image(self, temp_dir):
|
def test_nonexistent_image(self, temp_dir):
|
||||||
"""测试不存在的图片文件"""
|
"""测试不存在的图片文件"""
|
||||||
validator = ResourceValidator(yaml_dir=temp_dir)
|
validator = ResourceValidator(yaml_dir=temp_dir)
|
||||||
elem = type('Element', (), {'src': 'nonexistent.png'})()
|
elem = type("Element", (), {"src": "nonexistent.png"})()
|
||||||
issues = validator.validate_image(elem, 1, 1)
|
issues = validator.validate_image(elem, 1, 1)
|
||||||
assert len(issues) == 1
|
assert len(issues) == 1
|
||||||
assert issues[0].level == "ERROR"
|
assert issues[0].level == "ERROR"
|
||||||
@@ -50,21 +47,21 @@ class TestValidateImage:
|
|||||||
def test_image_with_absolute_path(self, temp_dir, sample_image):
|
def test_image_with_absolute_path(self, temp_dir, sample_image):
|
||||||
"""测试绝对路径图片"""
|
"""测试绝对路径图片"""
|
||||||
validator = ResourceValidator(yaml_dir=temp_dir)
|
validator = ResourceValidator(yaml_dir=temp_dir)
|
||||||
elem = type('Element', (), {'src': str(sample_image)})()
|
elem = type("Element", (), {"src": str(sample_image)})()
|
||||||
issues = validator.validate_image(elem, 1, 1)
|
issues = validator.validate_image(elem, 1, 1)
|
||||||
assert len(issues) == 0
|
assert len(issues) == 0
|
||||||
|
|
||||||
def test_image_without_src_attribute(self, temp_dir):
|
def test_image_without_src_attribute(self, temp_dir):
|
||||||
"""测试没有 src 属性的元素"""
|
"""测试没有 src 属性的元素"""
|
||||||
validator = ResourceValidator(yaml_dir=temp_dir)
|
validator = ResourceValidator(yaml_dir=temp_dir)
|
||||||
elem = type('Element', (), {})() # 没有 src 属性
|
elem = type("Element", (), {})() # 没有 src 属性
|
||||||
issues = validator.validate_image(elem, 1, 1)
|
issues = validator.validate_image(elem, 1, 1)
|
||||||
assert len(issues) == 0
|
assert len(issues) == 0
|
||||||
|
|
||||||
def test_image_with_empty_src(self, temp_dir):
|
def test_image_with_empty_src(self, temp_dir):
|
||||||
"""测试空 src 字符串"""
|
"""测试空 src 字符串"""
|
||||||
validator = ResourceValidator(yaml_dir=temp_dir)
|
validator = ResourceValidator(yaml_dir=temp_dir)
|
||||||
elem = type('Element', (), {'src': ''})()
|
elem = type("Element", (), {"src": ""})()
|
||||||
issues = validator.validate_image(elem, 1, 1)
|
issues = validator.validate_image(elem, 1, 1)
|
||||||
assert len(issues) == 0
|
assert len(issues) == 0
|
||||||
|
|
||||||
@@ -82,7 +79,7 @@ class TestValidateTemplate:
|
|||||||
def test_template_with_dir_not_specified(self, temp_dir):
|
def test_template_with_dir_not_specified(self, temp_dir):
|
||||||
"""测试使用模板但未指定模板目录"""
|
"""测试使用模板但未指定模板目录"""
|
||||||
validator = ResourceValidator(yaml_dir=temp_dir, template_dir=None)
|
validator = ResourceValidator(yaml_dir=temp_dir, template_dir=None)
|
||||||
slide_data = {'template': 'title-slide'}
|
slide_data = {"template": "title-slide"}
|
||||||
issues = validator.validate_template(slide_data, 1)
|
issues = validator.validate_template(slide_data, 1)
|
||||||
assert len(issues) == 1
|
assert len(issues) == 1
|
||||||
assert issues[0].level == "ERROR"
|
assert issues[0].level == "ERROR"
|
||||||
@@ -93,7 +90,7 @@ class TestValidateTemplate:
|
|||||||
template_dir = temp_dir / "templates"
|
template_dir = temp_dir / "templates"
|
||||||
template_dir.mkdir()
|
template_dir.mkdir()
|
||||||
validator = ResourceValidator(yaml_dir=temp_dir, template_dir=template_dir)
|
validator = ResourceValidator(yaml_dir=temp_dir, template_dir=template_dir)
|
||||||
slide_data = {'template': 'nonexistent'}
|
slide_data = {"template": "nonexistent"}
|
||||||
issues = validator.validate_template(slide_data, 1)
|
issues = validator.validate_template(slide_data, 1)
|
||||||
assert len(issues) == 1
|
assert len(issues) == 1
|
||||||
assert issues[0].level == "ERROR"
|
assert issues[0].level == "ERROR"
|
||||||
@@ -102,10 +99,9 @@ class TestValidateTemplate:
|
|||||||
def test_valid_template_file(self, sample_template):
|
def test_valid_template_file(self, sample_template):
|
||||||
"""测试有效的模板文件"""
|
"""测试有效的模板文件"""
|
||||||
validator = ResourceValidator(
|
validator = ResourceValidator(
|
||||||
yaml_dir=sample_template.parent,
|
yaml_dir=sample_template.parent, template_dir=sample_template
|
||||||
template_dir=sample_template
|
|
||||||
)
|
)
|
||||||
slide_data = {'template': 'title-slide'}
|
slide_data = {"template": "title-slide"}
|
||||||
issues = validator.validate_template(slide_data, 1)
|
issues = validator.validate_template(slide_data, 1)
|
||||||
assert len(issues) == 0
|
assert len(issues) == 0
|
||||||
|
|
||||||
@@ -116,7 +112,7 @@ class TestValidateTemplate:
|
|||||||
(template_dir / "test.yaml").write_text("vars: []\nelements: []")
|
(template_dir / "test.yaml").write_text("vars: []\nelements: []")
|
||||||
|
|
||||||
validator = ResourceValidator(yaml_dir=temp_dir, template_dir=template_dir)
|
validator = ResourceValidator(yaml_dir=temp_dir, template_dir=template_dir)
|
||||||
slide_data = {'template': 'test.yaml'}
|
slide_data = {"template": "test.yaml"}
|
||||||
issues = validator.validate_template(slide_data, 1)
|
issues = validator.validate_template(slide_data, 1)
|
||||||
assert len(issues) == 0
|
assert len(issues) == 0
|
||||||
|
|
||||||
@@ -128,8 +124,116 @@ class TestValidateTemplate:
|
|||||||
(template_dir / "invalid.yaml").write_text("vars: []")
|
(template_dir / "invalid.yaml").write_text("vars: []")
|
||||||
|
|
||||||
validator = ResourceValidator(yaml_dir=temp_dir, template_dir=template_dir)
|
validator = ResourceValidator(yaml_dir=temp_dir, template_dir=template_dir)
|
||||||
slide_data = {'template': 'invalid'}
|
slide_data = {"template": "invalid"}
|
||||||
issues = validator.validate_template(slide_data, 1)
|
issues = validator.validate_template(slide_data, 1)
|
||||||
assert len(issues) == 1
|
assert len(issues) == 1
|
||||||
assert issues[0].level == "ERROR"
|
assert issues[0].level == "ERROR"
|
||||||
assert issues[0].code == "TEMPLATE_STRUCTURE_ERROR"
|
assert issues[0].code == "TEMPLATE_STRUCTURE_ERROR"
|
||||||
|
|
||||||
|
|
||||||
|
class TestValidateTemplateVars:
|
||||||
|
"""validate_template_vars 方法测试"""
|
||||||
|
|
||||||
|
def test_slide_without_template(self, temp_dir):
|
||||||
|
"""测试不使用模板的幻灯片"""
|
||||||
|
validator = ResourceValidator(yaml_dir=temp_dir)
|
||||||
|
slide_data = {}
|
||||||
|
issues = validator.validate_template_vars(slide_data, 1)
|
||||||
|
assert len(issues) == 0
|
||||||
|
|
||||||
|
def test_template_with_dir_not_specified(self, temp_dir):
|
||||||
|
"""测试使用模板但未指定模板目录"""
|
||||||
|
validator = ResourceValidator(yaml_dir=temp_dir, template_dir=None)
|
||||||
|
slide_data = {"template": "title-slide"}
|
||||||
|
issues = validator.validate_template_vars(slide_data, 1)
|
||||||
|
assert len(issues) == 0
|
||||||
|
|
||||||
|
def test_provide_all_required_vars(self, sample_template):
|
||||||
|
"""测试提供所有必需变量时验证通过"""
|
||||||
|
validator = ResourceValidator(
|
||||||
|
yaml_dir=sample_template.parent, template_dir=sample_template
|
||||||
|
)
|
||||||
|
slide_data = {
|
||||||
|
"template": "title-slide",
|
||||||
|
"vars": {"title": "Hello", "subtitle": "World"},
|
||||||
|
}
|
||||||
|
issues = validator.validate_template_vars(slide_data, 1)
|
||||||
|
assert len(issues) == 0
|
||||||
|
|
||||||
|
def test_missing_required_var(self, sample_template):
|
||||||
|
"""测试缺少必需变量时验证失败"""
|
||||||
|
validator = ResourceValidator(
|
||||||
|
yaml_dir=sample_template.parent, template_dir=sample_template
|
||||||
|
)
|
||||||
|
slide_data = {"template": "title-slide", "vars": {"subtitle": "World"}}
|
||||||
|
issues = validator.validate_template_vars(slide_data, 1)
|
||||||
|
assert len(issues) == 1
|
||||||
|
assert issues[0].level == "ERROR"
|
||||||
|
assert issues[0].code == "MISSING_TEMPLATE_REQUIRED_VARS"
|
||||||
|
assert "title" in issues[0].message
|
||||||
|
|
||||||
|
def test_multiple_required_vars_partial_missing(self, temp_dir):
|
||||||
|
"""测试多个必需变量部分缺失"""
|
||||||
|
template_dir = temp_dir / "templates"
|
||||||
|
template_dir.mkdir()
|
||||||
|
template_content = """vars:
|
||||||
|
- name: title
|
||||||
|
required: true
|
||||||
|
- name: subtitle
|
||||||
|
required: true
|
||||||
|
- name: author
|
||||||
|
required: false
|
||||||
|
elements: []
|
||||||
|
"""
|
||||||
|
(template_dir / "multi-var.yaml").write_text(template_content)
|
||||||
|
|
||||||
|
validator = ResourceValidator(yaml_dir=temp_dir, template_dir=template_dir)
|
||||||
|
slide_data = {"template": "multi-var", "vars": {"title": "Hello"}}
|
||||||
|
issues = validator.validate_template_vars(slide_data, 1)
|
||||||
|
assert len(issues) == 1
|
||||||
|
assert issues[0].level == "ERROR"
|
||||||
|
assert "subtitle" in issues[0].message
|
||||||
|
|
||||||
|
def test_optional_var_missing(self, sample_template):
|
||||||
|
"""测试可选变量缺失时验证通过"""
|
||||||
|
validator = ResourceValidator(
|
||||||
|
yaml_dir=sample_template.parent, template_dir=sample_template
|
||||||
|
)
|
||||||
|
slide_data = {"template": "title-slide", "vars": {"title": "Hello"}}
|
||||||
|
issues = validator.validate_template_vars(slide_data, 1)
|
||||||
|
assert len(issues) == 0
|
||||||
|
|
||||||
|
def test_template_with_no_required_vars(self, temp_dir):
|
||||||
|
"""测试模板没有必需变量时"""
|
||||||
|
template_dir = temp_dir / "templates"
|
||||||
|
template_dir.mkdir()
|
||||||
|
template_content = """vars:
|
||||||
|
- name: subtitle
|
||||||
|
required: false
|
||||||
|
elements: []
|
||||||
|
"""
|
||||||
|
(template_dir / "optional-only.yaml").write_text(template_content)
|
||||||
|
|
||||||
|
validator = ResourceValidator(yaml_dir=temp_dir, template_dir=template_dir)
|
||||||
|
slide_data = {"template": "optional-only", "vars": {}}
|
||||||
|
issues = validator.validate_template_vars(slide_data, 1)
|
||||||
|
assert len(issues) == 0
|
||||||
|
|
||||||
|
def test_nonexistent_template_file(self, temp_dir):
|
||||||
|
"""测试模板文件不存在时不报错(由 validate_template 处理)"""
|
||||||
|
template_dir = temp_dir / "templates"
|
||||||
|
template_dir.mkdir()
|
||||||
|
validator = ResourceValidator(yaml_dir=temp_dir, template_dir=template_dir)
|
||||||
|
slide_data = {"template": "nonexistent"}
|
||||||
|
issues = validator.validate_template_vars(slide_data, 1)
|
||||||
|
assert len(issues) == 0
|
||||||
|
|
||||||
|
def test_error_location_contains_slide_number(self, sample_template):
|
||||||
|
"""测试错误信息包含幻灯片位置"""
|
||||||
|
validator = ResourceValidator(
|
||||||
|
yaml_dir=sample_template.parent, template_dir=sample_template
|
||||||
|
)
|
||||||
|
slide_data = {"template": "title-slide", "vars": {}}
|
||||||
|
issues = validator.validate_template_vars(slide_data, 5)
|
||||||
|
assert len(issues) == 1
|
||||||
|
assert "幻灯片 5" in issues[0].location
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ class ResourceValidator:
|
|||||||
issues = []
|
issues = []
|
||||||
location = f"幻灯片 {slide_index}, 元素 {elem_index}"
|
location = f"幻灯片 {slide_index}, 元素 {elem_index}"
|
||||||
|
|
||||||
if not hasattr(element, 'src'):
|
if not hasattr(element, "src"):
|
||||||
return issues
|
return issues
|
||||||
|
|
||||||
src = element.src
|
src = element.src
|
||||||
@@ -52,12 +52,14 @@ class ResourceValidator:
|
|||||||
|
|
||||||
# 检查文件是否存在
|
# 检查文件是否存在
|
||||||
if not src_path.exists():
|
if not src_path.exists():
|
||||||
issues.append(ValidationIssue(
|
issues.append(
|
||||||
level="ERROR",
|
ValidationIssue(
|
||||||
message=f"图片文件不存在: {src}",
|
level="ERROR",
|
||||||
location=location,
|
message=f"图片文件不存在: {src}",
|
||||||
code="IMAGE_FILE_NOT_FOUND"
|
location=location,
|
||||||
))
|
code="IMAGE_FILE_NOT_FOUND",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
return issues
|
return issues
|
||||||
|
|
||||||
@@ -75,36 +77,40 @@ class ResourceValidator:
|
|||||||
issues = []
|
issues = []
|
||||||
location = f"幻灯片 {slide_index}"
|
location = f"幻灯片 {slide_index}"
|
||||||
|
|
||||||
if 'template' not in slide_data:
|
if "template" not in slide_data:
|
||||||
return issues
|
return issues
|
||||||
|
|
||||||
template_name = slide_data['template']
|
template_name = slide_data["template"]
|
||||||
if not template_name:
|
if not template_name:
|
||||||
return issues
|
return issues
|
||||||
|
|
||||||
# 检查是否提供了模板目录
|
# 检查是否提供了模板目录
|
||||||
if not self.template_dir:
|
if not self.template_dir:
|
||||||
issues.append(ValidationIssue(
|
issues.append(
|
||||||
level="ERROR",
|
ValidationIssue(
|
||||||
message=f"使用了模板但未指定模板目录: {template_name}",
|
level="ERROR",
|
||||||
location=location,
|
message=f"使用了模板但未指定模板目录: {template_name}",
|
||||||
code="TEMPLATE_DIR_NOT_SPECIFIED"
|
location=location,
|
||||||
))
|
code="TEMPLATE_DIR_NOT_SPECIFIED",
|
||||||
|
)
|
||||||
|
)
|
||||||
return issues
|
return issues
|
||||||
|
|
||||||
# 解析模板文件路径
|
# 解析模板文件路径
|
||||||
template_path = self.template_dir / template_name
|
template_path = self.template_dir / template_name
|
||||||
if not template_path.suffix:
|
if not template_path.suffix:
|
||||||
template_path = template_path.with_suffix('.yaml')
|
template_path = template_path.with_suffix(".yaml")
|
||||||
|
|
||||||
# 检查模板文件是否存在
|
# 检查模板文件是否存在
|
||||||
if not template_path.exists():
|
if not template_path.exists():
|
||||||
issues.append(ValidationIssue(
|
issues.append(
|
||||||
level="ERROR",
|
ValidationIssue(
|
||||||
message=f"模板文件不存在: {template_name}",
|
level="ERROR",
|
||||||
location=location,
|
message=f"模板文件不存在: {template_name}",
|
||||||
code="TEMPLATE_FILE_NOT_FOUND"
|
location=location,
|
||||||
))
|
code="TEMPLATE_FILE_NOT_FOUND",
|
||||||
|
)
|
||||||
|
)
|
||||||
return issues
|
return issues
|
||||||
|
|
||||||
# 验证模板文件结构
|
# 验证模板文件结构
|
||||||
@@ -112,11 +118,71 @@ class ResourceValidator:
|
|||||||
template_data = load_yaml_file(template_path)
|
template_data = load_yaml_file(template_path)
|
||||||
validate_template_yaml(template_data, str(template_path))
|
validate_template_yaml(template_data, str(template_path))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
issues.append(ValidationIssue(
|
issues.append(
|
||||||
level="ERROR",
|
ValidationIssue(
|
||||||
message=f"模板文件结构错误: {template_name} - {str(e)}",
|
level="ERROR",
|
||||||
location=location,
|
message=f"模板文件结构错误: {template_name} - {str(e)}",
|
||||||
code="TEMPLATE_STRUCTURE_ERROR"
|
location=location,
|
||||||
))
|
code="TEMPLATE_STRUCTURE_ERROR",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
return issues
|
||||||
|
|
||||||
|
def validate_template_vars(self, slide_data: dict, slide_index: int) -> list:
|
||||||
|
"""
|
||||||
|
验证模板变量是否满足要求
|
||||||
|
|
||||||
|
Args:
|
||||||
|
slide_data: 幻灯片数据字典
|
||||||
|
slide_index: 幻灯片索引(从 1 开始)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
验证问题列表
|
||||||
|
"""
|
||||||
|
issues = []
|
||||||
|
location = f"幻灯片 {slide_index}"
|
||||||
|
|
||||||
|
if "template" not in slide_data:
|
||||||
|
return issues
|
||||||
|
|
||||||
|
template_name = slide_data["template"]
|
||||||
|
if not template_name:
|
||||||
|
return issues
|
||||||
|
|
||||||
|
if not self.template_dir:
|
||||||
|
return issues
|
||||||
|
|
||||||
|
template_path = self.template_dir / template_name
|
||||||
|
if not template_path.suffix:
|
||||||
|
template_path = template_path.with_suffix(".yaml")
|
||||||
|
|
||||||
|
if not template_path.exists():
|
||||||
|
return issues
|
||||||
|
|
||||||
|
try:
|
||||||
|
template_data = load_yaml_file(template_path)
|
||||||
|
validate_template_yaml(template_data, str(template_path))
|
||||||
|
except Exception:
|
||||||
|
return issues
|
||||||
|
|
||||||
|
template_vars = template_data.get("vars", [])
|
||||||
|
required_vars = [v["name"] for v in template_vars if v.get("required", False)]
|
||||||
|
|
||||||
|
if not required_vars:
|
||||||
|
return issues
|
||||||
|
|
||||||
|
user_vars = slide_data.get("vars", {})
|
||||||
|
missing_vars = [v for v in required_vars if v not in user_vars]
|
||||||
|
|
||||||
|
if missing_vars:
|
||||||
|
issues.append(
|
||||||
|
ValidationIssue(
|
||||||
|
level="ERROR",
|
||||||
|
message=f"缺少模板必需变量: {', '.join(missing_vars)}",
|
||||||
|
location=location,
|
||||||
|
code="MISSING_TEMPLATE_REQUIRED_VARS",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
return issues
|
return issues
|
||||||
|
|||||||
@@ -45,59 +45,61 @@ class Validator:
|
|||||||
data = load_yaml_file(yaml_path)
|
data = load_yaml_file(yaml_path)
|
||||||
validate_presentation_yaml(data, str(yaml_path))
|
validate_presentation_yaml(data, str(yaml_path))
|
||||||
except YAMLError as e:
|
except YAMLError as e:
|
||||||
errors.append(ValidationIssue(
|
errors.append(
|
||||||
level="ERROR",
|
ValidationIssue(
|
||||||
message=str(e),
|
level="ERROR", message=str(e), location="", code="YAML_ERROR"
|
||||||
location="",
|
)
|
||||||
code="YAML_ERROR"
|
)
|
||||||
))
|
|
||||||
return ValidationResult(
|
return ValidationResult(
|
||||||
valid=False,
|
valid=False, errors=errors, warnings=warnings, infos=infos
|
||||||
errors=errors,
|
|
||||||
warnings=warnings,
|
|
||||||
infos=infos
|
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
errors.append(ValidationIssue(
|
errors.append(
|
||||||
level="ERROR",
|
ValidationIssue(
|
||||||
message=f"加载 YAML 文件失败: {str(e)}",
|
level="ERROR",
|
||||||
location="",
|
message=f"加载 YAML 文件失败: {str(e)}",
|
||||||
code="YAML_LOAD_ERROR"
|
location="",
|
||||||
))
|
code="YAML_LOAD_ERROR",
|
||||||
|
)
|
||||||
|
)
|
||||||
return ValidationResult(
|
return ValidationResult(
|
||||||
valid=False,
|
valid=False, errors=errors, warnings=warnings, infos=infos
|
||||||
errors=errors,
|
|
||||||
warnings=warnings,
|
|
||||||
infos=infos
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# 获取幻灯片尺寸
|
# 获取幻灯片尺寸
|
||||||
size_str = data.get('metadata', {}).get('size', '16:9')
|
size_str = data.get("metadata", {}).get("size", "16:9")
|
||||||
slide_width, slide_height = self.SLIDE_SIZES.get(size_str, (10, 5.625))
|
slide_width, slide_height = self.SLIDE_SIZES.get(size_str, (10, 5.625))
|
||||||
|
|
||||||
# 初始化子验证器
|
# 初始化子验证器
|
||||||
geometry_validator = GeometryValidator(slide_width, slide_height)
|
geometry_validator = GeometryValidator(slide_width, slide_height)
|
||||||
resource_validator = ResourceValidator(
|
resource_validator = ResourceValidator(
|
||||||
yaml_dir=yaml_path.parent,
|
yaml_dir=yaml_path.parent, template_dir=template_dir
|
||||||
template_dir=template_dir
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# 2. 验证每个幻灯片
|
# 2. 验证每个幻灯片
|
||||||
slides = data.get('slides', [])
|
slides = data.get("slides", [])
|
||||||
for slide_index, slide_data in enumerate(slides, start=1):
|
for slide_index, slide_data in enumerate(slides, start=1):
|
||||||
# 验证模板
|
# 验证模板
|
||||||
template_issues = resource_validator.validate_template(slide_data, slide_index)
|
template_issues = resource_validator.validate_template(
|
||||||
|
slide_data, slide_index
|
||||||
|
)
|
||||||
self._categorize_issues(template_issues, errors, warnings, infos)
|
self._categorize_issues(template_issues, errors, warnings, infos)
|
||||||
|
|
||||||
|
# 验证模板变量
|
||||||
|
template_var_issues = resource_validator.validate_template_vars(
|
||||||
|
slide_data, slide_index
|
||||||
|
)
|
||||||
|
self._categorize_issues(template_var_issues, errors, warnings, infos)
|
||||||
|
|
||||||
# 验证元素
|
# 验证元素
|
||||||
elements = slide_data.get('elements', [])
|
elements = slide_data.get("elements", [])
|
||||||
for elem_index, elem_dict in enumerate(elements, start=1):
|
for elem_index, elem_dict in enumerate(elements, start=1):
|
||||||
# 3. 元素级验证
|
# 3. 元素级验证
|
||||||
try:
|
try:
|
||||||
element = create_element(elem_dict)
|
element = create_element(elem_dict)
|
||||||
|
|
||||||
# 调用元素的 validate() 方法
|
# 调用元素的 validate() 方法
|
||||||
if hasattr(element, 'validate'):
|
if hasattr(element, "validate"):
|
||||||
elem_issues = element.validate()
|
elem_issues = element.validate()
|
||||||
# 填充位置信息
|
# 填充位置信息
|
||||||
for issue in elem_issues:
|
for issue in elem_issues:
|
||||||
@@ -111,7 +113,7 @@ class Validator:
|
|||||||
self._categorize_issues(geom_issues, errors, warnings, infos)
|
self._categorize_issues(geom_issues, errors, warnings, infos)
|
||||||
|
|
||||||
# 5. 资源验证(图片)
|
# 5. 资源验证(图片)
|
||||||
if elem_dict.get('type') == 'image':
|
if elem_dict.get("type") == "image":
|
||||||
img_issues = resource_validator.validate_image(
|
img_issues = resource_validator.validate_image(
|
||||||
element, slide_index, elem_index
|
element, slide_index, elem_index
|
||||||
)
|
)
|
||||||
@@ -119,29 +121,32 @@ class Validator:
|
|||||||
|
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
# 元素创建失败(__post_init__ 中的验证)
|
# 元素创建失败(__post_init__ 中的验证)
|
||||||
errors.append(ValidationIssue(
|
errors.append(
|
||||||
level="ERROR",
|
ValidationIssue(
|
||||||
message=str(e),
|
level="ERROR",
|
||||||
location=f"幻灯片 {slide_index}, 元素 {elem_index}",
|
message=str(e),
|
||||||
code="ELEMENT_VALIDATION_ERROR"
|
location=f"幻灯片 {slide_index}, 元素 {elem_index}",
|
||||||
))
|
code="ELEMENT_VALIDATION_ERROR",
|
||||||
|
)
|
||||||
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
errors.append(ValidationIssue(
|
errors.append(
|
||||||
level="ERROR",
|
ValidationIssue(
|
||||||
message=f"验证元素时出错: {str(e)}",
|
level="ERROR",
|
||||||
location=f"幻灯片 {slide_index}, 元素 {elem_index}",
|
message=f"验证元素时出错: {str(e)}",
|
||||||
code="ELEMENT_VALIDATION_ERROR"
|
location=f"幻灯片 {slide_index}, 元素 {elem_index}",
|
||||||
))
|
code="ELEMENT_VALIDATION_ERROR",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
# 返回验证结果
|
# 返回验证结果
|
||||||
return ValidationResult(
|
return ValidationResult(
|
||||||
valid=len(errors) == 0,
|
valid=len(errors) == 0, errors=errors, warnings=warnings, infos=infos
|
||||||
errors=errors,
|
|
||||||
warnings=warnings,
|
|
||||||
infos=infos
|
|
||||||
)
|
)
|
||||||
|
|
||||||
def _categorize_issues(self, issues: list, errors: list, warnings: list, infos: list):
|
def _categorize_issues(
|
||||||
|
self, issues: list, errors: list, warnings: list, infos: list
|
||||||
|
):
|
||||||
"""
|
"""
|
||||||
将问题按级别分类
|
将问题按级别分类
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user