storj/pkg/ranger/file_test.go

117 lines
2.4 KiB
Go
Raw Normal View History

2018-04-24 03:16:34 +01:00
// Copyright (C) 2018 Storj Labs, Inc.
// See LICENSE for copying information.
package ranger
import (
"bytes"
"context"
2018-04-24 03:16:34 +01:00
"io/ioutil"
"os"
2018-09-11 14:57:12 +01:00
"path/filepath"
"strconv"
2018-04-24 03:16:34 +01:00
"testing"
)
func TestFileRanger(t *testing.T) {
2018-09-11 14:57:12 +01:00
tempdir, err := ioutil.TempDir("", "storj-fileranger")
if err != nil {
t.Fatal(err)
}
defer func() {
err := os.RemoveAll(tempdir)
if err != nil {
_ = err // TODO: figure out what is holding the folder open
// t.Fatal(err)
}
}()
for i, example := range []struct {
2018-04-24 03:16:34 +01:00
data string
size, offset, length int64
substr string
fail bool
}{
{"", 0, 0, 0, "", false},
{"abcdef", 6, 0, 0, "", false},
{"abcdef", 6, 3, 0, "", false},
{"abcdef", 6, 0, 6, "abcdef", false},
{"abcdef", 6, 0, 5, "abcde", false},
{"abcdef", 6, 0, 4, "abcd", false},
{"abcdef", 6, 1, 4, "bcde", false},
{"abcdef", 6, 2, 4, "cdef", false},
{"abcdefg", 7, 1, 4, "bcde", false},
{"abcdef", 6, 0, 7, "", true},
{"abcdef", 6, -1, 7, "abcde", true},
{"abcdef", 6, 0, -1, "abcde", true},
} {
2018-09-11 14:57:12 +01:00
fh, err := os.Create(filepath.Join(tempdir, "test"+strconv.Itoa(i)))
2018-04-24 03:16:34 +01:00
if err != nil {
t.Fatalf("failed making tempfile")
}
_, err = fh.Write([]byte(example.data))
if err != nil {
t.Fatalf("failed writing data")
}
name := fh.Name()
err = fh.Close()
if err != nil {
t.Fatalf("failed closing data")
}
2018-09-11 14:57:12 +01:00
rr, err := FileRanger(name)
2018-04-24 03:16:34 +01:00
if err != nil {
t.Fatalf("failed opening tempfile")
}
if rr.Size() != example.size {
t.Fatalf("invalid size: %v != %v", rr.Size(), example.size)
2018-04-24 03:16:34 +01:00
}
2018-09-11 14:57:12 +01:00
r, err := rr.Range(context.Background(), example.offset, example.length)
2018-04-24 03:16:34 +01:00
if example.fail {
if err == nil {
t.Fatalf("expected error")
}
return
}
2018-09-11 14:57:12 +01:00
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
2018-09-11 14:57:12 +01:00
data, err := ioutil.ReadAll(r)
if err != nil {
t.Fatal(err)
}
2018-09-11 14:57:12 +01:00
if !bytes.Equal(data, []byte(example.substr)) {
t.Fatalf("invalid subrange: %#v != %#v", string(data), example.substr)
2018-04-24 03:16:34 +01:00
}
if err := rr.Close(); err != nil {
t.Fatalf("unable to close file %q: %v", name, err)
}
2018-04-24 03:16:34 +01:00
}
}
func TestFileRangerOpenFileError(t *testing.T) {
rr, err := FileRanger("")
if rr != nil {
t.Fatal("Ranger expected to be nil")
}
if err == nil {
t.Fatal("Error expected")
}
}
func TestFileRangerHandlerFileStatError(t *testing.T) {
rr, err := FileHandleRanger(nil)
if rr != nil {
t.Fatal("Ranger expected to be nil")
}
if err == nil {
t.Fatal("Error expected")
}
}