-
Notifications
You must be signed in to change notification settings - Fork 4
/
dec_obj_test.go
88 lines (80 loc) · 1.85 KB
/
dec_obj_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
package jx
import (
"encoding/json"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestDecoder_ObjBytes(t *testing.T) {
t.Run("Object", func(t *testing.T) {
i := DecodeStr(`{ "id" :1 , "randomNumber" : 10 }`)
met := map[string]struct{}{}
require.NoError(t, i.ObjBytes(func(i *Decoder, key []byte) error {
switch string(key) {
case "id":
v, err := i.Int64()
assert.NoError(t, err)
assert.Equal(t, int64(1), v)
met["id"] = struct{}{}
case "randomNumber":
v, err := i.Int64()
if err != nil {
return err
}
assert.Equal(t, int64(10), v)
met["randomNumber"] = struct{}{}
}
return nil
}))
if len(met) != 2 {
t.Error("not all keys met")
}
})
t.Run("Depth", func(t *testing.T) {
var input []byte
for i := 0; i <= maxDepth; i++ {
input = append(input, `{"1":`...)
}
d := DecodeBytes(input)
require.ErrorIs(t, d.ObjBytes(func(d *Decoder, key []byte) error {
return crawlValue(d)
}), errMaxDepth)
})
t.Run("Invalid", func(t *testing.T) {
for _, s := range testObjs {
checker := require.Error
if json.Valid([]byte(s)) {
continue
}
d := DecodeStr(s)
err := d.ObjBytes(func(d *Decoder, key []byte) error {
return crawlValue(d)
})
if err == nil && len(d.buf) > 0 {
// FIXME(tdakkota): fix cases like {"hello":{}}}
continue
}
checker(t, err, s)
}
})
}
func TestDecoderObjBytesIssue62(t *testing.T) {
a := require.New(t)
const input = `{"1":1,"2":2}`
// Force decoder to read only first 4 bytes of input.
d := Decode(strings.NewReader(input), 4)
actual := map[string]int{}
a.NoError(d.ObjBytes(func(d *Decoder, key []byte) error {
val, err := d.Int()
if err != nil {
return err
}
actual[string(key)] = val
return nil
}))
a.Equal(map[string]int{
"1": 1,
"2": 2,
}, actual)
}