File: btesting.go

package info (click to toggle)
golang-github-coreos-bbolt 1.4.2-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, sid
  • size: 1,300 kB
  • sloc: makefile: 87; sh: 57
file content (221 lines) | stat: -rw-r--r-- 5,449 bytes parent folder | download
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package btesting

import (
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"testing"
	"time"

	"github.com/stretchr/testify/require"

	bolt "go.etcd.io/bbolt"
)

var statsFlag = flag.Bool("stats", false, "show performance stats")

const (
	// TestFreelistType is used as an env variable for test to indicate the backend type.
	TestFreelistType = "TEST_FREELIST_TYPE"
	// TestEnableStrictMode is used to enable strict check by default after opening each DB.
	TestEnableStrictMode = "TEST_ENABLE_STRICT_MODE"
)

// DB is a test wrapper for bolt.DB.
type DB struct {
	*bolt.DB
	f string
	o *bolt.Options
	t testing.TB
}

// MustCreateDB returns a new, open DB at a temporary location.
func MustCreateDB(t testing.TB) *DB {
	return MustCreateDBWithOption(t, nil)
}

// MustCreateDBWithOption returns a new, open DB at a temporary location with given options.
func MustCreateDBWithOption(t testing.TB, o *bolt.Options) *DB {
	f := filepath.Join(t.TempDir(), "db")
	return MustOpenDBWithOption(t, f, o)
}

func MustOpenDBWithOption(t testing.TB, f string, o *bolt.Options) *DB {
	t.Logf("Opening bbolt DB at: %s", f)
	if o == nil {
		o = bolt.DefaultOptions
	}

	freelistType := bolt.FreelistArrayType
	if env := os.Getenv(TestFreelistType); env == string(bolt.FreelistMapType) {
		freelistType = bolt.FreelistMapType
	}

	o.FreelistType = freelistType

	db, err := bolt.Open(f, 0600, o)
	require.NoError(t, err)
	resDB := &DB{
		DB: db,
		f:  f,
		o:  o,
		t:  t,
	}
	resDB.strictModeEnabledDefault()
	t.Cleanup(resDB.PostTestCleanup)
	return resDB
}

func (db *DB) PostTestCleanup() {
	// Check database consistency after every test.
	if db.DB != nil {
		db.MustCheck()
		db.MustClose()
	}
}

// Close closes the database but does NOT delete the underlying file.
func (db *DB) Close() error {
	if db.DB != nil {
		// Log statistics.
		if *statsFlag {
			db.PrintStats()
		}
		db.t.Logf("Closing bbolt DB at: %s", db.f)
		err := db.DB.Close()
		if err != nil {
			return err
		}
		db.DB = nil
	}
	return nil
}

// MustClose closes the database but does NOT delete the underlying file.
func (db *DB) MustClose() {
	err := db.Close()
	require.NoError(db.t, err)
}

func (db *DB) MustDeleteFile() {
	err := os.Remove(db.Path())
	require.NoError(db.t, err)
}

func (db *DB) SetOptions(o *bolt.Options) {
	db.o = o
}

// MustReopen reopen the database. Panic on error.
func (db *DB) MustReopen() {
	if db.DB != nil {
		panic("Please call Close() before MustReopen()")
	}
	db.t.Logf("Reopening bbolt DB at: %s", db.f)
	indb, err := bolt.Open(db.Path(), 0600, db.o)
	require.NoError(db.t, err)
	db.DB = indb
	db.strictModeEnabledDefault()
}

// MustCheck runs a consistency check on the database and panics if any errors are found.
func (db *DB) MustCheck() {
	err := db.View(func(tx *bolt.Tx) error {
		// Collect all the errors.
		var errors []error
		for err := range tx.Check() {
			errors = append(errors, err)
			if len(errors) > 10 {
				break
			}
		}

		// If errors occurred, copy the DB and print the errors.
		if len(errors) > 0 {
			var path = filepath.Join(db.t.TempDir(), "db.backup")
			err := tx.CopyFile(path, 0600)
			require.NoError(db.t, err)

			// Print errors.
			fmt.Print("\n\n")
			fmt.Printf("consistency check failed (%d errors)\n", len(errors))
			for _, err := range errors {
				fmt.Println(err)
			}
			fmt.Println("")
			fmt.Println("db saved to:")
			fmt.Println(path)
			fmt.Print("\n\n")
			os.Exit(-1)
		}

		return nil
	})
	require.NoError(db.t, err)
}

// Fill - fills the DB using numTx transactions and numKeysPerTx.
func (db *DB) Fill(bucket []byte, numTx int, numKeysPerTx int,
	keyGen func(tx int, key int) []byte,
	valueGen func(tx int, key int) []byte) error {
	for tr := 0; tr < numTx; tr++ {
		err := db.Update(func(tx *bolt.Tx) error {
			b, _ := tx.CreateBucketIfNotExists(bucket)
			for i := 0; i < numKeysPerTx; i++ {
				if err := b.Put(keyGen(tr, i), valueGen(tr, i)); err != nil {
					return err
				}
			}
			return nil
		})
		if err != nil {
			return err
		}
	}
	return nil
}

func (db *DB) Path() string {
	return db.f
}

// CopyTempFile copies a database to a temporary file.
func (db *DB) CopyTempFile() {
	path := filepath.Join(db.t.TempDir(), "db.copy")
	err := db.View(func(tx *bolt.Tx) error {
		return tx.CopyFile(path, 0600)
	})
	require.NoError(db.t, err)
	fmt.Println("db copied to: ", path)
}

// PrintStats prints the database stats
func (db *DB) PrintStats() {
	var stats = db.Stats()
	fmt.Printf("[db] %-20s %-20s %-20s\n",
		fmt.Sprintf("pg(%d/%d)", stats.TxStats.GetPageCount(), stats.TxStats.GetPageAlloc()),
		fmt.Sprintf("cur(%d)", stats.TxStats.GetCursorCount()),
		fmt.Sprintf("node(%d/%d)", stats.TxStats.GetNodeCount(), stats.TxStats.GetNodeDeref()),
	)
	fmt.Printf("     %-20s %-20s %-20s\n",
		fmt.Sprintf("rebal(%d/%v)", stats.TxStats.GetRebalance(), truncDuration(stats.TxStats.GetRebalanceTime())),
		fmt.Sprintf("spill(%d/%v)", stats.TxStats.GetSpill(), truncDuration(stats.TxStats.GetSpillTime())),
		fmt.Sprintf("w(%d/%v)", stats.TxStats.GetWrite(), truncDuration(stats.TxStats.GetWriteTime())),
	)
}

func truncDuration(d time.Duration) string {
	return regexp.MustCompile(`^(\d+)(\.\d+)`).ReplaceAllString(d.String(), "$1")
}

func (db *DB) strictModeEnabledDefault() {
	strictModeEnabled := strings.ToLower(os.Getenv(TestEnableStrictMode))
	db.StrictMode = strictModeEnabled == "true"
}

func (db *DB) ForceDisableStrictMode() {
	db.StrictMode = false
}