-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader_fuzz_test.go
67 lines (52 loc) · 1.24 KB
/
reader_fuzz_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
package buffbits
import (
"bytes"
"math/rand"
"testing"
"time"
fuzz "github.com/google/gofuzz"
"github.com/stretchr/testify/assert"
)
func TestFuzzReader(t *testing.T) {
t.Parallel()
iters := 1
seed := *fuzzRetrySeed
if seed == 0 {
iters = 50
seed = time.Now().UnixNano()
}
source := rand.NewSource(seed)
rng := rand.New(source)
fuzzer := fuzz.New().RandSource(source).NilChance(0).NumElements(1, 4096)
for i := 0; i < iters; i++ {
expected, actual, err := fuzzReader(rng, fuzzer)
assert.NoError(t, err)
if !assert.Equal(t, expected, actual) {
t.Logf("retry with '-seed %#v -run TestFuzzReader'", seed)
}
}
}
func fuzzReader(rng *rand.Rand, fuzzer *fuzz.Fuzzer) ([]byte, []byte, error) {
var data []byte
fuzzer.Fuzz(&data)
reader := NewReader(bytes.NewReader(data))
// Read the data stream in intervals of random bit counts.
var actual bytes.Buffer
writer := NewWriter(&actual)
left := len(data) * 8
for left != 0 {
maxBits := 64
if left < maxBits {
maxBits = left
}
bitsCount := rng.Intn(maxBits) + 1
left -= bitsCount
value, err := reader.Read(bitsCount)
if err != nil {
return nil, nil, err
}
writer.Write(value, bitsCount)
}
writer.Flush()
return data, actual.Bytes(), writer.Err()
}