github.com/imannamdari/v2ray-core/v5@v5.0.5/common/buf/copy_test.go (about) 1 package buf_test 2 3 import ( 4 "crypto/rand" 5 "io" 6 "testing" 7 8 "github.com/golang/mock/gomock" 9 10 "github.com/imannamdari/v2ray-core/v5/common/buf" 11 "github.com/imannamdari/v2ray-core/v5/common/errors" 12 "github.com/imannamdari/v2ray-core/v5/testing/mocks" 13 ) 14 15 func TestReadError(t *testing.T) { 16 mockCtl := gomock.NewController(t) 17 defer mockCtl.Finish() 18 19 mockReader := mocks.NewReader(mockCtl) 20 mockReader.EXPECT().Read(gomock.Any()).Return(0, errors.New("error")) 21 22 err := buf.Copy(buf.NewReader(mockReader), buf.Discard) 23 if err == nil { 24 t.Fatal("expected error, but nil") 25 } 26 27 if !buf.IsReadError(err) { 28 t.Error("expected to be ReadError, but not") 29 } 30 31 if err.Error() != "error" { 32 t.Fatal("unexpected error message: ", err.Error()) 33 } 34 } 35 36 func TestWriteError(t *testing.T) { 37 mockCtl := gomock.NewController(t) 38 defer mockCtl.Finish() 39 40 mockWriter := mocks.NewWriter(mockCtl) 41 mockWriter.EXPECT().Write(gomock.Any()).Return(0, errors.New("error")) 42 43 err := buf.Copy(buf.NewReader(rand.Reader), buf.NewWriter(mockWriter)) 44 if err == nil { 45 t.Fatal("expected error, but nil") 46 } 47 48 if !buf.IsWriteError(err) { 49 t.Error("expected to be WriteError, but not") 50 } 51 52 if err.Error() != "error" { 53 t.Fatal("unexpected error message: ", err.Error()) 54 } 55 } 56 57 type TestReader struct{} 58 59 func (TestReader) Read(b []byte) (int, error) { 60 return len(b), nil 61 } 62 63 func BenchmarkCopy(b *testing.B) { 64 reader := buf.NewReader(io.LimitReader(TestReader{}, 10240)) 65 writer := buf.Discard 66 67 b.ResetTimer() 68 for i := 0; i < b.N; i++ { 69 _ = buf.Copy(reader, writer) 70 } 71 }