-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdirectio_test.go
105 lines (85 loc) · 2.02 KB
/
directio_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// +build linux
package directio
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
)
var (
bufsizes = []int{
0, 16, 23, 32, 46, 64, 93, 128, 1024, 4096, 4197, 12384, 16384, 32754,
}
writesizes = []int{
8192, 16384, 16, 23, 32, 0, 46, 8192, 64, 93, 128, 1024, 4096, 4197, 12384, 16384, 32754,
}
)
func tmpDir(t testing.TB) (string, func()) {
dir, err := ioutil.TempDir("", "directio-test-")
if err != nil {
t.Fatal(err)
}
clean := func() {
os.RemoveAll(dir)
}
return dir, clean
}
func tmpFile(t testing.TB, dir string, prefix string) *os.File {
flags := os.O_WRONLY | os.O_EXCL | os.O_CREATE | O_DIRECT
f, err := os.OpenFile(filepath.Join(dir, fmt.Sprintf("foo-%s", prefix)), flags, 0666)
if err != nil {
t.Fatal(err)
}
return f
}
func TestWriter(t *testing.T) {
data := make([]byte, 2<<16) // 128KB test data
for i := 0; i < len(data); i++ {
data[i] = byte(' ' + i%('~'-' '))
}
dir, clean := tmpDir(t)
defer clean()
// Write nwrite bytes using buffer size bs.
// Check that the right amount makes it out
// and that the data is correct.
for i := 0; i < len(bufsizes); i++ {
var context string
twrite := 0
bs := bufsizes[i]
f := tmpFile(t, dir, fmt.Sprintf("%d", bs))
dio, err := NewSize(f, bs)
if err != nil {
t.Fatal(err)
}
point := 0
for j := 0; j < len(writesizes); j++ {
nwrite := writesizes[j]
twrite += nwrite
context = fmt.Sprintf("nwrite=%d bufsize=%d", nwrite, bs)
n, e1 := dio.Write(data[point : point+nwrite])
if e1 != nil || n != nwrite {
t.Errorf("%s: buf.Write %d = %d, %v", context, nwrite, n, e1)
continue
}
point += nwrite
}
if e := dio.Flush(); e != nil {
t.Errorf("%s: buf.Flush = %v", context, e)
}
fname := f.Name()
f.Close()
written, err := ioutil.ReadFile(fname)
if err != nil {
t.Fatal(err)
}
if len(written) != twrite {
t.Errorf("%s: %d bytes written", context, len(written))
}
// Check content
if !bytes.Equal(written, data[:twrite]) {
t.Fatal("wrong bytes were written")
}
}
}