2018-10-24 06:02:02 -04:00
|
|
|
package buf_test
|
|
|
|
|
|
|
|
import (
|
2018-11-15 16:06:54 -05:00
|
|
|
"crypto/rand"
|
2018-11-15 13:44:24 -05:00
|
|
|
"io"
|
2018-10-24 06:02:02 -04:00
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/golang/mock/gomock"
|
|
|
|
|
2021-02-16 15:31:50 -05:00
|
|
|
"github.com/v2fly/v2ray-core/v4/common/buf"
|
|
|
|
"github.com/v2fly/v2ray-core/v4/common/errors"
|
|
|
|
"github.com/v2fly/v2ray-core/v4/testing/mocks"
|
2018-10-24 06:02:02 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestReadError(t *testing.T) {
|
|
|
|
mockCtl := gomock.NewController(t)
|
|
|
|
defer mockCtl.Finish()
|
|
|
|
|
|
|
|
mockReader := mocks.NewReader(mockCtl)
|
|
|
|
mockReader.EXPECT().Read(gomock.Any()).Return(0, errors.New("error"))
|
|
|
|
|
|
|
|
err := buf.Copy(buf.NewReader(mockReader), buf.Discard)
|
|
|
|
if err == nil {
|
|
|
|
t.Fatal("expected error, but nil")
|
|
|
|
}
|
|
|
|
|
|
|
|
if !buf.IsReadError(err) {
|
|
|
|
t.Error("expected to be ReadError, but not")
|
|
|
|
}
|
|
|
|
|
|
|
|
if err.Error() != "error" {
|
|
|
|
t.Fatal("unexpected error message: ", err.Error())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestWriteError(t *testing.T) {
|
|
|
|
mockCtl := gomock.NewController(t)
|
|
|
|
defer mockCtl.Finish()
|
|
|
|
|
|
|
|
mockWriter := mocks.NewWriter(mockCtl)
|
|
|
|
mockWriter.EXPECT().Write(gomock.Any()).Return(0, errors.New("error"))
|
|
|
|
|
2018-11-15 16:06:54 -05:00
|
|
|
err := buf.Copy(buf.NewReader(rand.Reader), buf.NewWriter(mockWriter))
|
2018-10-24 06:02:02 -04:00
|
|
|
if err == nil {
|
|
|
|
t.Fatal("expected error, but nil")
|
|
|
|
}
|
|
|
|
|
|
|
|
if !buf.IsWriteError(err) {
|
|
|
|
t.Error("expected to be WriteError, but not")
|
|
|
|
}
|
|
|
|
|
|
|
|
if err.Error() != "error" {
|
|
|
|
t.Fatal("unexpected error message: ", err.Error())
|
|
|
|
}
|
|
|
|
}
|
2018-11-15 13:44:24 -05:00
|
|
|
|
2018-11-15 16:06:54 -05:00
|
|
|
type TestReader struct{}
|
|
|
|
|
|
|
|
func (TestReader) Read(b []byte) (int, error) {
|
|
|
|
return len(b), nil
|
|
|
|
}
|
|
|
|
|
2018-11-15 13:44:24 -05:00
|
|
|
func BenchmarkCopy(b *testing.B) {
|
2018-11-15 16:06:54 -05:00
|
|
|
reader := buf.NewReader(io.LimitReader(TestReader{}, 10240))
|
2018-11-15 13:44:24 -05:00
|
|
|
writer := buf.Discard
|
|
|
|
|
|
|
|
b.ResetTimer()
|
|
|
|
for i := 0; i < b.N; i++ {
|
|
|
|
_ = buf.Copy(reader, writer)
|
|
|
|
}
|
|
|
|
}
|