-
Notifications
You must be signed in to change notification settings - Fork 4
/
obj_test.go
126 lines (107 loc) · 2.3 KB
/
obj_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
// SPDX-FileCopyrightText: 2014-2024 caixw
//
// SPDX-License-Identifier: MIT
package conv
import (
"strings"
"testing"
"github.com/issue9/assert/v4"
)
type A1 struct {
ID int
Name string
}
type b1 struct {
A1
Password string
}
type c1 struct {
sub *A1
Sub *b1
Password string
}
type C struct {
SUB *b1
PASSWORD string
}
func ToUpperFieldConv(str string) string {
return strings.ToUpper(str)
}
func TestMap2Obj(t *testing.T) {
as := assert.New(t, false)
// 一般
m := map[string]any{
"ID": 5,
"Name": "admin",
}
// 包含匿名元素
obja := &A1{}
err := Map2Obj(m, obja, nil)
as.Nil(err)
as.Equal(obja.ID, 5)
as.Equal(obja.Name, "admin")
m = map[string]any{
"ID": 5,
"Name": "admin",
"Password": "password",
"lower": "lower",
}
objb := &b1{}
err = Map2Obj(m, objb, nil)
as.Nil(err)
as.Equal(objb.ID, 5)
as.Equal(objb.Name, "admin")
as.Equal(objb.Password, "password")
// 包含子元素
objc := &c1{Sub: &b1{}}
m = map[string]any{
"Password": "password",
"Sub": map[string]any{
"ID": 6,
"Name": "test",
"Password": "sub-password",
},
}
err = Map2Obj(m, objc, nil)
as.Nil(err)
as.Equal(objc.Password, "password")
as.Equal(objc.Sub.ID, 6)
as.Equal(objc.Sub.Password, "sub-password")
// 带转换函数
objC := &C{SUB: &b1{}}
err = Map2Obj(m, objC, ToUpperFieldConv)
as.Nil(err)
as.Equal(objC.PASSWORD, "password")
as.NotNil(objC.SUB)
}
func TestObj2Map(t *testing.T) {
as := assert.New(t, false)
// 普通
obja := &A1{6, "admin"}
m, err := Obj2Map(obja, nil)
as.Nil(err)
as.Equal(m["ID"], 6)
as.Equal(m["Name"], "admin")
// 包含匿名字段
objb := &b1{A1{6, "admin"}, "password"}
m, err = Obj2Map(objb, nil)
as.Nil(err)
as.Equal(m["ID"], 6)
as.Equal(m["Name"], "admin")
as.Equal(m["Password"], "password")
// 包含子元素
objc := &c1{sub: &A1{6, "admin"}, Sub: &b1{A1{5, "test"}, "b-password"}, Password: "password"}
m, err = Obj2Map(objc, nil)
as.Nil(err)
as.Equal(m["Password"], "password")
sub := m["Sub"].(map[string]any)
as.Equal(sub["Password"], "b-password")
as.Equal(sub["ID"], 5)
as.Equal(sub["Name"], "test")
// 带转换函数
m, err = Obj2Map(objc, ToUpperFieldConv)
as.Nil(err)
as.Equal(m["PASSWORD"], "password")
sub = m["SUB"].(map[string]any)
as.Equal(sub["ID"], 5)
}