1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-08 22:52:29 +08:00

[StructUtil] add support that the Struct can nest any type to transform (#80)

* add support json tag attribute for StructToMap function

* add the structutil to provide more rich functions and fixed #77

* add support that the nested struct to map for structutil

* recover code

* add structutil unit test

* [StructUtil] add unit test
This commit is contained in:
zm
2023-03-15 14:26:34 +08:00
committed by GitHub
parent ef1e548dfc
commit 2d2c277090
9 changed files with 473 additions and 20 deletions

View File

@@ -2,11 +2,18 @@ package structutil
import (
"github.com/duke-git/lancet/v2/internal"
"reflect"
"testing"
)
func TestToMap(t *testing.T) {
assert := internal.NewAssert(t, "TestStructToMap")
func TestStruct_ToMap(t *testing.T) {
assert := internal.NewAssert(t, "TestStruct_ToMap")
t.Run("no struct", func(t *testing.T) {
m, _ := ToMap(1)
var expected map[string]any
assert.Equal(expected, m)
})
t.Run("StructToMap", func(_ *testing.T) {
type People struct {
@@ -55,3 +62,69 @@ func TestToMap(t *testing.T) {
assert.Equal(expect2, p2m)
})
}
func TestStruct_Fields(t *testing.T) {
assert := internal.NewAssert(t, "TestStruct_Fields")
type Parent struct {
A string `json:"a"`
B int `json:"b"`
C []string `json:"c"`
D map[string]any `json:"d"`
}
p1 := &Parent{
A: "1",
B: 11,
C: []string{"11", "22"},
D: map[string]any{"d1": 1, "d2": 2},
}
s := New(p1)
fields := s.Fields()
assert.Equal(4, len(fields))
assert.Equal(reflect.String, fields[0].Kind())
assert.Equal(reflect.Int, fields[1].Kind())
assert.Equal(reflect.Slice, fields[2].Kind())
assert.Equal(reflect.Map, fields[3].Kind())
}
func TestStruct_Field(t *testing.T) {
assert := internal.NewAssert(t, "TestStruct_Field")
type Parent struct {
A string `json:"a"`
B int `json:"b"`
C []string `json:"c"`
D map[string]any `json:"d"`
}
p1 := &Parent{
A: "1",
B: 11,
C: []string{"11", "22"},
D: map[string]any{"d1": 1, "d2": 2},
}
s := New(p1)
a, ok := s.Field("A")
assert.Equal(true, ok)
assert.Equal(reflect.String, a.Kind())
assert.Equal("1", a.Value())
assert.Equal("a", a.tag.Name)
assert.Equal(false, a.tag.HasOption("omitempty"))
}
func TestStruct_IsStruct(t *testing.T) {
assert := internal.NewAssert(t, "TestStruct_Field")
type Test1 struct{}
t1 := &Test1{}
t2 := 1
s1 := New(t1)
s2 := New(t2)
assert.Equal(true, s1.IsStruct())
assert.Equal(false, s2.IsStruct())
}