github.com/weaviate/weaviate@v1.24.6/adapters/repos/db/lsmkv/segmentindex/balanced_test.go (about)

     1  //                           _       _
     2  // __      _____  __ ___   ___  __ _| |_ ___
     3  // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
     4  //  \ V  V /  __/ (_| |\ V /| | (_| | ||  __/
     5  //   \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
     6  //
     7  //  Copyright © 2016 - 2024 Weaviate B.V. All rights reserved.
     8  //
     9  //  CONTACT: hello@weaviate.io
    10  //
    11  
    12  package segmentindex
    13  
    14  import (
    15  	"crypto/rand"
    16  	"fmt"
    17  	"math"
    18  	"math/big"
    19  	"testing"
    20  
    21  	"github.com/stretchr/testify/assert"
    22  )
    23  
    24  func mustRandUint64() uint64 {
    25  	randInt, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64))
    26  	if err != nil {
    27  		panic(fmt.Sprintf("mustRandUint64 error: %v", err))
    28  	}
    29  	return randInt.Uint64()
    30  }
    31  
    32  func TestBuildBalancedTree(t *testing.T) {
    33  	size := 2000
    34  	idealHeight := int(math.Ceil(math.Log2(float64(size))))
    35  	fmt.Printf("ideal height would be %d\n", idealHeight)
    36  
    37  	nodes := make([]Node, size)
    38  	var tree Tree
    39  
    40  	t.Run("generate random data", func(t *testing.T) {
    41  		for i := range nodes {
    42  			nodes[i].Key = make([]byte, 8)
    43  			rand.Read(nodes[i].Key)
    44  
    45  			nodes[i].Start = mustRandUint64()
    46  			nodes[i].End = mustRandUint64()
    47  		}
    48  	})
    49  
    50  	t.Run("insert", func(t *testing.T) {
    51  		tree = NewBalanced(nodes)
    52  	})
    53  
    54  	t.Run("check height", func(t *testing.T) {
    55  		assert.Equal(t, idealHeight, tree.Height())
    56  	})
    57  
    58  	t.Run("check values", func(t *testing.T) {
    59  		for _, control := range nodes {
    60  			k, s, e := tree.Get(control.Key)
    61  
    62  			assert.Equal(t, control.Key, k)
    63  			assert.Equal(t, control.Start, s)
    64  			assert.Equal(t, control.End, e)
    65  		}
    66  	})
    67  }