Skip to content

Commit

Permalink
✅ test: reflects - add more unit tests for FlatMap(), EachMap()
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Jun 29, 2023
1 parent 899294d commit f39f74c
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
3 changes: 1 addition & 2 deletions reflects/conv_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"reflect"
"testing"

"github.com/gookit/goutil/arrutil"
"github.com/gookit/goutil/reflects"
"github.com/gookit/goutil/testutil/assert"
)
Expand Down Expand Up @@ -102,7 +101,7 @@ func TestConvSlice(t *testing.T) {
oldArr = []string{"12", "23"}
newArr, err = reflects.ConvSlice(reflect.ValueOf(oldArr), reflect.TypeOf(1))
assert.NoErr(t, err)
assert.Eq(t, arrutil.StringsAsInts(oldArr), newArr.Interface())
assert.Eq(t, []int{12, 23}, newArr.Interface())

assert.Panics(t, func() {
_, _ = reflects.ConvSlice(reflect.ValueOf("s"), reflect.TypeOf("s"))
Expand Down
42 changes: 42 additions & 0 deletions reflects/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,4 +211,46 @@ func TestFlatMap(t *testing.T) {
assert.NotPanics(t, func() {
reflects.FlatMap(reflect.ValueOf(nil), nil)
})

mp := map[string]any{
"name": "inhere",
"age": 234,
"top": map[string]any{
"sub0": "val0",
"sub1": []string{"val1-0", "val1-1"},
},
}

flatMp := make(map[string]any, len(mp)*2)
reflects.FlatMap(reflect.ValueOf(mp), func(path string, val reflect.Value) {
flatMp[path] = val.Interface()
})
dump.P(flatMp)
assert.Eq(t, "inhere", flatMp["name"])
assert.Eq(t, "val0", flatMp["top.sub0"])
assert.Eq(t, "val1-0", flatMp["top.sub1[0]"])
}

func TestEachStrAnyMap(t *testing.T) {
smp := map[int]string{
1: "val1",
2: "val2",
}

mp := make(map[string]any)
reflects.EachStrAnyMap(reflect.ValueOf(smp), func(key string, val any) {
mp[key] = val
})

assert.Eq(t, "val1", mp["1"])
assert.Eq(t, "val2", mp["2"])

assert.NotPanics(t, func() {
reflects.EachMap(reflect.ValueOf("abc"), nil)
})
assert.Panics(t, func() {
reflects.EachMap(reflect.ValueOf("abc"), func(key, val reflect.Value) {
// do nothing
})
})
}

0 comments on commit f39f74c

Please sign in to comment.