add more struct field tests

This commit is contained in:
c9s 2022-07-06 22:01:35 +08:00
parent 30deaad079
commit c9859c9238
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")
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)

View File

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