-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgflatten_test.go
120 lines (108 loc) · 2.43 KB
/
gflatten_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
package gflatten_test
import (
"encoding/json"
"testing"
"github.com/cloudmatelabs/gflatten"
)
var src = map[string]any{
"foo": []any{
"bar", "baz",
},
"foobar": map[string]any{
"foo": []any{
"baz",
map[string]any{
"bar": map[string]any{
"baz": "foobar",
},
},
},
},
}
func TestFlatten(t *testing.T) {
option := gflatten.Option{
ParameterDelimiter: ".",
ArrayWrap: gflatten.WRAP.SQUARE_BRACKET,
}
flattenTest(t, src, option, map[string]any{
"foo[0]": "bar",
"foo[1]": "baz",
"foobar.foo[0]": "baz",
"foobar.foo[1].bar.baz": "foobar",
})
}
func TestFlattenPostgresStyle(t *testing.T) {
option := gflatten.Option{
ParameterDelimiter: "->",
ArrayDelimiter: "->",
ParameterWrap: gflatten.WRAP.SINGLE_QUOTE,
}
flattenTest(t, src, option, map[string]any{
"'foo'->0": "bar",
"'foo'->1": "baz",
"'foobar'->'foo'->0": "baz",
"'foobar'->'foo'->1->'bar'->'baz'": "foobar",
})
}
func TestFlattenMySQLStyle(t *testing.T) {
option := gflatten.Option{
Prefix: "$",
ParameterDelimiter: ".",
ArrayWrap: gflatten.WRAP.SQUARE_BRACKET,
}
flattenTest(t, src, option, map[string]any{
"$.foo[0]": "bar",
"$.foo[1]": "baz",
"$.foobar.foo[0]": "baz",
"$.foobar.foo[1].bar.baz": "foobar",
})
}
func TestFlattenStructInput(t *testing.T) {
type bar struct {
Baz string `json:"baz"`
}
type foobar struct {
Foo []bar `json:"foo"`
}
type input struct {
Foo []string `json:"foo"`
Foobar foobar `json:"foobar"`
}
src := input{
Foo: []string{"bar", "baz"},
Foobar: foobar{
Foo: []bar{
{Baz: "baz"},
{Baz: "foobar"},
},
},
}
option := gflatten.Option{
ParameterDelimiter: ".",
ArrayWrap: gflatten.WRAP.SQUARE_BRACKET,
}
flattenTest(t, src, option, map[string]any{
"foo[0]": "bar",
"foo[1]": "baz",
"foobar.foo[0].baz": "baz",
"foobar.foo[1].baz": "foobar",
})
}
func flattenTest(t *testing.T, src any, option gflatten.Option, expect map[string]any) {
dest, err := gflatten.Flatten(src, option)
if err != nil {
t.Fatalf("Error: %v", err)
return
}
fatal := false
for k, v := range expect {
if dest[k] != v {
fatal = true
t.Errorf("dest[%s] != %v", k, v)
}
}
if fatal {
d, _ := json.MarshalIndent(dest, "", " ")
t.Fatal(string(d))
}
}