1package bbolt_test
2
3import (
4	"bytes"
5	"flag"
6	"fmt"
7	"math/rand"
8	"os"
9	"reflect"
10	"testing"
11	"testing/quick"
12	"time"
13)
14
15// testing/quick defaults to 5 iterations and a random seed.
16// You can override these settings from the command line:
17//
18//   -quick.count     The number of iterations to perform.
19//   -quick.seed      The seed to use for randomizing.
20//   -quick.maxitems  The maximum number of items to insert into a DB.
21//   -quick.maxksize  The maximum size of a key.
22//   -quick.maxvsize  The maximum size of a value.
23//
24
25var qcount, qseed, qmaxitems, qmaxksize, qmaxvsize int
26
27func TestMain(m *testing.M) {
28	flag.IntVar(&qcount, "quick.count", 5, "")
29	flag.IntVar(&qseed, "quick.seed", int(time.Now().UnixNano())%100000, "")
30	flag.IntVar(&qmaxitems, "quick.maxitems", 1000, "")
31	flag.IntVar(&qmaxksize, "quick.maxksize", 1024, "")
32	flag.IntVar(&qmaxvsize, "quick.maxvsize", 1024, "")
33	flag.Parse()
34	fmt.Fprintln(os.Stderr, "seed:", qseed)
35	fmt.Fprintf(os.Stderr, "quick settings: count=%v, items=%v, ksize=%v, vsize=%v\n", qcount, qmaxitems, qmaxksize, qmaxvsize)
36
37	m.Run()
38}
39
40func qconfig() *quick.Config {
41	return &quick.Config{
42		MaxCount: qcount,
43		Rand:     rand.New(rand.NewSource(int64(qseed))),
44	}
45}
46
47type testdata []testdataitem
48
49func (t testdata) Len() int           { return len(t) }
50func (t testdata) Swap(i, j int)      { t[i], t[j] = t[j], t[i] }
51func (t testdata) Less(i, j int) bool { return bytes.Compare(t[i].Key, t[j].Key) == -1 }
52
53func (t testdata) Generate(rand *rand.Rand, size int) reflect.Value {
54	n := rand.Intn(qmaxitems-1) + 1
55	items := make(testdata, n)
56	used := make(map[string]bool)
57	for i := 0; i < n; i++ {
58		item := &items[i]
59		// Ensure that keys are unique by looping until we find one that we have not already used.
60		for {
61			item.Key = randByteSlice(rand, 1, qmaxksize)
62			if !used[string(item.Key)] {
63				used[string(item.Key)] = true
64				break
65			}
66		}
67		item.Value = randByteSlice(rand, 0, qmaxvsize)
68	}
69	return reflect.ValueOf(items)
70}
71
72type revtestdata []testdataitem
73
74func (t revtestdata) Len() int           { return len(t) }
75func (t revtestdata) Swap(i, j int)      { t[i], t[j] = t[j], t[i] }
76func (t revtestdata) Less(i, j int) bool { return bytes.Compare(t[i].Key, t[j].Key) == 1 }
77
78type testdataitem struct {
79	Key   []byte
80	Value []byte
81}
82
83func randByteSlice(rand *rand.Rand, minSize, maxSize int) []byte {
84	n := rand.Intn(maxSize-minSize) + minSize
85	b := make([]byte, n)
86	for i := 0; i < n; i++ {
87		b[i] = byte(rand.Intn(255))
88	}
89	return b
90}
91