forked from basgys/goxml2json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencoder_test.go
119 lines (103 loc) · 2.4 KB
/
encoder_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
package xml2json_test
import (
"bytes"
"encoding/json"
"testing"
"github.com/stretchr/testify/suite"
xml2json "github.com/txix-open/goxml2json"
)
func TestEncoder_Suite(t *testing.T) {
t.Parallel()
suite.Run(t, &TestEncoder{})
}
type TestEncoder struct {
suite.Suite
}
func (t *TestEncoder) SetupSuite() {}
// TestEncode ensures that encode outputs the expected JSON document.
func (t *TestEncoder) TestEncode() {
type bio struct {
Firstname string
Lastname string
Hobbies []string
Misc map[string]string
}
author := bio{
Firstname: "Bastien",
Lastname: "Gysler",
Hobbies: []string{"DJ", "Running", "Tennis"},
Misc: map[string]string{
"lineSeparator": "\u2028",
"Nationality": "Swiss",
"City": "Zürich",
"foo": "",
"bar": "\"quoted text\"",
"esc": "escaped \\ sanitized",
"r": "\r return line",
"default": "< >",
"runeError": "\uFFFD",
},
}
// Build document
root := &xml2json.Node{}
root.AddChild("firstname", &xml2json.Node{
Data: author.Firstname,
})
root.AddChild("lastname", &xml2json.Node{
Data: author.Lastname,
})
for _, h := range author.Hobbies {
root.AddChild("hobbies", &xml2json.Node{
Data: h,
})
}
misc := &xml2json.Node{}
for k, v := range author.Misc {
misc.AddChild(k, &xml2json.Node{
Data: v,
})
}
root.AddChild("misc", misc)
var enc *xml2json.Encoder
// Convert to JSON string
buf := new(bytes.Buffer)
enc = xml2json.NewEncoder(buf)
err := enc.Encode(nil)
t.NoError(err)
attr := xml2json.WithAttrPrefix("test")
attr.AddToEncoder(enc)
content := xml2json.WithContentPrefix("test2")
content.AddToEncoder(enc)
err = enc.Encode(root)
t.NoError(err)
// Build SimpleJSON
expectedResultBytes := []byte(`
{
"firstname": "Bastien",
"lastname": "Gysler",
"hobbies": [
"DJ",
"Running",
"Tennis"
],
"misc": {
"lineSeparator": "\u2028",
"Nationality": "Swiss",
"City": "Zürich",
"foo": "",
"bar": "\"quoted text\"",
"esc": "escaped \\ sanitized",
"r": "\r return line",
"default": "< >",
"runeError": "\uFFFD"
}
}
`)
expectedResult := make(map[string]any)
err = json.Unmarshal(expectedResultBytes, &expectedResult)
t.NoError(err)
actualResult := make(map[string]any)
err = json.Unmarshal(buf.Bytes(), &actualResult)
t.NoError(err)
t.EqualValues(expectedResult, actualResult)
}