Add Pipe function to paster

master
Nick Krichevsky 2019-03-17 14:10:04 -04:00
parent a224fe15c0
commit f9b7eebc17
2 changed files with 56 additions and 1 deletions

View File

@ -8,7 +8,10 @@ import (
"github.com/ollien/updown/repository"
)
const pasteFileMode = 0644
const (
pasteFileMode = 0644
bufferSize = 1024
)
// TruncatableFile implements reading, writing, seeking, truncation, and closing
type TruncatableFile interface {
@ -94,3 +97,19 @@ func (p *Paster) Close() error {
return p.file.Close()
}
// Pipe pours the entirety of the underlying pate into the given writer
func (p *Paster) Pipe(w io.Writer) error {
buffer := make([]byte, bufferSize)
for {
n, err := p.Read(buffer)
if err == io.EOF {
break
} else if err != nil {
return err
}
w.Write(buffer[:n])
}
return nil
}

View File

@ -1,13 +1,16 @@
package paste
import (
"bytes"
"io"
"strings"
"testing"
"github.com/google/uuid"
"github.com/ollien/updown/repository"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
type MockFile struct {
@ -109,3 +112,36 @@ func TestClose(t *testing.T) {
mockFile.AssertNotCalled(t, "Seek", mock.Anything)
mockFile.AssertNotCalled(t, "Read", mock.Anything)
}
func TestPipe(t *testing.T) {
paster := setupPaster()
mockFile := paster.file.(*MockFile)
// For subsequent calls to Read, we need to return different errors and paste contents
readCursor := 0
pasteContents := []string{"hello", " pipe", ""}
errors := []error{nil, nil, io.EOF}
readCall := mockFile.On("Read", mock.Anything).Return(len(pasteContents[0]), nil)
readCall.Run(func(args mock.Arguments) {
buffer := args.Get(0).([]byte)
singlePasteContents := pasteContents[readCursor]
// Dump pasteContents into the buffer
for i, char := range singlePasteContents {
buffer[i] = byte(char)
}
readCall.Return(len(singlePasteContents), errors[readCursor])
readCursor++
// Cannot call this more times than we have values for
require.True(t, func() bool {
return readCursor <= len(pasteContents)
}())
})
mockFile.On("Seek", int64(0), 0).Return(int64(0), nil)
pipeBuffer := bytes.NewBuffer([]byte{})
err := paster.Pipe(pipeBuffer)
assert.Nil(t, err)
assert.Equal(t, strings.Join(pasteContents, ""), pipeBuffer.String())
}