fstest/mockobject: add UnknownSize() method to make Size() return -1

This commit is contained in:
Nick Craig-Wood 2019-09-14 13:07:01 +01:00
parent ea9b6087cf
commit 2e80e035c9

View File

@ -96,9 +96,10 @@ var SeekModes = []SeekMode{SeekModeNone, SeekModeRegular, SeekModeRange}
// ContentMockObject mocks an fs.Object and has content // ContentMockObject mocks an fs.Object and has content
type ContentMockObject struct { type ContentMockObject struct {
Object Object
content []byte content []byte
seekMode SeekMode seekMode SeekMode
f fs.Fs f fs.Fs
unknownSize bool
} }
// WithContent returns a fs.Object with the given content. // WithContent returns a fs.Object with the given content.
@ -115,6 +116,11 @@ func (o *ContentMockObject) SetFs(f fs.Fs) {
o.f = f o.f = f
} }
// SetUnknownSize makes the mock object return -1 for size if true
func (o *ContentMockObject) SetUnknownSize(unknownSize bool) {
o.unknownSize = true
}
// Fs returns read only access to the Fs that this object is part of // Fs returns read only access to the Fs that this object is part of
// //
// This is nil unless SetFs has been called // This is nil unless SetFs has been called
@ -124,21 +130,22 @@ func (o *ContentMockObject) Fs() fs.Info {
// Open opens the file for read. Call Close() on the returned io.ReadCloser // Open opens the file for read. Call Close() on the returned io.ReadCloser
func (o *ContentMockObject) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadCloser, error) { func (o *ContentMockObject) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadCloser, error) {
size := int64(len(o.content))
var offset, limit int64 = 0, -1 var offset, limit int64 = 0, -1
for _, option := range options { for _, option := range options {
switch x := option.(type) { switch x := option.(type) {
case *fs.SeekOption: case *fs.SeekOption:
offset = x.Offset offset = x.Offset
case *fs.RangeOption: case *fs.RangeOption:
offset, limit = x.Decode(o.Size()) offset, limit = x.Decode(size)
default: default:
if option.Mandatory() { if option.Mandatory() {
return nil, fmt.Errorf("Unsupported mandatory option: %v", option) return nil, fmt.Errorf("Unsupported mandatory option: %v", option)
} }
} }
} }
if limit == -1 || offset+limit > o.Size() { if limit == -1 || offset+limit > size {
limit = o.Size() - offset limit = size - offset
} }
var r *bytes.Reader var r *bytes.Reader
@ -165,6 +172,9 @@ func (o *ContentMockObject) Open(ctx context.Context, options ...fs.OpenOption)
// Size returns the size of the file // Size returns the size of the file
func (o *ContentMockObject) Size() int64 { func (o *ContentMockObject) Size() int64 {
if o.unknownSize {
return -1
}
return int64(len(o.content)) return int64(len(o.content))
} }