Skip to content

Commit

Permalink
optionize txn kv tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jessepeterson committed Sep 11, 2024
1 parent b79e666 commit 9e297e3
Showing 1 changed file with 37 additions and 11 deletions.
48 changes: 37 additions & 11 deletions storage/kv/test/txn.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,23 @@ import (
"github.com/micromdm/nanolib/storage/kv"
)

func TestTxnSimple(t *testing.T, ctx context.Context, b kv.TxnCRUDBucket) {
type txnConfig struct {
noReadAfterRollback bool
}

type TxnOption func(*txnConfig)

func WithNoReadAfterRollback() TxnOption {
return func(c *txnConfig) {
c.noReadAfterRollback = true
}
}

func TestTxnSimple(t *testing.T, ctx context.Context, b kv.TxnCRUDBucket, opts ...TxnOption) {
config := new(txnConfig)
for _, opt := range opts {
opt(config)
}
// first, set a value in the "parent" bucket
err := b.Set(ctx, "test-txn-key-1", []byte("test-txn-val-1"))
if err != nil {
Expand Down Expand Up @@ -61,14 +77,22 @@ func TestTxnSimple(t *testing.T, ctx context.Context, b kv.TxnCRUDBucket) {
t.Errorf("have: %v, want: %v", string(have), string(want))
}

// read the value we just reset in the txn and make sure it was rolled back
val, err = bt.Get(ctx, "test-txn-key-1")
if !config.noReadAfterRollback {
// read the value we just reset in the txn and make sure it was rolled back
val, err = bt.Get(ctx, "test-txn-key-1")
if err != nil {
t.Fatal(err)
}
if have, want := val, []byte("test-txn-val-1"); !bytes.Equal(have, want) {
t.Errorf("have: %v, want: %v", string(have), string(want))
}
}

// create a txn again
bt, err = b.BeginCRUDBucketTxn(ctx)
if err != nil {
t.Fatal(err)
}
if have, want := val, []byte("test-txn-val-1"); !bytes.Equal(have, want) {
t.Errorf("have: %v, want: %v", string(have), string(want))
}

// okay, let's re-reset the value again
err = bt.Set(ctx, "test-txn-key-1", []byte("test-txn-val-2"))
Expand Down Expand Up @@ -119,11 +143,13 @@ func TestTxnSimple(t *testing.T, ctx context.Context, b kv.TxnCRUDBucket) {
t.Fatal(err)
}

// and try and read the values we just set (but discarded)
// should error with a key not found
_, err = bt.Get(ctx, "test-txn-key-2")
if !errors.Is(err, kv.ErrKeyNotFound) {
t.Fatal(err)
if !config.noReadAfterRollback {
// and try and read the values we just set (but discarded)
// should error with a key not found
_, err = bt.Get(ctx, "test-txn-key-2")
if !errors.Is(err, kv.ErrKeyNotFound) {
t.Fatal(err)
}
}

// .. same for the parent bucket
Expand Down

0 comments on commit 9e297e3

Please sign in to comment.