test_extensions.go raw
1 /*
2 * SPDX-FileCopyrightText: © Hypermode Inc. <hello@hypermode.com>
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6 package badger
7
8 // Important: Do NOT import the "testing" package, as otherwise, that
9 // will pull in imports into the production class that we do not want.
10
11 // TODO: Consider using this with specific compilation tags so that it only
12 // shows up when performing testing (e.g., specify build tag=unit).
13 // We are not yet ready to do that, as it may impact customer usage as
14 // well as requiring us to update the CI build flags. Moreover, the
15 // current model does not actually incur any significant cost.
16 // If we do this, we will also want to introduce a parallel file that
17 // overrides some of these structs and functions with empty contents.
18
19 // String constants for messages to be pushed to syncChan.
20 const (
21 updateDiscardStatsMsg = "updateDiscardStats iteration done"
22 endVLogInitMsg = "End: vlog.init(db)"
23 )
24
25 // testOnlyOptions specifies an extension to the type Options that we want to
26 // use only in the context of testing.
27 type testOnlyOptions struct {
28 // syncChan is used to listen for specific messages related to activities
29 // that can occur in a DB instance. Currently, this is only used in
30 // testing activities.
31 syncChan chan string
32 }
33
34 // testOnlyDBExtensions specifies an extension to the type DB that we want to
35 // use only in the context of testing.
36 type testOnlyDBExtensions struct {
37 syncChan chan string
38
39 // onCloseDiscardCapture will be populated by a DB instance during the
40 // process of performing the Close operation. Currently, we only consider
41 // using this during testing.
42 onCloseDiscardCapture map[uint64]uint64
43 }
44
45 // logToSyncChan sends a message to the DB's syncChan. Note that we expect
46 // that the DB never closes this channel; the responsibility for
47 // allocating and closing the channel belongs to the test module.
48 // if db.syncChan is nil or has never been initialized, ths will be
49 // silently ignored.
50 func (db *DB) logToSyncChan(msg string) {
51 if db.syncChan != nil {
52 db.syncChan <- msg
53 }
54 }
55
56 // captureDiscardStats will copy the contents of the discardStats file
57 // maintained by vlog to the onCloseDiscardCapture map specified by
58 // db.opt. Of couse, if db.opt.onCloseDiscardCapture is nil (as expected
59 // for a production system as opposed to a test system), this is a no-op.
60 func (db *DB) captureDiscardStats() {
61 if db.onCloseDiscardCapture != nil {
62 db.vlog.discardStats.Lock()
63 db.vlog.discardStats.Iterate(func(id, val uint64) {
64 db.onCloseDiscardCapture[id] = val
65 })
66 db.vlog.discardStats.Unlock()
67 }
68 }
69