-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdynamic_test.go
More file actions
112 lines (97 loc) · 1.55 KB
/
dynamic_test.go
File metadata and controls
112 lines (97 loc) · 1.55 KB
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
package dynamic
import (
"encoding/json"
"testing"
)
var _ (json.Marshaler) = (*Type)(nil)
var _ (json.Unmarshaler) = (*Type)(nil)
var _ (json.Unmarshaler) = (*Data)(nil)
type a struct {
A string
}
type b struct {
B string
}
func createA() interface{} {
return &a{}
}
func createB() interface{} {
return &b{}
}
func init() {
Register("a", createA)
Register("b", createB)
}
func TestNameDuplicated(t *testing.T) {
defer func() {
err := recover()
if err == nil {
t.Fatal("panic expected")
}
}()
Register("a", createB)
}
func TestUnmarshalUnsupportedType(t *testing.T) {
var test Type
data := `
{
"type": "c",
"C": "This is C"
}`
err := json.Unmarshal([]byte(data), &test)
if err == nil {
t.Fatal("error expected")
}
if "type \"c\" is not supported" != err.Error() {
t.Fatal(err)
}
}
func TestUnmarshalEmptyType(t *testing.T) {
var test Type
data := `
{
"type": "",
"A": "This is A"
}`
err := json.Unmarshal([]byte(data), &test)
if err == nil {
t.Fatal("error expected")
}
if "type must be specified" != err.Error() {
t.Fatal(err)
}
}
func TestUnmarshalEmbeddedStruct(t *testing.T) {
type inner struct {
Type
}
type iinner struct {
inner
}
var test struct {
X []iinner
}
data := `
{
"X": [
{
"type": "a",
"A": "This is A"
},
{
"type": "a",
"A": "This is A"
}
]
}`
if err := json.Unmarshal([]byte(data), &test); err != nil {
t.Fatal(err)
}
for _, i := range test.X {
switch i.Value().(type) {
case *a:
default:
t.Fatalf("%#v is not *a", i.Value())
}
}
}