Skip to content

Commit

Permalink
Fix Range requests to correctly interpret last-byte-pos (#255)
Browse files Browse the repository at this point in the history
* Fix Range requests to correctly interpret last-byte-pos

* Update existing tests
  • Loading branch information
chowey authored May 28, 2020
1 parent 24c142d commit 64e3d1e
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 4 deletions.
6 changes: 4 additions & 2 deletions fakestorage/object.go
Original file line number Diff line number Diff line change
Expand Up @@ -395,9 +395,11 @@ func (s *Server) handleRange(obj Object, r *http.Request) (start, end int, conte
rangeParts := strings.SplitN(parts[1], "-", 2)
if len(rangeParts) == 2 {
start, _ = strconv.Atoi(rangeParts[0])
end, _ = strconv.Atoi(rangeParts[1])
if end < 1 {
var err error
if end, err = strconv.Atoi(rangeParts[1]); err != nil {
end = len(obj.Content)
} else {
end++
}
return start, end, obj.Content[start:end]
}
Expand Down
52 changes: 50 additions & 2 deletions fakestorage/object_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -339,9 +339,9 @@ func TestServerClientObjectRangeReader(t *testing.T) {
t.Run(test.testCase, func(t *testing.T) {
length := test.length
if length == -1 {
length = int64(len(content)) - test.offset + 1
length = int64(len(content)) - test.offset
}
expectedData := content[test.offset : test.offset+length-1]
expectedData := content[test.offset : test.offset+length]
client := server.Client()
objHandle := client.Bucket(bucketName).Object(objectName)
reader, err := objHandle.NewRangeReader(context.TODO(), test.offset, test.length)
Expand Down Expand Up @@ -1260,3 +1260,51 @@ func checkObjectMetadata(actual, expected map[string]string, t *testing.T) {
}
}
}

func TestParseRangeRequest(t *testing.T) {
ctx := context.TODO()

in := []byte("this is a test object")

srv, _ := NewServerWithOptions(Options{
InitialObjects: []Object{
{
BucketName: "test-bucket",
Name: "test-object",
ContentType: "text/plain",
Content: in,
},
},
NoListener: true,
})
obj := srv.Client().Bucket("test-bucket").Object("test-object")

var tests = []struct {
Start int64
Length int64
}{
{4, 8},
{4, -1},
{0, 0},
{0, -1},
{0, 21},
}

for _, test := range tests {
start, length := test.Start, test.Length

rng, _ := obj.NewRangeReader(ctx, start, length)
out, _ := ioutil.ReadAll(rng)
rng.Close()

if length < 0 {
length = int64(len(in)) - start
}
if n := int64(len(out)); n != length {
t.Fatalf("expected %d bytes, RangeReader returned %d bytes", length, n)
}
if expected := in[start : start+length]; !bytes.Equal(expected, out) {
t.Fatalf("expected %q, RangeReader returned %q", expected, out)
}
}
}

0 comments on commit 64e3d1e

Please sign in to comment.