-
-
Notifications
You must be signed in to change notification settings - Fork 90
/
json_test.go
91 lines (84 loc) · 1.86 KB
/
json_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
package ecspresso_test
import (
"bytes"
"encoding/json"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/kayac/ecspresso/v2"
)
type testJSONStruct struct {
FooBarBaz string
Options map[string]string
Nested struct {
FooBar string
}
}
var testJSONValue = testJSONStruct{
FooBarBaz: "foo",
Options: map[string]string{
"Foo": "xxx",
},
Nested: struct {
FooBar string
}{
FooBar: "foobar",
},
}
var testSuiteJSONForAPI = []struct {
name string
json string
queries []string
}{
{
name: "no transform",
json: `{"fooBarBaz": "foo","nested":{"fooBar":"foobar"},"options":{"Foo":"xxx"}}`,
},
{
name: "options only",
json: `{"Foo":"xxx"}`,
queries: []string{".options"},
},
{
name: "del options",
json: `{"fooBarBaz": "foo","nested":{"fooBar":"foobar"}}`,
queries: []string{"del(.options)"},
},
{
name: "multiple del queries",
json: `{"fooBarBaz": "foo"}`,
queries: []string{"del(.options)", "del(.nested)"},
},
}
func TestMarshalJSONForAPI(t *testing.T) {
for _, s := range testSuiteJSONForAPI {
t.Run(s.name, func(t *testing.T) {
b, err := ecspresso.MarshalJSONForAPI(testJSONValue, s.queries...)
if err != nil {
t.Fatal(err)
}
var expected bytes.Buffer
json.Indent(&expected, []byte(s.json), "", " ")
expected.WriteByte('\n') // json.MarshalIndent does not append newline
if diff := cmp.Diff(expected.String(), string(b)); diff != "" {
t.Errorf("unexpected json: %s", diff)
}
})
}
}
func TestUnmarshalJSON(t *testing.T) {
for _, s := range testSuiteJSONForAPI {
if s.queries != nil {
continue
}
t.Run(s.name, func(t *testing.T) {
var v testJSONStruct
err := ecspresso.UnmarshalJSONForStruct([]byte(s.json), &v, "")
if err != nil {
t.Fatal(err)
}
if diff := cmp.Diff(v, testJSONValue); diff != "" {
t.Errorf("unexpected json: %s", diff)
}
})
}
}