This repository was archived by the owner on Dec 15, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathmax_marshalled_size_test.go
More file actions
77 lines (61 loc) · 1.89 KB
/
max_marshalled_size_test.go
File metadata and controls
77 lines (61 loc) · 1.89 KB
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
package misc_tests
import (
"fmt"
"testing"
"github.com/stretchr/testify/require"
jsoniter "github.com/json-iterator/go"
)
func TestMaxMarshalledSize(t *testing.T) {
testCases := []interface{}{
nil,
"",
false,
123,
123.123,
[]string{"foo", "bar"},
map[string]int{"foo": 123},
}
for _, testCase := range testCases {
t.Run(fmt.Sprintf("%#v", testCase), func(t *testing.T) {
expectedBytes, err := jsoniter.Marshal(testCase)
require.NoError(t, err)
expectedLength := uint64(len(expectedBytes))
expectSuccessfulMarshalling := func(t *testing.T, limit uint64) {
cfg := jsoniter.Config{
MaxMarshalledBytes: limit,
}
api := cfg.Froze()
actualBytes, err := api.Marshal(testCase)
require.NoError(t, err)
require.Equal(t, expectedBytes, actualBytes)
}
expectFailedMarshalling := func(t *testing.T, limit uint64) {
cfg := jsoniter.Config{
MaxMarshalledBytes: limit,
}
api := cfg.Froze()
actualBytes, err := api.Marshal(testCase)
require.ErrorContains(t, err, fmt.Sprintf("marshalling produced a result over the configured limit of %d bytes", limit))
require.Nil(t, actualBytes)
}
t.Run("limit set to 0 (unlimited)", func(t *testing.T) {
expectSuccessfulMarshalling(t, 0)
})
t.Run("limit set to exact length of output", func(t *testing.T) {
expectSuccessfulMarshalling(t, expectedLength)
})
t.Run("limit set to just under length of output", func(t *testing.T) {
expectFailedMarshalling(t, expectedLength-1)
})
t.Run("limit set to well under length of output", func(t *testing.T) {
expectFailedMarshalling(t, 1)
})
t.Run("limit set to just over length of output", func(t *testing.T) {
expectSuccessfulMarshalling(t, expectedLength+1)
})
t.Run("limit set to well over length of output", func(t *testing.T) {
expectSuccessfulMarshalling(t, expectedLength+100)
})
})
}
}