yaml_loader_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. package yaml_loader
  2. import (
  3. "os"
  4. "testing"
  5. )
  6. type TestYamlModel1 struct {
  7. Test `yaml:"test1"`
  8. }
  9. type TestYamlModel2 struct {
  10. Test `yaml:"test2"`
  11. }
  12. type Test struct {
  13. Name string `yaml:"name"`
  14. }
  15. func TestLoadYAML(t *testing.T) {
  16. testModel1 := new(TestYamlModel1)
  17. testModel2 := new(TestYamlModel2)
  18. retObjects := []any{testModel1, testModel2}
  19. err := LoadYamlFile("test.yaml", &retObjects)
  20. if err != nil {
  21. t.Fatal(err)
  22. }
  23. if retObjects[0].(*TestYamlModel1).Name != "foo1" {
  24. t.Fatal("model1名称错误")
  25. }
  26. if retObjects[1].(*TestYamlModel2).Name != "foo2" {
  27. t.Fatal("model2名称错误")
  28. }
  29. testModel1 = new(TestYamlModel1)
  30. testModel2 = new(TestYamlModel2)
  31. retObjects = []any{testModel1, testModel2}
  32. yamlFileBytes, err := os.ReadFile("test.yaml")
  33. if err != nil {
  34. t.Fatal(err)
  35. }
  36. err = LoadYamlBytes(yamlFileBytes, &retObjects)
  37. if err != nil {
  38. t.Fatal(err)
  39. }
  40. if retObjects[0].(*TestYamlModel1).Name != "foo1" {
  41. t.Fatal("model1名称错误")
  42. }
  43. if retObjects[1].(*TestYamlModel2).Name != "foo2" {
  44. t.Fatal("model2名称错误")
  45. }
  46. retObjects = []any{make(map[string]any), make(map[string]any)}
  47. err = LoadYamlFile("test.yaml", &retObjects)
  48. if err != nil {
  49. t.Fatal(err)
  50. }
  51. if retObjects[0].(map[string]any)["test1"].(map[string]any)["name"] != "foo1" {
  52. t.Fatal("model1名称错误")
  53. }
  54. if retObjects[1].(map[string]any)["test2"].(map[string]any)["name"] != "foo2" {
  55. t.Fatal("model2名称错误")
  56. }
  57. }
  58. func TestLoadYAMLMap(t *testing.T) {
  59. retObjectMaps := make([]map[string]any, 0)
  60. err := LoadYamlMapFile("test.yaml", func(objectMap map[string]any) {
  61. retObjectMaps = append(retObjectMaps, objectMap)
  62. })
  63. if err != nil {
  64. t.Fatal(err)
  65. }
  66. if retObjectMaps[0]["test1"].(map[string]any)["name"] != "foo1" {
  67. t.Fatal("model1名称错误")
  68. }
  69. if retObjectMaps[1]["test2"].(map[string]any)["name"] != "foo2" {
  70. t.Fatal("model2名称错误")
  71. }
  72. retObjectMaps = make([]map[string]any, 0)
  73. yamlFileBytes, err := os.ReadFile("test.yaml")
  74. if err != nil {
  75. t.Fatal(err)
  76. }
  77. err = LoadYamlMapBytes(yamlFileBytes, func(objectMap map[string]any) {
  78. retObjectMaps = append(retObjectMaps, objectMap)
  79. })
  80. if err != nil {
  81. t.Fatal(err)
  82. }
  83. if retObjectMaps[0]["test1"].(map[string]any)["name"] != "foo1" {
  84. t.Fatal("model1名称错误")
  85. }
  86. if retObjectMaps[1]["test2"].(map[string]any)["name"] != "foo2" {
  87. t.Fatal("model2名称错误")
  88. }
  89. }