package yaml_loader import ( "os" "testing" ) type TestYamlModel1 struct { Test `yaml:"test1"` } type TestYamlModel2 struct { Test `yaml:"test2"` } type Test struct { Name string `yaml:"name"` } func TestLoadYAML(t *testing.T) { testModel1 := new(TestYamlModel1) testModel2 := new(TestYamlModel2) retObjects := []any{testModel1, testModel2} err := LoadYamlFile("test.yaml", &retObjects) if err != nil { t.Fatal(err) } if retObjects[0].(*TestYamlModel1).Name != "foo1" { t.Fatal("model1名称错误") } if retObjects[1].(*TestYamlModel2).Name != "foo2" { t.Fatal("model2名称错误") } testModel1 = new(TestYamlModel1) testModel2 = new(TestYamlModel2) retObjects = []any{testModel1, testModel2} yamlFileBytes, err := os.ReadFile("test.yaml") if err != nil { t.Fatal(err) } err = LoadYamlBytes(yamlFileBytes, &retObjects) if err != nil { t.Fatal(err) } if retObjects[0].(*TestYamlModel1).Name != "foo1" { t.Fatal("model1名称错误") } if retObjects[1].(*TestYamlModel2).Name != "foo2" { t.Fatal("model2名称错误") } retObjects = []any{make(map[string]any), make(map[string]any)} err = LoadYamlFile("test.yaml", &retObjects) if err != nil { t.Fatal(err) } if retObjects[0].(map[string]any)["test1"].(map[string]any)["name"] != "foo1" { t.Fatal("model1名称错误") } if retObjects[1].(map[string]any)["test2"].(map[string]any)["name"] != "foo2" { t.Fatal("model2名称错误") } } func TestLoadYAMLMap(t *testing.T) { retObjectMaps := make([]map[string]any, 0) err := LoadYamlMapFile("test.yaml", func(objectMap map[string]any) error { retObjectMaps = append(retObjectMaps, objectMap) return nil }) if err != nil { t.Fatal(err) } if retObjectMaps[0]["test1"].(map[string]any)["name"] != "foo1" { t.Fatal("model1名称错误") } if retObjectMaps[1]["test2"].(map[string]any)["name"] != "foo2" { t.Fatal("model2名称错误") } retObjectMaps = make([]map[string]any, 0) yamlFileBytes, err := os.ReadFile("test.yaml") if err != nil { t.Fatal(err) } err = LoadYamlMapBytes(yamlFileBytes, func(objectMap map[string]any) error { retObjectMaps = append(retObjectMaps, objectMap) return nil }) if err != nil { t.Fatal(err) } if retObjectMaps[0]["test1"].(map[string]any)["name"] != "foo1" { t.Fatal("model1名称错误") } if retObjectMaps[1]["test2"].(map[string]any)["name"] != "foo2" { t.Fatal("model2名称错误") } }