mirror of
https://github.com/c9s/bbgo.git
synced 2024-11-10 09:11:55 +00:00
add more struct field tests
This commit is contained in:
parent
30deaad079
commit
c9859c9238
|
@ -11,6 +11,10 @@ type StructFieldIterator func(tag string, ft reflect.StructField, fv reflect.Val
|
|||
var ErrCanNotIterateNilPointer = errors.New("can not iterate struct on a nil pointer")
|
||||
|
||||
func IterateFields(obj interface{}, cb func(ft reflect.StructField, fv reflect.Value) error) error {
|
||||
if obj == nil {
|
||||
return errors.New("can not iterate field, given object is nil")
|
||||
}
|
||||
|
||||
sv := reflect.ValueOf(obj)
|
||||
st := reflect.TypeOf(obj)
|
||||
|
||||
|
|
|
@ -9,17 +9,36 @@ import (
|
|||
)
|
||||
|
||||
func TestIterateFields(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
|
||||
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)
|
||||
})
|
||||
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)
|
||||
})
|
||||
|
||||
t.Run("nil", func(t *testing.T) {
|
||||
err := IterateFields(nil, func(ft reflect.StructField, fv reflect.Value) error {
|
||||
return nil
|
||||
})
|
||||
assert.Error(t, err)
|
||||
})
|
||||
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user