struct_to_schema_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. package schema
  2. import (
  3. "github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
  4. "github.com/stretchr/testify/assert"
  5. "testing"
  6. )
  7. func TestStructToSchema(t *testing.T) {
  8. type args struct {
  9. instance any
  10. }
  11. tests := []struct {
  12. name string
  13. args args
  14. want *schema_pb.RecordType
  15. }{
  16. {
  17. name: "scalar type",
  18. args: args{
  19. instance: 1,
  20. },
  21. want: nil,
  22. },
  23. {
  24. name: "simple struct type",
  25. args: args{
  26. instance: struct {
  27. Field1 int
  28. Field2 string
  29. }{},
  30. },
  31. want: RecordTypeBegin().
  32. WithField("Field1", TypeInt32).
  33. WithField("Field2", TypeString).
  34. RecordTypeEnd(),
  35. },
  36. {
  37. name: "simple list",
  38. args: args{
  39. instance: struct {
  40. Field1 []int
  41. Field2 string
  42. }{},
  43. },
  44. want: RecordTypeBegin().
  45. WithField("Field1", ListOf(TypeInt32)).
  46. WithField("Field2", TypeString).
  47. RecordTypeEnd(),
  48. },
  49. {
  50. name: "simple []byte",
  51. args: args{
  52. instance: struct {
  53. Field2 []byte
  54. }{},
  55. },
  56. want: RecordTypeBegin().
  57. WithField("Field2", TypeBytes).
  58. RecordTypeEnd(),
  59. },
  60. {
  61. name: "nested simpe structs",
  62. args: args{
  63. instance: struct {
  64. Field1 int
  65. Field2 struct {
  66. Field3 string
  67. Field4 int
  68. }
  69. }{},
  70. },
  71. want: RecordTypeBegin().
  72. WithField("Field1", TypeInt32).
  73. WithRecordField("Field2",
  74. RecordTypeBegin().
  75. WithField("Field3", TypeString).
  76. WithField("Field4", TypeInt32).
  77. RecordTypeEnd(),
  78. ).
  79. RecordTypeEnd(),
  80. },
  81. {
  82. name: "nested struct type",
  83. args: args{
  84. instance: struct {
  85. Field1 int
  86. Field2 struct {
  87. Field3 string
  88. Field4 []int
  89. Field5 struct {
  90. Field6 string
  91. Field7 []byte
  92. }
  93. }
  94. }{},
  95. },
  96. want: RecordTypeBegin().
  97. WithField("Field1", TypeInt32).
  98. WithRecordField("Field2", RecordTypeBegin().
  99. WithField("Field3", TypeString).
  100. WithField("Field4", ListOf(TypeInt32)).
  101. WithRecordField("Field5",
  102. RecordTypeBegin().
  103. WithField("Field6", TypeString).
  104. WithField("Field7", TypeBytes).
  105. RecordTypeEnd(),
  106. ).RecordTypeEnd(),
  107. ).
  108. RecordTypeEnd(),
  109. },
  110. }
  111. for _, tt := range tests {
  112. t.Run(tt.name, func(t *testing.T) {
  113. assert.Equalf(t, tt.want, StructToSchema(tt.args.instance), "StructToSchema(%v)", tt.args.instance)
  114. })
  115. }
  116. }