bbgo_origin/pkg/dynamic/iterate_test.go

104 lines
2.0 KiB
Go
Raw Normal View History

2022-07-06 13:58:26 +00:00
package dynamic
import (
"os"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
func TestIterateFields(t *testing.T) {
2022-07-06 14:01:35 +00:00
t.Run("basic", func(t *testing.T) {
var a = struct {
A int
B float64
C *os.File
}{}
cnt := 0
err := IterateFields(&a, func(ft reflect.StructField, fv reflect.Value) error {
cnt++
return nil
})
assert.NoError(t, err)
assert.Equal(t, 3, cnt)
})
t.Run("non-ptr", func(t *testing.T) {
err := IterateFields(struct{}{}, func(ft reflect.StructField, fv reflect.Value) error {
return nil
})
assert.Error(t, err)
2022-07-06 13:58:26 +00:00
})
2022-07-06 14:01:35 +00:00
t.Run("nil", func(t *testing.T) {
err := IterateFields(nil, func(ft reflect.StructField, fv reflect.Value) error {
return nil
})
assert.Error(t, err)
})
2023-07-09 07:11:09 +00:00
}
func TestIterateFieldsByTag(t *testing.T) {
t.Run("nested", func(t *testing.T) {
var a = struct {
A int `persistence:"a"`
B int `persistence:"b"`
C *struct {
D int `persistence:"d"`
E int `persistence:"e"`
}
}{
A: 1,
B: 2,
C: &struct {
D int `persistence:"d"`
E int `persistence:"e"`
}{
D: 3,
E: 4,
},
}
collectedTags := []string{}
cnt := 0
err := IterateFieldsByTag(&a, "persistence", func(tag string, ft reflect.StructField, fv reflect.Value) error {
cnt++
collectedTags = append(collectedTags, tag)
return nil
})
assert.NoError(t, err)
assert.Equal(t, 4, cnt)
assert.Equal(t, []string{"a", "b", "d", "e"}, collectedTags)
})
t.Run("nested nil", func(t *testing.T) {
var a = struct {
A int `persistence:"a"`
B int `persistence:"b"`
C *struct {
D int `persistence:"d"`
E int `persistence:"e"`
}
}{
A: 1,
B: 2,
C: nil,
}
2022-07-06 14:01:35 +00:00
2023-07-09 07:11:09 +00:00
collectedTags := []string{}
cnt := 0
err := IterateFieldsByTag(&a, "persistence", func(tag string, ft reflect.StructField, fv reflect.Value) error {
cnt++
collectedTags = append(collectedTags, tag)
return nil
})
assert.NoError(t, err)
assert.Equal(t, 2, cnt)
assert.Equal(t, []string{"a", "b"}, collectedTags)
})
2022-07-06 13:58:26 +00:00
}