123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- 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) {
- retObjectMaps = append(retObjectMaps, objectMap)
- })
- 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) {
- retObjectMaps = append(retObjectMaps, objectMap)
- })
- 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名称错误")
- }
- }
|