github.com/euank/go@v0.0.0-20160829210321-495514729181/src/io/multi_test.go (about)

     1  // Copyright 2010 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package io_test
     6  
     7  import (
     8  	"bytes"
     9  	"crypto/sha1"
    10  	"errors"
    11  	"fmt"
    12  	. "io"
    13  	"io/ioutil"
    14  	"runtime"
    15  	"strings"
    16  	"testing"
    17  )
    18  
    19  func TestMultiReader(t *testing.T) {
    20  	var mr Reader
    21  	var buf []byte
    22  	nread := 0
    23  	withFooBar := func(tests func()) {
    24  		r1 := strings.NewReader("foo ")
    25  		r2 := strings.NewReader("")
    26  		r3 := strings.NewReader("bar")
    27  		mr = MultiReader(r1, r2, r3)
    28  		buf = make([]byte, 20)
    29  		tests()
    30  	}
    31  	expectRead := func(size int, expected string, eerr error) {
    32  		nread++
    33  		n, gerr := mr.Read(buf[0:size])
    34  		if n != len(expected) {
    35  			t.Errorf("#%d, expected %d bytes; got %d",
    36  				nread, len(expected), n)
    37  		}
    38  		got := string(buf[0:n])
    39  		if got != expected {
    40  			t.Errorf("#%d, expected %q; got %q",
    41  				nread, expected, got)
    42  		}
    43  		if gerr != eerr {
    44  			t.Errorf("#%d, expected error %v; got %v",
    45  				nread, eerr, gerr)
    46  		}
    47  		buf = buf[n:]
    48  	}
    49  	withFooBar(func() {
    50  		expectRead(2, "fo", nil)
    51  		expectRead(5, "o ", nil)
    52  		expectRead(5, "bar", nil)
    53  		expectRead(5, "", EOF)
    54  	})
    55  	withFooBar(func() {
    56  		expectRead(4, "foo ", nil)
    57  		expectRead(1, "b", nil)
    58  		expectRead(3, "ar", nil)
    59  		expectRead(1, "", EOF)
    60  	})
    61  	withFooBar(func() {
    62  		expectRead(5, "foo ", nil)
    63  	})
    64  }
    65  
    66  func TestMultiWriter(t *testing.T) {
    67  	sink := new(bytes.Buffer)
    68  	// Hide bytes.Buffer's WriteString method:
    69  	testMultiWriter(t, struct {
    70  		Writer
    71  		fmt.Stringer
    72  	}{sink, sink})
    73  }
    74  
    75  func TestMultiWriter_String(t *testing.T) {
    76  	testMultiWriter(t, new(bytes.Buffer))
    77  }
    78  
    79  // test that a multiWriter.WriteString calls results in at most 1 allocation,
    80  // even if multiple targets don't support WriteString.
    81  func TestMultiWriter_WriteStringSingleAlloc(t *testing.T) {
    82  	var sink1, sink2 bytes.Buffer
    83  	type simpleWriter struct { // hide bytes.Buffer's WriteString
    84  		Writer
    85  	}
    86  	mw := MultiWriter(simpleWriter{&sink1}, simpleWriter{&sink2})
    87  	allocs := int(testing.AllocsPerRun(1000, func() {
    88  		WriteString(mw, "foo")
    89  	}))
    90  	if allocs != 1 {
    91  		t.Errorf("num allocations = %d; want 1", allocs)
    92  	}
    93  }
    94  
    95  type writeStringChecker struct{ called bool }
    96  
    97  func (c *writeStringChecker) WriteString(s string) (n int, err error) {
    98  	c.called = true
    99  	return len(s), nil
   100  }
   101  
   102  func (c *writeStringChecker) Write(p []byte) (n int, err error) {
   103  	return len(p), nil
   104  }
   105  
   106  func TestMultiWriter_StringCheckCall(t *testing.T) {
   107  	var c writeStringChecker
   108  	mw := MultiWriter(&c)
   109  	WriteString(mw, "foo")
   110  	if !c.called {
   111  		t.Error("did not see WriteString call to writeStringChecker")
   112  	}
   113  }
   114  
   115  func testMultiWriter(t *testing.T, sink interface {
   116  	Writer
   117  	fmt.Stringer
   118  }) {
   119  	sha1 := sha1.New()
   120  	mw := MultiWriter(sha1, sink)
   121  
   122  	sourceString := "My input text."
   123  	source := strings.NewReader(sourceString)
   124  	written, err := Copy(mw, source)
   125  
   126  	if written != int64(len(sourceString)) {
   127  		t.Errorf("short write of %d, not %d", written, len(sourceString))
   128  	}
   129  
   130  	if err != nil {
   131  		t.Errorf("unexpected error: %v", err)
   132  	}
   133  
   134  	sha1hex := fmt.Sprintf("%x", sha1.Sum(nil))
   135  	if sha1hex != "01cb303fa8c30a64123067c5aa6284ba7ec2d31b" {
   136  		t.Error("incorrect sha1 value")
   137  	}
   138  
   139  	if sink.String() != sourceString {
   140  		t.Errorf("expected %q; got %q", sourceString, sink.String())
   141  	}
   142  }
   143  
   144  // Test that MultiReader copies the input slice and is insulated from future modification.
   145  func TestMultiReaderCopy(t *testing.T) {
   146  	slice := []Reader{strings.NewReader("hello world")}
   147  	r := MultiReader(slice...)
   148  	slice[0] = nil
   149  	data, err := ioutil.ReadAll(r)
   150  	if err != nil || string(data) != "hello world" {
   151  		t.Errorf("ReadAll() = %q, %v, want %q, nil", data, err, "hello world")
   152  	}
   153  }
   154  
   155  // Test that MultiWriter copies the input slice and is insulated from future modification.
   156  func TestMultiWriterCopy(t *testing.T) {
   157  	var buf bytes.Buffer
   158  	slice := []Writer{&buf}
   159  	w := MultiWriter(slice...)
   160  	slice[0] = nil
   161  	n, err := w.Write([]byte("hello world"))
   162  	if err != nil || n != 11 {
   163  		t.Errorf("Write(`hello world`) = %d, %v, want 11, nil", n, err)
   164  	}
   165  	if buf.String() != "hello world" {
   166  		t.Errorf("buf.String() = %q, want %q", buf.String(), "hello world")
   167  	}
   168  }
   169  
   170  // readerFunc is an io.Reader implemented by the underlying func.
   171  type readerFunc func(p []byte) (int, error)
   172  
   173  func (f readerFunc) Read(p []byte) (int, error) {
   174  	return f(p)
   175  }
   176  
   177  // Test that MultiReader properly flattens chained multiReaders when Read is called
   178  func TestMultiReaderFlatten(t *testing.T) {
   179  	pc := make([]uintptr, 1000) // 1000 should fit the full stack
   180  	var myDepth = runtime.Callers(0, pc)
   181  	var readDepth int // will contain the depth from which fakeReader.Read was called
   182  	var r Reader = MultiReader(readerFunc(func(p []byte) (int, error) {
   183  		readDepth = runtime.Callers(1, pc)
   184  		return 0, errors.New("irrelevant")
   185  	}))
   186  
   187  	// chain a bunch of multiReaders
   188  	for i := 0; i < 100; i++ {
   189  		r = MultiReader(r)
   190  	}
   191  
   192  	r.Read(nil) // don't care about errors, just want to check the call-depth for Read
   193  
   194  	if readDepth != myDepth+2 { // 2 should be multiReader.Read and fakeReader.Read
   195  		t.Errorf("multiReader did not flatten chained multiReaders: expected readDepth %d, got %d",
   196  			myDepth+2, readDepth)
   197  	}
   198  }
   199  
   200  // byteAndEOFReader is a Reader which reads one byte (the underlying
   201  // byte) and io.EOF at once in its Read call.
   202  type byteAndEOFReader byte
   203  
   204  func (b byteAndEOFReader) Read(p []byte) (n int, err error) {
   205  	if len(p) == 0 {
   206  		// Read(0 bytes) is useless. We expect no such useless
   207  		// calls in this test.
   208  		panic("unexpected call")
   209  	}
   210  	p[0] = byte(b)
   211  	return 1, EOF
   212  }
   213  
   214  // This used to yield bytes forever; issue 16795.
   215  func TestMultiReaderSingleByteWithEOF(t *testing.T) {
   216  	got, err := ioutil.ReadAll(LimitReader(MultiReader(byteAndEOFReader('a'), byteAndEOFReader('b')), 10))
   217  	if err != nil {
   218  		t.Fatal(err)
   219  	}
   220  	const want = "ab"
   221  	if string(got) != want {
   222  		t.Errorf("got %q; want %q", got, want)
   223  	}
   224  }
   225  
   226  // Test that a reader returning (n, EOF) at the end of an MultiReader
   227  // chain continues to return EOF on its final read, rather than
   228  // yielding a (0, EOF).
   229  func TestMultiReaderFinalEOF(t *testing.T) {
   230  	r := MultiReader(bytes.NewReader(nil), byteAndEOFReader('a'))
   231  	buf := make([]byte, 2)
   232  	n, err := r.Read(buf)
   233  	if n != 1 || err != EOF {
   234  		t.Errorf("got %v, %v; want 1, EOF", n, err)
   235  	}
   236  }