96 lines
2.0 KiB
Go
96 lines
2.0 KiB
Go
package pipe
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"io/ioutil"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func Test_PipeReader_Bench(t *testing.T) {
|
|
input := []byte(strings.Repeat("hello world", 1000))
|
|
pr := New()
|
|
pr.SetCap(1000)
|
|
writing := func() {
|
|
defer pr.Close()
|
|
if n, err := pr.Write(input); err != nil {
|
|
t.Errorf("failed to write: %v", err)
|
|
} else if n != len(input) {
|
|
t.Errorf("failed to write: wrote %v, expected %v", n, len(input))
|
|
}
|
|
}
|
|
reading := func() {
|
|
if bytes, err := ioutil.ReadAll(pr); err != nil {
|
|
t.Errorf("failed to read: %v", err)
|
|
} else if len(bytes) != len(input) {
|
|
t.Errorf("failed to read: read %v, expected %v", len(bytes), len(input))
|
|
}
|
|
}
|
|
go writing()
|
|
reading()
|
|
}
|
|
|
|
func Test_PipeReader(t *testing.T) {
|
|
cases := []struct {
|
|
streamLength int
|
|
bufferCap int
|
|
}{
|
|
{
|
|
streamLength: 10000000,
|
|
bufferCap: 50,
|
|
},
|
|
{
|
|
streamLength: 1000000,
|
|
bufferCap: 5000,
|
|
},
|
|
{
|
|
streamLength: 100,
|
|
bufferCap: 50,
|
|
},
|
|
{
|
|
streamLength: 50,
|
|
bufferCap: 100,
|
|
},
|
|
{
|
|
streamLength: 10,
|
|
bufferCap: 5,
|
|
},
|
|
{
|
|
streamLength: 5,
|
|
bufferCap: 10,
|
|
},
|
|
{
|
|
streamLength: 1,
|
|
bufferCap: 10,
|
|
},
|
|
{
|
|
streamLength: 0,
|
|
bufferCap: 10,
|
|
},
|
|
}
|
|
|
|
for _, c := range cases {
|
|
pr := New()
|
|
pr.SetCap(int64(c.bufferCap))
|
|
input := make([]byte, c.streamLength)
|
|
if _, err := rand.Read(input); err != nil {
|
|
t.Fatalf("cannot read random bytes: %v", err)
|
|
}
|
|
go func() {
|
|
defer pr.Close()
|
|
n, err := pr.Write(input)
|
|
if n != c.streamLength || err != nil {
|
|
t.Errorf("ERR: failed to write %v bytes to %v cap: %v", c.streamLength, c.bufferCap, err)
|
|
}
|
|
t.Logf("wrote %v bytes to pipereader", n)
|
|
}()
|
|
output, err := ioutil.ReadAll(pr)
|
|
if err != nil {
|
|
t.Errorf("ERR: failed to read %v bytes to %v cap: %v", c.streamLength, c.bufferCap, err)
|
|
} else if string(output) != string(input) {
|
|
t.Errorf("ERR: sl=%v, bc=%v, read wrong output from pipe: \nwanted %v, \n got %v", c.streamLength, c.bufferCap, len(input), len(output))
|
|
}
|
|
t.Logf("read %v bytes from pipereader", len(output))
|
|
}
|
|
}
|