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