github.com/xuyutom/docker@v1.6.0/pkg/ioutils/readers_test.go (about)

     1  package ioutils
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  	"io/ioutil"
     7  	"testing"
     8  )
     9  
    10  func TestBufReader(t *testing.T) {
    11  	reader, writer := io.Pipe()
    12  	bufreader := NewBufReader(reader)
    13  
    14  	// Write everything down to a Pipe
    15  	// Usually, a pipe should block but because of the buffered reader,
    16  	// the writes will go through
    17  	done := make(chan bool)
    18  	go func() {
    19  		writer.Write([]byte("hello world"))
    20  		writer.Close()
    21  		done <- true
    22  	}()
    23  
    24  	// Drain the reader *after* everything has been written, just to verify
    25  	// it is indeed buffering
    26  	<-done
    27  	output, err := ioutil.ReadAll(bufreader)
    28  	if err != nil {
    29  		t.Fatal(err)
    30  	}
    31  	if !bytes.Equal(output, []byte("hello world")) {
    32  		t.Error(string(output))
    33  	}
    34  }
    35  
    36  type repeatedReader struct {
    37  	readCount int
    38  	maxReads  int
    39  	data      []byte
    40  }
    41  
    42  func newRepeatedReader(max int, data []byte) *repeatedReader {
    43  	return &repeatedReader{0, max, data}
    44  }
    45  
    46  func (r *repeatedReader) Read(p []byte) (int, error) {
    47  	if r.readCount >= r.maxReads {
    48  		return 0, io.EOF
    49  	}
    50  	r.readCount++
    51  	n := copy(p, r.data)
    52  	return n, nil
    53  }
    54  
    55  func testWithData(data []byte, reads int) {
    56  	reader := newRepeatedReader(reads, data)
    57  	bufReader := NewBufReader(reader)
    58  	io.Copy(ioutil.Discard, bufReader)
    59  }
    60  
    61  func Benchmark1M10BytesReads(b *testing.B) {
    62  	reads := 1000000
    63  	readSize := int64(10)
    64  	data := make([]byte, readSize)
    65  	b.SetBytes(readSize * int64(reads))
    66  	b.ResetTimer()
    67  	for i := 0; i < b.N; i++ {
    68  		testWithData(data, reads)
    69  	}
    70  }
    71  
    72  func Benchmark1M1024BytesReads(b *testing.B) {
    73  	reads := 1000000
    74  	readSize := int64(1024)
    75  	data := make([]byte, readSize)
    76  	b.SetBytes(readSize * int64(reads))
    77  	b.ResetTimer()
    78  	for i := 0; i < b.N; i++ {
    79  		testWithData(data, reads)
    80  	}
    81  }
    82  
    83  func Benchmark10k32KBytesReads(b *testing.B) {
    84  	reads := 10000
    85  	readSize := int64(32 * 1024)
    86  	data := make([]byte, readSize)
    87  	b.SetBytes(readSize * int64(reads))
    88  	b.ResetTimer()
    89  	for i := 0; i < b.N; i++ {
    90  		testWithData(data, reads)
    91  	}
    92  }