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,6 +9,8 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestIterateFields(t *testing.T) {
|
func TestIterateFields(t *testing.T) {
|
||||||
|
|
||||||
|
t.Run("basic", func(t *testing.T) {
|
||||||
var a = struct {
|
var a = struct {
|
||||||
A int
|
A int
|
||||||
B float64
|
B float64
|
||||||
|
@ -22,4 +24,21 @@ func TestIterateFields(t *testing.T) {
|
||||||
})
|
})
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
assert.Equal(t, 3, cnt)
|
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