1
2
3
18
19 package ast
20
21 import (
22 `encoding/json`
23 `testing`
24
25 `github.com/bytedance/sonic/encoder`
26 `github.com/stretchr/testify/require`
27 `github.com/bytedance/sonic/internal/native/types`
28 `github.com/stretchr/testify/assert`
29 )
30
31 func TestEncodeValue(t *testing.T) {
32 obj := new(_TwitterStruct)
33 if err := json.Unmarshal([]byte(_TwitterJson), obj); err != nil {
34 t.Fatal(err)
35 }
36
37 buf, err := json.Marshal(obj)
38 if err != nil {
39 t.Fatal(err)
40 }
41 quote, err := json.Marshal(_TwitterJson)
42 if err != nil {
43 t.Fatal(err)
44 }
45 type Case struct {
46 node Node
47 exp string
48 err bool
49 }
50 input := []Case{
51 {NewNull(), "null", false},
52 {NewBool(true), "true", false},
53 {NewBool(false), "false", false},
54 {NewNumber("0.0"), "0.0", false},
55 {NewString(""), `""`, false},
56 {NewString(`\"\"`), `"\\\"\\\""`, false},
57 {NewString(_TwitterJson), string(quote), false},
58 {NewArray([]Node{}), "[]", false},
59 {NewArray([]Node{NewString(""), NewNull()}), `["",null]`, false},
60 {NewArray([]Node{NewBool(true), NewString("true"), NewString("\t")}), `[true,"true","\t"]`, false},
61 {NewObject([]Pair{Pair{"a", NewNull()}, Pair{"b", NewNumber("0")}}), `{"a":null,"b":0}`, false},
62 {NewObject([]Pair{Pair{"\ta", NewString("\t")}, Pair{"\bb", NewString("\b")}, Pair{"\nb", NewString("\n")}, Pair{"\ra", NewString("\r")}}),`{"\ta":"\t","\u0008b":"\u0008","\nb":"\n","\ra":"\r"}`, false},
63 {NewObject([]Pair{}), `{}`, false},
64 {NewObject([]Pair{Pair{Key: "", Value: NewNull()}}), `{"":null}`, false},
65 {NewBytes([]byte("hello, world")), `"aGVsbG8sIHdvcmxk"`, false},
66 {NewAny(obj), string(buf), false},
67 {NewRaw(`[{ }]`), "[{}]", false},
68 {Node{}, "", true},
69 {Node{t: types.ValueType(1)}, "", true},
70 }
71 for i, c := range input {
72 t.Log(i)
73 buf, err := json.Marshal(&c.node)
74 if c.err {
75 if err == nil {
76 t.Fatal(i)
77 }
78 continue
79 }
80 if err != nil {
81 t.Fatal(i, err)
82 }
83 assert.Equal(t, c.exp, string(buf))
84 }
85 }
86
87 func TestSortNodeTwitter(t *testing.T) {
88 root, err := NewSearcher(_TwitterJson).GetByPath()
89 if err != nil {
90 t.Fatal(err)
91 }
92 obj, err := root.MapUseNumber()
93 if err != nil {
94 t.Fatal(err)
95 }
96 exp, err := encoder.Encode(obj, encoder.SortMapKeys)
97 if err != nil {
98 t.Fatal(err)
99 }
100 var expObj interface{}
101 require.NoError(t, json.Unmarshal(exp, &expObj))
102
103 if err := root.SortKeys(true); err != nil {
104 t.Fatal(err)
105 }
106 act, err := root.MarshalJSON()
107 if err != nil {
108 t.Fatal(err)
109 }
110 var actObj interface{}
111 require.NoError(t, json.Unmarshal(act, &actObj))
112 require.Equal(t, expObj, actObj)
113 require.Equal(t, len(exp), len(act))
114 require.Equal(t, string(exp), string(act))
115 }
View as plain text