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
825022715d
commit
81e05a3f2c
|
@ -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")
|
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 {
|
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)
|
sv := reflect.ValueOf(obj)
|
||||||
st := reflect.TypeOf(obj)
|
st := reflect.TypeOf(obj)
|
||||||
|
|
||||||
|
|
|
@ -9,17 +9,36 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestIterateFields(t *testing.T) {
|
func TestIterateFields(t *testing.T) {
|
||||||
var a = struct {
|
|
||||||
A int
|
|
||||||
B float64
|
|
||||||
C *os.File
|
|
||||||
}{}
|
|
||||||
|
|
||||||
cnt := 0
|
t.Run("basic", func(t *testing.T) {
|
||||||
err := IterateFields(&a, func(ft reflect.StructField, fv reflect.Value) error {
|
var a = struct {
|
||||||
cnt++
|
A int
|
||||||
return nil
|
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