-
Notifications
You must be signed in to change notification settings - Fork 2
/
json_test.go
126 lines (117 loc) · 2.72 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
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
package yaml_test
import (
"fmt"
"testing"
"github.com/stretchr/testify/require"
"github.com/go-faster/jx"
"github.com/go-faster/yaml"
)
func TestNode_EncodeJSON(t *testing.T) {
type testCase struct {
input yaml.Node
output string
wantErr bool
}
mustNode := func(input string) (n yaml.Node) {
require.NoError(t, yaml.Unmarshal([]byte(input), &n))
return n
}
tests := []testCase{
{mustNode(`foobar`), `"foobar"`, false},
{mustNode(`"\nfoo\n"`), `"\nfoo\n"`, false},
{mustNode(`10`), `10`, false},
{mustNode(`null`), `null`, false},
{yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str"}, `""`, false},
{yaml.Node{Kind: yaml.ScalarNode, Tag: "!!int", Value: "10"}, `10`, false},
{yaml.Node{Kind: yaml.SequenceNode}, "[]", false},
{yaml.Node{Kind: yaml.MappingNode}, "{}", false},
{
yaml.Node{
Kind: yaml.MappingNode,
Content: []*yaml.Node{
{Kind: yaml.ScalarNode, Tag: "!!str", Anchor: "a", Value: "key"},
{Kind: yaml.ScalarNode, Tag: "!!str", Anchor: "b", Value: "value"},
{Kind: yaml.AliasNode, Alias: &yaml.Node{
Kind: yaml.ScalarNode,
Tag: "!!str",
Anchor: "b",
Value: "value",
}},
{Kind: yaml.AliasNode, Alias: &yaml.Node{
Kind: yaml.ScalarNode,
Tag: "!!str",
Anchor: "a",
Value: "key",
}},
},
},
`{"key": "value", "value": "key"}`,
false,
},
{
yaml.Node{
Kind: yaml.DocumentNode,
Content: []*yaml.Node{
{
Kind: yaml.SequenceNode,
Content: []*yaml.Node{
{Kind: yaml.ScalarNode, Tag: "!!str", Anchor: "a", Value: "a"},
{Kind: yaml.ScalarNode, Tag: "!!str", Anchor: "b", Value: "b"},
{Kind: yaml.AliasNode, Alias: &yaml.Node{
Kind: yaml.ScalarNode,
Tag: "!!str",
Anchor: "a",
Value: "a",
}},
{Kind: yaml.AliasNode, Alias: &yaml.Node{
Kind: yaml.ScalarNode,
Tag: "!!str",
Anchor: "b",
Value: "b",
}},
},
},
},
},
`["a","b","a","b"]`,
false,
},
{
yaml.Node{
Kind: yaml.MappingNode,
Content: []*yaml.Node{
{Kind: yaml.ScalarNode, Tag: "!!int", Value: "10"},
{Kind: yaml.ScalarNode, Tag: "!!str", Value: "foo"},
},
},
"",
true,
},
{yaml.Node{Kind: yaml.DocumentNode}, "", true},
{
yaml.Node{
Kind: yaml.DocumentNode,
Content: []*yaml.Node{
{}, {},
},
},
"",
true,
},
{yaml.Node{}, "", true},
}
for i, tt := range tests {
tt := tt
t.Run(fmt.Sprintf("Test%d", i+1), func(t *testing.T) {
a := require.New(t)
var e jx.Encoder
err := tt.input.EncodeJSON(&e)
if tt.wantErr {
a.Error(err)
return
}
a.NoError(err)
a.JSONEq(tt.output, e.String())
})
}
}