-
Notifications
You must be signed in to change notification settings - Fork 0
/
segment_test.go
128 lines (115 loc) · 2.52 KB
/
segment_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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package hasty
import (
"bytes"
"errors"
"io"
"os"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
)
func TestOpenReadonlySegment_error(t *testing.T) {
tests := map[string]struct {
path string
want error
}{
"no file": {"testdata/404segment", os.ErrNotExist},
"file exists": {"testdata/readsegment", nil},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
_, err := openReadonlySegment(tc.path)
if !errors.Is(err, tc.want) {
t.Errorf("expected: %v, got: %v", tc.want, err)
}
})
}
}
func TestOpenWriteonlySegment_error(t *testing.T) {
tests := map[string]struct {
path string
want error
}{
"no file": {"testdata/404segment", nil},
"file exists": {"testdata/readsegment", os.ErrExist},
}
t.Cleanup(func() {
os.Remove("testdata/404segment")
})
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
_, err := openWriteonlySegment(tc.path)
if !errors.Is(err, tc.want) {
t.Errorf("expected: %v, got: %v", tc.want, err)
}
})
}
}
func TestEncode(t *testing.T) {
tests := map[string]struct {
key string
value []byte
want []byte
}{
"name=Bob": {
// [110 97 109 101]
key: "name",
// [66 111 98]
value: []byte("Bob"),
// record len (4 bytes) + key + delimeter (1 byte) + value
want: []byte{12, 0, 0, 0, 110, 97, 109, 101, 0, 66, 111, 98},
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
var out bytes.Buffer
rec := record{
key: tc.key,
value: tc.value,
}
if err := encode(&out, &rec); err != nil {
t.Fatal(err)
}
if diff := cmp.Diff(tc.want, out.Bytes()); diff != "" {
t.Fatalf(diff)
}
})
}
}
func TestDecode(t *testing.T) {
tests := map[string]struct {
b []byte
wantKey string
wantValue []byte
}{
"name=Bob": {
b: []byte{12, 0, 0, 0, 110, 97, 109, 101, 0, 66, 111, 98},
wantKey: "name",
wantValue: []byte("Bob"),
},
}
for _, tc := range tests {
rec := decode(tc.b)
if rec.key != tc.wantKey {
t.Errorf("expected key: %q got: %q", tc.wantKey, rec.key)
}
if !bytes.Equal(rec.value, tc.wantValue) {
t.Errorf("expected value: %q got: %q", tc.wantValue, rec.value)
}
}
}
func plainDecode(b []byte) *record {
kv := strings.Split(string(b), ":")
return &record{
key: kv[0],
value: []byte(kv[1]),
}
}
func plainEncode(out io.Writer, rec *record) (err error) {
ew := &errWriter{Writer: out}
ew.Write([]byte("\n"))
ew.Write([]byte(rec.key))
ew.Write([]byte(":"))
ew.Write([]byte(rec.value))
return ew.err
}