Dealing with short writes. A more clean implementation of SynchronizeStreams to give a higher guarantee that all data will be written before the connections are closed.
70 lines
1.4 KiB
Go
70 lines
1.4 KiB
Go
package ioutils
|
|
|
|
import (
|
|
"bytes"
|
|
"github.com/stretchr/testify/suite"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
type RetryWriterTestSuite struct {
|
|
suite.Suite
|
|
}
|
|
|
|
func (s *RetryWriterTestSuite) SetupSuite() {
|
|
}
|
|
|
|
func (s *RetryWriterTestSuite) TearDownSuite() {
|
|
}
|
|
|
|
func (s *RetryWriterTestSuite) SetupTest() {
|
|
}
|
|
|
|
func (s *RetryWriterTestSuite) TearDownTest() {
|
|
}
|
|
|
|
func TestRetryWriterTestSuit(t *testing.T) {
|
|
suite.Run(t, &RetryWriterTestSuite{})
|
|
}
|
|
|
|
func (s *RetryWriterTestSuite) Test_WriteInOneGo() {
|
|
buf := &bytes.Buffer{}
|
|
retrier := &RetryWriter{Writer: buf}
|
|
bytesWritten := []byte("hello this is a test string")
|
|
|
|
t0 := time.Now()
|
|
retrier.Write(bytesWritten)
|
|
bytesRead := buf.Bytes()
|
|
s.Equal(bytesWritten, bytesRead)
|
|
// no delays introduced if data is writteni none go.
|
|
s.True(time.Now().Sub(t0) < 5*time.Millisecond)
|
|
}
|
|
|
|
type ShortWriteBuffer struct {
|
|
bytes.Buffer
|
|
}
|
|
|
|
func (buf *ShortWriteBuffer) Write(b []byte) (int, error) {
|
|
if len(b) == 0 {
|
|
return buf.Buffer.Write(b)
|
|
}
|
|
return buf.Buffer.Write(b[:1])
|
|
}
|
|
|
|
func (buf *ShortWriteBuffer) Bytes() []byte {
|
|
return buf.Buffer.Bytes()
|
|
}
|
|
|
|
func (s *RetryWriterTestSuite) Test_WriteInParts() {
|
|
buf := &ShortWriteBuffer{}
|
|
retrier := &RetryWriter{Writer: buf}
|
|
bytesWritten := []byte("hello this is a test string")
|
|
|
|
t0 := time.Now()
|
|
retrier.Write(bytesWritten)
|
|
bytesRead := buf.Bytes()
|
|
s.Equal(bytesWritten, bytesRead)
|
|
// no delays introduced if data is writteni none go.
|
|
s.True(time.Now().Sub(t0) > 5*time.Millisecond)
|
|
}
|