github.com/karrick/gorill@v1.10.3/testReader_test.go (about) 1 package gorill 2 3 import ( 4 "io" 5 "testing" 6 ) 7 8 // testReader is a structure used to simulate reads from. In order to test that 9 // an io.Reader implementation handles the various legal `io.Reader` responses, 10 // and not merely the observed behaviors of `bytes.Reader`, a `testReader` 11 // structure is defined that can be easily declared with various return values 12 // when it is read from. 13 type testReader struct { 14 tuples []tuple 15 } 16 17 func (tr *testReader) Read(p []byte) (int, error) { 18 l := len(tr.tuples) 19 if l == 0 { 20 // This test function panics when there are no more tuples to read, so 21 // when testing, if the io.Reader being tested invokes Read one too many 22 // times, its tests will fail. 23 panic("unexpected read") 24 } 25 t := tr.tuples[0] 26 tr.tuples = tr.tuples[1:] 27 n := copy(p, []byte(t.s)) 28 return n, t.e 29 } 30 31 type tuple struct { 32 s string 33 e error 34 } 35 36 // TestReader ensures that the testReader is working properly. 37 func TestReader(t *testing.T) { 38 buf := make([]byte, 64) 39 40 t.Run("read tuple panics when exhausted", func(t *testing.T) { 41 tr := testReader{tuples: nil} 42 ensurePanic(t, "unexpected read", func() { 43 _, _ = tr.Read(buf) 44 }) 45 }) 46 47 t.Run("source returns EOF with final data", func(t *testing.T) { 48 tr := testReader{tuples: []tuple{ 49 tuple{"first", io.EOF}, 50 }} 51 52 n, err := tr.Read(buf) 53 ensureError(t, err, "EOF") 54 if got, want := n, 5; got != want { 55 t.Fatalf("GOT: %v; WANT: %v", got, want) 56 } 57 if got, want := string(buf[:n]), "first"; got != want { 58 t.Errorf("GOT: %v; WANT: %v", got, want) 59 } 60 61 ensurePanic(t, "unexpected read", func() { 62 _, _ = tr.Read(buf) 63 }) 64 }) 65 66 t.Run("source returns EOF after final data", func(t *testing.T) { 67 tr := testReader{tuples: []tuple{ 68 tuple{"first", nil}, 69 tuple{"", io.EOF}, 70 }} 71 72 n, err := tr.Read(buf) 73 ensureError(t, err, "") 74 if got, want := n, 5; got != want { 75 t.Fatalf("GOT: %v; WANT: %v", got, want) 76 } 77 if got, want := string(buf[:n]), "first"; got != want { 78 t.Errorf("GOT: %v; WANT: %v", got, want) 79 } 80 81 n, err = tr.Read(buf) 82 ensureError(t, err, "EOF") 83 if got, want := n, 0; got != want { 84 t.Fatalf("GOT: %v; WANT: %v", got, want) 85 } 86 87 ensurePanic(t, "unexpected read", func() { 88 _, _ = tr.Read(buf) 89 }) 90 }) 91 }