1
0

feat: 添加模板变量验证功能

- 在 ResourceValidator 中添加 validate_template_vars 方法
- 在验证阶段检查用户是否提供了模板所需的必需变量
- 缺少必需变量时返回 ERROR 级别错误
- 添加 9 个单元测试用例验证功能
- 同步更新 OpenSpec 规格文档
This commit is contained in:
2026-03-03 01:00:21 +08:00
parent e31a7e9bed
commit ef3fa6a06a
9 changed files with 468 additions and 89 deletions

View File

@@ -38,7 +38,7 @@ class ResourceValidator:
issues = []
location = f"幻灯片 {slide_index}, 元素 {elem_index}"
if not hasattr(element, 'src'):
if not hasattr(element, "src"):
return issues
src = element.src
@@ -52,12 +52,14 @@ class ResourceValidator:
# 检查文件是否存在
if not src_path.exists():
issues.append(ValidationIssue(
level="ERROR",
message=f"图片文件不存在: {src}",
location=location,
code="IMAGE_FILE_NOT_FOUND"
))
issues.append(
ValidationIssue(
level="ERROR",
message=f"图片文件不存在: {src}",
location=location,
code="IMAGE_FILE_NOT_FOUND",
)
)
return issues
@@ -75,36 +77,40 @@ class ResourceValidator:
issues = []
location = f"幻灯片 {slide_index}"
if 'template' not in slide_data:
if "template" not in slide_data:
return issues
template_name = slide_data['template']
template_name = slide_data["template"]
if not template_name:
return issues
# 检查是否提供了模板目录
if not self.template_dir:
issues.append(ValidationIssue(
level="ERROR",
message=f"使用了模板但未指定模板目录: {template_name}",
location=location,
code="TEMPLATE_DIR_NOT_SPECIFIED"
))
issues.append(
ValidationIssue(
level="ERROR",
message=f"使用了模板但未指定模板目录: {template_name}",
location=location,
code="TEMPLATE_DIR_NOT_SPECIFIED",
)
)
return issues
# 解析模板文件路径
template_path = self.template_dir / template_name
if not template_path.suffix:
template_path = template_path.with_suffix('.yaml')
template_path = template_path.with_suffix(".yaml")
# 检查模板文件是否存在
if not template_path.exists():
issues.append(ValidationIssue(
level="ERROR",
message=f"模板文件不存在: {template_name}",
location=location,
code="TEMPLATE_FILE_NOT_FOUND"
))
issues.append(
ValidationIssue(
level="ERROR",
message=f"模板文件不存在: {template_name}",
location=location,
code="TEMPLATE_FILE_NOT_FOUND",
)
)
return issues
# 验证模板文件结构
@@ -112,11 +118,71 @@ class ResourceValidator:
template_data = load_yaml_file(template_path)
validate_template_yaml(template_data, str(template_path))
except Exception as e:
issues.append(ValidationIssue(
level="ERROR",
message=f"模板文件结构错误: {template_name} - {str(e)}",
location=location,
code="TEMPLATE_STRUCTURE_ERROR"
))
issues.append(
ValidationIssue(
level="ERROR",
message=f"模板文件结构错误: {template_name} - {str(e)}",
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

View File

@@ -45,59 +45,61 @@ class Validator:
data = load_yaml_file(yaml_path)
validate_presentation_yaml(data, str(yaml_path))
except YAMLError as e:
errors.append(ValidationIssue(
level="ERROR",
message=str(e),
location="",
code="YAML_ERROR"
))
errors.append(
ValidationIssue(
level="ERROR", message=str(e), location="", code="YAML_ERROR"
)
)
return ValidationResult(
valid=False,
errors=errors,
warnings=warnings,
infos=infos
valid=False, errors=errors, warnings=warnings, infos=infos
)
except Exception as e:
errors.append(ValidationIssue(
level="ERROR",
message=f"加载 YAML 文件失败: {str(e)}",
location="",
code="YAML_LOAD_ERROR"
))
errors.append(
ValidationIssue(
level="ERROR",
message=f"加载 YAML 文件失败: {str(e)}",
location="",
code="YAML_LOAD_ERROR",
)
)
return ValidationResult(
valid=False,
errors=errors,
warnings=warnings,
infos=infos
valid=False, 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))
# 初始化子验证器
geometry_validator = GeometryValidator(slide_width, slide_height)
resource_validator = ResourceValidator(
yaml_dir=yaml_path.parent,
template_dir=template_dir
yaml_dir=yaml_path.parent, template_dir=template_dir
)
# 2. 验证每个幻灯片
slides = data.get('slides', [])
slides = data.get("slides", [])
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)
# 验证模板变量
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):
# 3. 元素级验证
try:
element = create_element(elem_dict)
# 调用元素的 validate() 方法
if hasattr(element, 'validate'):
if hasattr(element, "validate"):
elem_issues = element.validate()
# 填充位置信息
for issue in elem_issues:
@@ -111,7 +113,7 @@ class Validator:
self._categorize_issues(geom_issues, errors, warnings, infos)
# 5. 资源验证(图片)
if elem_dict.get('type') == 'image':
if elem_dict.get("type") == "image":
img_issues = resource_validator.validate_image(
element, slide_index, elem_index
)
@@ -119,29 +121,32 @@ class Validator:
except ValueError as e:
# 元素创建失败__post_init__ 中的验证)
errors.append(ValidationIssue(
level="ERROR",
message=str(e),
location=f"幻灯片 {slide_index}, 元素 {elem_index}",
code="ELEMENT_VALIDATION_ERROR"
))
errors.append(
ValidationIssue(
level="ERROR",
message=str(e),
location=f"幻灯片 {slide_index}, 元素 {elem_index}",
code="ELEMENT_VALIDATION_ERROR",
)
)
except Exception as e:
errors.append(ValidationIssue(
level="ERROR",
message=f"验证元素时出错: {str(e)}",
location=f"幻灯片 {slide_index}, 元素 {elem_index}",
code="ELEMENT_VALIDATION_ERROR"
))
errors.append(
ValidationIssue(
level="ERROR",
message=f"验证元素时出错: {str(e)}",
location=f"幻灯片 {slide_index}, 元素 {elem_index}",
code="ELEMENT_VALIDATION_ERROR",
)
)
# 返回验证结果
return ValidationResult(
valid=len(errors) == 0,
errors=errors,
warnings=warnings,
infos=infos
valid=len(errors) == 0, 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
):
"""
将问题按级别分类