github.com/zuoyebang/bitalosdb@v1.1.1-0.20240516111551-79a8c4d8ce20/bitree/bdb/manydbs_test.go (about)

     1  // Copyright 2021 The Bitalosdb author(hustxrb@163.com) and other contributors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package bdb
    16  
    17  import (
    18  	"fmt"
    19  	"io/ioutil"
    20  	"math/rand"
    21  	"os"
    22  	"path/filepath"
    23  	"testing"
    24  )
    25  
    26  func createDb(t *testing.T) (*DB, func()) {
    27  	tempDirName, err := ioutil.TempDir("", "bdbmemtest")
    28  	if err != nil {
    29  		t.Fatalf("error creating temp dir: %v", err)
    30  	}
    31  	path := filepath.Join(tempDirName, "testdb.db")
    32  
    33  	bdb, err := Open(path, nil)
    34  	if err != nil {
    35  		t.Fatalf("error creating bdb db: %v", err)
    36  	}
    37  
    38  	cleanup := func() {
    39  		bdb.Close()
    40  		os.RemoveAll(tempDirName)
    41  	}
    42  
    43  	return bdb, cleanup
    44  }
    45  
    46  func createAndPutKeys(t *testing.T) {
    47  	t.Parallel()
    48  
    49  	db, cleanup := createDb(t)
    50  	defer cleanup()
    51  
    52  	bucketName := []byte("bucket")
    53  
    54  	for i := 0; i < 100; i++ {
    55  		err := db.Update(func(tx *Tx) error {
    56  			nodes, err := tx.CreateBucketIfNotExists(bucketName)
    57  			if err != nil {
    58  				return err
    59  			}
    60  
    61  			var key [16]byte
    62  			rand.Read(key[:])
    63  			if err := nodes.Put(key[:], nil); err != nil {
    64  				return err
    65  			}
    66  
    67  			return nil
    68  		})
    69  		if err != nil {
    70  			t.Fatal(err)
    71  		}
    72  	}
    73  }
    74  
    75  func TestManyDBs(t *testing.T) {
    76  	if testing.Short() {
    77  		t.Skip("skipping test in short mode")
    78  	}
    79  
    80  	for i := 0; i < 100; i++ {
    81  		t.Run(fmt.Sprintf("%d", i), createAndPutKeys)
    82  	}
    83  }