-
Notifications
You must be signed in to change notification settings - Fork 4
/
enc_stream_test.go
124 lines (99 loc) · 2.42 KB
/
enc_stream_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
package jx
import (
"io"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/go-faster/errors"
)
func TestEncoderStreamingCheck(t *testing.T) {
a := require.New(t)
e := NewStreamingEncoder(io.Discard, -1)
_, err := e.Write([]byte("hello"))
a.ErrorIs(err, errStreaming)
_, err = e.WriteTo(io.Discard)
a.ErrorIs(err, errStreaming)
a.PanicsWithError(errStreaming.Error(), func() {
_ = e.String()
})
}
type errWriter struct {
err error
n int
}
func (e *errWriter) Write(p []byte) (int, error) {
n := e.n
if n <= 0 {
n = len(p)
}
return n, e.err
}
func TestEncoder_Close(t *testing.T) {
errTest := errors.New("test")
t.Run("FlushErr", func(t *testing.T) {
ew := &errWriter{err: errTest}
e := NewStreamingEncoder(ew, -1)
e.Null()
require.ErrorIs(t, e.Close(), errTest)
})
t.Run("WriteErr", func(t *testing.T) {
ew := &errWriter{err: errTest}
e := NewStreamingEncoder(ew, minEncoderBufSize)
e.Obj(func(e *Encoder) {
e.FieldStart(strings.Repeat("a", minEncoderBufSize))
e.Null()
})
require.ErrorIs(t, e.Close(), errTest)
})
t.Run("ShortWrite", func(t *testing.T) {
ew := &errWriter{n: 1}
e := NewStreamingEncoder(ew, -1)
e.Null()
require.ErrorIs(t, e.Close(), io.ErrShortWrite)
})
t.Run("OK", func(t *testing.T) {
e := NewStreamingEncoder(io.Discard, -1)
e.Null()
require.NoError(t, e.Close())
})
t.Run("NoStreaming", func(t *testing.T) {
var e Encoder
e.Null()
require.NoError(t, e.Close())
})
}
func TestEncoder_ResetWriter(t *testing.T) {
do := func(e *Encoder) {
e.ObjStart()
e.FieldStart(strings.Repeat("a", minEncoderBufSize))
e.Null()
e.ObjEnd()
require.NoError(t, e.Close())
}
var e Encoder
do(&e)
expected := e.String()
for range [3]struct{}{} {
var got strings.Builder
e.ResetWriter(&got)
do(&e)
require.Equal(t, expected, got.String())
}
}
// This benchmark is used to measure the overhead of ignoring errors.
func BenchmarkSkipError(b *testing.B) {
e := NewStreamingEncoder(io.Discard, minEncoderBufSize)
e.w.stream.setError(errors.New("test"))
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
encodeObject(e)
}
}
func TestStreamingEncoderBufferSize(t *testing.T) {
e := NewStreamingEncoder(io.Discard, -1)
assert.Equal(t, encoderBufSize, cap(e.w.Buf))
e = NewStreamingEncoder(io.Discard, minEncoderBufSize-1)
assert.Equal(t, minEncoderBufSize, cap(e.w.Buf))
}