github.com/sandwich-go/boost@v1.3.29/xio/xio_test.go (about) 1 package xio 2 3 import ( 4 "bytes" 5 "context" 6 "io" 7 "testing" 8 "time" 9 ) 10 11 func TestReader(t *testing.T) { 12 buf := []byte("abcdef") 13 buf2 := make([]byte, 3) 14 r := NewReader(context.Background(), bytes.NewReader(buf)) 15 16 // read first half 17 n, err := r.Read(buf2) 18 if n != 3 { 19 t.Error("n should be 3") 20 } 21 if err != nil { 22 t.Error("should have no error") 23 } 24 if string(buf2) != string(buf[:3]) { 25 t.Error("incorrect contents") 26 } 27 28 // read second half 29 n, err = r.Read(buf2) 30 if n != 3 { 31 t.Error("n should be 3") 32 } 33 if err != nil { 34 t.Error("should have no error") 35 } 36 if string(buf2) != string(buf[3:6]) { 37 t.Error("incorrect contents") 38 } 39 40 // read more. 41 n, err = r.Read(buf2) 42 if n != 0 { 43 t.Error("n should be 0", n) 44 } 45 if err != io.EOF { 46 t.Error("should be EOF", err) 47 } 48 49 context.WithTimeout(context.Background(), 1*time.Second) 50 ctx, cancel := context.WithCancel(context.Background()) 51 r = NewReader(ctx, bytes.NewReader(buf)) 52 block = true 53 cancel() 54 _, err = r.Read(buf2) 55 if err == nil { 56 t.Error("should have error") 57 } 58 }