add more struct field tests

This commit is contained in:
c9s 2022-07-06 22:01:35 +08:00
parent 825022715d
commit 81e05a3f2c
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
2 changed files with 34 additions and 11 deletions

View File

@ -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)

View File

@ -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)
})
} }