shad-go/gzep/encode_test.go

84 lines
1.5 KiB
Go
Raw Normal View History

2022-05-05 22:10:05 +00:00
package gzep_test
2022-05-05 16:08:49 +00:00
import (
"bytes"
"compress/gzip"
"io"
2022-05-05 20:30:04 +00:00
"sync"
2022-05-05 16:08:49 +00:00
"testing"
"github.com/stretchr/testify/require"
2022-05-05 19:14:33 +00:00
2022-05-05 22:10:05 +00:00
"gitlab.com/slon/shad-go/gzep"
2022-05-05 16:08:49 +00:00
"gitlab.com/slon/shad-go/tools/testtool"
)
func BenchmarkEncode(b *testing.B) {
data := []byte(
"New function should generally only return pointer types, " +
"since a pointer can be put into the return interface " +
"value without an allocation. " +
testtool.RandomName(),
)
b.ResetTimer()
b.ReportAllocs()
for n := 0; n < b.N; n++ {
2022-05-05 22:10:05 +00:00
require.NoError(b, gzep.Encode(data, io.Discard))
2022-05-05 16:08:49 +00:00
}
}
2022-05-05 20:30:04 +00:00
func TestEncode_RoundTrip(t *testing.T) {
2022-05-05 16:08:49 +00:00
testCases := []struct {
name string
in string
}{
{name: "empty", in: ""},
{name: "simple", in: "A long time ago in a galaxy far, far away..."},
{name: "random", in: testtool.RandomName()},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
buf := new(bytes.Buffer)
2022-05-05 22:10:05 +00:00
require.NoError(t, gzep.Encode([]byte(tc.in), buf))
2022-05-05 16:08:49 +00:00
2022-05-05 22:10:05 +00:00
out, err := decode(buf)
2022-05-05 16:08:49 +00:00
require.NoError(t, err, tc.in)
require.Equal(t, tc.in, string(out))
})
}
}
2022-05-05 20:30:04 +00:00
func TestEncode_Stress(t *testing.T) {
wg := &sync.WaitGroup{}
2022-05-05 22:10:05 +00:00
n := 100
2022-05-05 20:30:04 +00:00
for i := 0; i < n; i++ {
2022-05-05 22:10:05 +00:00
wg.Add(1)
2022-05-05 20:30:04 +00:00
go func() {
defer wg.Done()
2022-05-05 22:10:05 +00:00
_ = gzep.Encode([]byte("stonks"), io.Discard)
2022-05-05 20:30:04 +00:00
}()
}
wg.Wait()
}
2022-05-05 22:10:05 +00:00
func decode(r io.Reader) ([]byte, error) {
rr, err := gzip.NewReader(r)
2022-05-05 16:08:49 +00:00
if err != nil {
return nil, err
}
2022-05-05 22:10:05 +00:00
defer func() { _ = rr.Close() }()
2022-05-05 16:08:49 +00:00
buf := &bytes.Buffer{}
2022-05-05 22:10:05 +00:00
if _, err := io.Copy(buf, rr); err != nil {
2022-05-05 16:08:49 +00:00
return nil, err
}
return buf.Bytes(), nil
}