github.com/ActiveState/go@v0.0.0-20170614201249-0b81c023a722/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 "time" 18 ) 19 20 func TestMultiReader(t *testing.T) { 21 var mr Reader 22 var buf []byte 23 nread := 0 24 withFooBar := func(tests func()) { 25 r1 := strings.NewReader("foo ") 26 r2 := strings.NewReader("") 27 r3 := strings.NewReader("bar") 28 mr = MultiReader(r1, r2, r3) 29 buf = make([]byte, 20) 30 tests() 31 } 32 expectRead := func(size int, expected string, eerr error) { 33 nread++ 34 n, gerr := mr.Read(buf[0:size]) 35 if n != len(expected) { 36 t.Errorf("#%d, expected %d bytes; got %d", 37 nread, len(expected), n) 38 } 39 got := string(buf[0:n]) 40 if got != expected { 41 t.Errorf("#%d, expected %q; got %q", 42 nread, expected, got) 43 } 44 if gerr != eerr { 45 t.Errorf("#%d, expected error %v; got %v", 46 nread, eerr, gerr) 47 } 48 buf = buf[n:] 49 } 50 withFooBar(func() { 51 expectRead(2, "fo", nil) 52 expectRead(5, "o ", nil) 53 expectRead(5, "bar", nil) 54 expectRead(5, "", EOF) 55 }) 56 withFooBar(func() { 57 expectRead(4, "foo ", nil) 58 expectRead(1, "b", nil) 59 expectRead(3, "ar", nil) 60 expectRead(1, "", EOF) 61 }) 62 withFooBar(func() { 63 expectRead(5, "foo ", nil) 64 }) 65 } 66 67 func TestMultiWriter(t *testing.T) { 68 sink := new(bytes.Buffer) 69 // Hide bytes.Buffer's WriteString method: 70 testMultiWriter(t, struct { 71 Writer 72 fmt.Stringer 73 }{sink, sink}) 74 } 75 76 func TestMultiWriter_String(t *testing.T) { 77 testMultiWriter(t, new(bytes.Buffer)) 78 } 79 80 // test that a multiWriter.WriteString calls results in at most 1 allocation, 81 // even if multiple targets don't support WriteString. 82 func TestMultiWriter_WriteStringSingleAlloc(t *testing.T) { 83 var sink1, sink2 bytes.Buffer 84 type simpleWriter struct { // hide bytes.Buffer's WriteString 85 Writer 86 } 87 mw := MultiWriter(simpleWriter{&sink1}, simpleWriter{&sink2}) 88 allocs := int(testing.AllocsPerRun(1000, func() { 89 WriteString(mw, "foo") 90 })) 91 if allocs != 1 { 92 t.Errorf("num allocations = %d; want 1", allocs) 93 } 94 } 95 96 type writeStringChecker struct{ called bool } 97 98 func (c *writeStringChecker) WriteString(s string) (n int, err error) { 99 c.called = true 100 return len(s), nil 101 } 102 103 func (c *writeStringChecker) Write(p []byte) (n int, err error) { 104 return len(p), nil 105 } 106 107 func TestMultiWriter_StringCheckCall(t *testing.T) { 108 var c writeStringChecker 109 mw := MultiWriter(&c) 110 WriteString(mw, "foo") 111 if !c.called { 112 t.Error("did not see WriteString call to writeStringChecker") 113 } 114 } 115 116 func testMultiWriter(t *testing.T, sink interface { 117 Writer 118 fmt.Stringer 119 }) { 120 sha1 := sha1.New() 121 mw := MultiWriter(sha1, sink) 122 123 sourceString := "My input text." 124 source := strings.NewReader(sourceString) 125 written, err := Copy(mw, source) 126 127 if written != int64(len(sourceString)) { 128 t.Errorf("short write of %d, not %d", written, len(sourceString)) 129 } 130 131 if err != nil { 132 t.Errorf("unexpected error: %v", err) 133 } 134 135 sha1hex := fmt.Sprintf("%x", sha1.Sum(nil)) 136 if sha1hex != "01cb303fa8c30a64123067c5aa6284ba7ec2d31b" { 137 t.Error("incorrect sha1 value") 138 } 139 140 if sink.String() != sourceString { 141 t.Errorf("expected %q; got %q", sourceString, sink.String()) 142 } 143 } 144 145 // Test that MultiReader copies the input slice and is insulated from future modification. 146 func TestMultiReaderCopy(t *testing.T) { 147 slice := []Reader{strings.NewReader("hello world")} 148 r := MultiReader(slice...) 149 slice[0] = nil 150 data, err := ioutil.ReadAll(r) 151 if err != nil || string(data) != "hello world" { 152 t.Errorf("ReadAll() = %q, %v, want %q, nil", data, err, "hello world") 153 } 154 } 155 156 // Test that MultiWriter copies the input slice and is insulated from future modification. 157 func TestMultiWriterCopy(t *testing.T) { 158 var buf bytes.Buffer 159 slice := []Writer{&buf} 160 w := MultiWriter(slice...) 161 slice[0] = nil 162 n, err := w.Write([]byte("hello world")) 163 if err != nil || n != 11 { 164 t.Errorf("Write(`hello world`) = %d, %v, want 11, nil", n, err) 165 } 166 if buf.String() != "hello world" { 167 t.Errorf("buf.String() = %q, want %q", buf.String(), "hello world") 168 } 169 } 170 171 // readerFunc is an io.Reader implemented by the underlying func. 172 type readerFunc func(p []byte) (int, error) 173 174 func (f readerFunc) Read(p []byte) (int, error) { 175 return f(p) 176 } 177 178 // callDepth returns the logical call depth for the given PCs. 179 func callDepth(callers []uintptr) (depth int) { 180 frames := runtime.CallersFrames(callers) 181 more := true 182 for more { 183 _, more = frames.Next() 184 depth++ 185 } 186 return 187 } 188 189 // Test that MultiReader properly flattens chained multiReaders when Read is called 190 func TestMultiReaderFlatten(t *testing.T) { 191 pc := make([]uintptr, 1000) // 1000 should fit the full stack 192 n := runtime.Callers(0, pc) 193 var myDepth = callDepth(pc[:n]) 194 var readDepth int // will contain the depth from which fakeReader.Read was called 195 var r Reader = MultiReader(readerFunc(func(p []byte) (int, error) { 196 n := runtime.Callers(1, pc) 197 readDepth = callDepth(pc[:n]) 198 return 0, errors.New("irrelevant") 199 })) 200 201 // chain a bunch of multiReaders 202 for i := 0; i < 100; i++ { 203 r = MultiReader(r) 204 } 205 206 r.Read(nil) // don't care about errors, just want to check the call-depth for Read 207 208 if readDepth != myDepth+2 { // 2 should be multiReader.Read and fakeReader.Read 209 t.Errorf("multiReader did not flatten chained multiReaders: expected readDepth %d, got %d", 210 myDepth+2, readDepth) 211 } 212 } 213 214 // byteAndEOFReader is a Reader which reads one byte (the underlying 215 // byte) and io.EOF at once in its Read call. 216 type byteAndEOFReader byte 217 218 func (b byteAndEOFReader) Read(p []byte) (n int, err error) { 219 if len(p) == 0 { 220 // Read(0 bytes) is useless. We expect no such useless 221 // calls in this test. 222 panic("unexpected call") 223 } 224 p[0] = byte(b) 225 return 1, EOF 226 } 227 228 // This used to yield bytes forever; issue 16795. 229 func TestMultiReaderSingleByteWithEOF(t *testing.T) { 230 got, err := ioutil.ReadAll(LimitReader(MultiReader(byteAndEOFReader('a'), byteAndEOFReader('b')), 10)) 231 if err != nil { 232 t.Fatal(err) 233 } 234 const want = "ab" 235 if string(got) != want { 236 t.Errorf("got %q; want %q", got, want) 237 } 238 } 239 240 // Test that a reader returning (n, EOF) at the end of an MultiReader 241 // chain continues to return EOF on its final read, rather than 242 // yielding a (0, EOF). 243 func TestMultiReaderFinalEOF(t *testing.T) { 244 r := MultiReader(bytes.NewReader(nil), byteAndEOFReader('a')) 245 buf := make([]byte, 2) 246 n, err := r.Read(buf) 247 if n != 1 || err != EOF { 248 t.Errorf("got %v, %v; want 1, EOF", n, err) 249 } 250 } 251 252 func TestMultiReaderFreesExhaustedReaders(t *testing.T) { 253 var mr Reader 254 closed := make(chan struct{}) 255 // The closure ensures that we don't have a live reference to buf1 256 // on our stack after MultiReader is inlined (Issue 18819). This 257 // is a work around for a limitation in liveness analysis. 258 func() { 259 buf1 := bytes.NewReader([]byte("foo")) 260 buf2 := bytes.NewReader([]byte("bar")) 261 mr = MultiReader(buf1, buf2) 262 runtime.SetFinalizer(buf1, func(*bytes.Reader) { 263 close(closed) 264 }) 265 }() 266 267 buf := make([]byte, 4) 268 if n, err := ReadFull(mr, buf); err != nil || string(buf) != "foob" { 269 t.Fatalf(`ReadFull = %d (%q), %v; want 3, "foo", nil`, n, buf[:n], err) 270 } 271 272 runtime.GC() 273 select { 274 case <-closed: 275 case <-time.After(5 * time.Second): 276 t.Fatal("timeout waiting for collection of buf1") 277 } 278 279 if n, err := ReadFull(mr, buf[:2]); err != nil || string(buf[:2]) != "ar" { 280 t.Fatalf(`ReadFull = %d (%q), %v; want 2, "ar", nil`, n, buf[:n], err) 281 } 282 } 283 284 func TestInterleavedMultiReader(t *testing.T) { 285 r1 := strings.NewReader("123") 286 r2 := strings.NewReader("45678") 287 288 mr1 := MultiReader(r1, r2) 289 mr2 := MultiReader(mr1) 290 291 buf := make([]byte, 4) 292 293 // Have mr2 use mr1's []Readers. 294 // Consume r1 (and clear it for GC to handle) and consume part of r2. 295 n, err := ReadFull(mr2, buf) 296 if got := string(buf[:n]); got != "1234" || err != nil { 297 t.Errorf(`ReadFull(mr2) = (%q, %v), want ("1234", nil)`, got, err) 298 } 299 300 // Consume the rest of r2 via mr1. 301 // This should not panic even though mr2 cleared r1. 302 n, err = ReadFull(mr1, buf) 303 if got := string(buf[:n]); got != "5678" || err != nil { 304 t.Errorf(`ReadFull(mr1) = (%q, %v), want ("5678", nil)`, got, err) 305 } 306 }