Files
bytebufferpool/bytebuffer_test.go
T
2016-06-29 17:48:49 +03:00

70 lines
1.4 KiB
Go

package bytebufferpool
import (
"bytes"
"fmt"
"io"
"testing"
"time"
)
func TestByteBufferWriteTo(t *testing.T) {
expectedS := "foobarbaz"
var bb ByteBuffer
bb.WriteString(expectedS[:3])
bb.WriteString(expectedS[3:])
wt := (io.WriterTo)(&bb)
var w bytes.Buffer
for i := 0; i < 10; i++ {
n, err := wt.WriteTo(&w)
if n != int64(len(expectedS)) {
t.Fatalf("unexpected n returned from WriteTo: %d. Expecting %d", n, len(expectedS))
}
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
s := string(w.Bytes())
if s != expectedS {
t.Fatalf("unexpected string written %q. Expecting %q", s, expectedS)
}
w.Reset()
}
}
func TestByteBufferGetPutSerial(t *testing.T) {
testByteBufferGetPut(t)
}
func TestByteBufferGetPutConcurrent(t *testing.T) {
concurrency := 10
ch := make(chan struct{}, concurrency)
for i := 0; i < concurrency; i++ {
go func() {
testByteBufferGetPut(t)
ch <- struct{}{}
}()
}
for i := 0; i < concurrency; i++ {
select {
case <-ch:
case <-time.After(time.Second):
t.Fatalf("timeout!")
}
}
}
func testByteBufferGetPut(t *testing.T) {
for i := 0; i < 10; i++ {
expectedS := fmt.Sprintf("num %d", i)
b := Get()
b.B = append(b.B, "num "...)
b.B = append(b.B, fmt.Sprintf("%d", i)...)
if string(b.B) != expectedS {
t.Fatalf("unexpected result: %q. Expecting %q", b.B, expectedS)
}
Put(b)
}
}