From a6283ac432d86624e9e45cf39b8ea42d7b9bc241 Mon Sep 17 00:00:00 2001 From: what Date: Fri, 28 Aug 2026 16:42:04 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E6=AD=A3=20fieldx=20=E4=B8=AD?= =?UTF-8?q?=E8=BF=87=E6=97=B6=E7=9A=84=E5=AD=97=E6=AE=B5=E7=BC=BA=E5=A4=B1?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E5=B9=B6=E8=A1=A5=E9=BD=90=20Required=20?= =?UTF-8?q?=E8=A6=86=E7=9B=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TestSchema_Generate_FieldNotFound 断言字段缺失时报错, 但用例里没有设置 Required: true。按 Field.Required 的文档语义, 只有 Required 为 true 时字段 缺失才算错误, 否则取到 nil 继续 —— 所以这个测试一直是失败状态, 应该是在 Required 引入之前写的, 加了 Required 之后没有同步更新。 修正: 给用例加上 Required: true, 让它真正测到报错分支。 另补 TestSchema_Generate_OptionalFieldNotFound 覆盖非必需分支 —— Required 此前在整个包里没有任何测试覆盖。 --- fieldx/schema_test.go | 37 +++++++++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/fieldx/schema_test.go b/fieldx/schema_test.go index 151cfed..6c81641 100644 --- a/fieldx/schema_test.go +++ b/fieldx/schema_test.go @@ -426,12 +426,13 @@ func TestSchema_UnmarshalInStruct(t *testing.T) { } } -// TestSchema_Generate_FieldNotFound 测试字段不存在的情况 +// TestSchema_Generate_FieldNotFound 测试 Required 字段不存在时报错 func TestSchema_Generate_FieldNotFound(t *testing.T) { schema := Schema{ "name": Field{ - Type: FieldTypeField, - Value: "nonExistentField", + Type: FieldTypeField, + Value: "nonExistentField", + Required: true, }, } @@ -441,7 +442,35 @@ func TestSchema_Generate_FieldNotFound(t *testing.T) { _, err := schema.Generate(source) if err == nil { - t.Error("Generate() expected error for non-existent field, got nil") + t.Error("Generate() expected error for non-existent required field, got nil") + } +} + +// TestSchema_Generate_OptionalFieldNotFound 测试非 Required 字段不存在时返回 nil 而不报错 +// +// 这是 Required 的另一半语义(见 Field.Required 的文档): 只有 Required 为 true +// 时字段缺失才算错误,否则取到 nil 继续。 +func TestSchema_Generate_OptionalFieldNotFound(t *testing.T) { + schema := Schema{ + "name": Field{ + Type: FieldTypeField, + Value: "nonExistentField", + // Required 默认为 false + }, + } + + source := map[string]any{ + "otherField": "value", + } + + result, err := schema.Generate(source) + if err != nil { + t.Fatalf("Generate() 非必需字段缺失不应报错, 得到: %v", err) + } + if v, ok := result["name"]; !ok { + t.Error("Generate() 应该产出 name 键") + } else if v != nil { + t.Errorf("Generate() name = %v, 期望 nil", v) } }