github.com/matrixorigin/matrixone@v1.2.0/pkg/txn/storage/mem/kv_tree_test.go (about)

     1  // Copyright 2021 - 2022 Matrix Origin
     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 mem
    16  
    17  import (
    18  	"fmt"
    19  	"testing"
    20  
    21  	"github.com/stretchr/testify/assert"
    22  )
    23  
    24  func TestSetAndGetAndLenAtnDelete(t *testing.T) {
    25  	key := []byte("k1")
    26  	kv := NewKV()
    27  	assert.Equal(t, 0, kv.Len())
    28  
    29  	v, ok := kv.Get(key)
    30  	assert.False(t, ok)
    31  	assert.Empty(t, v)
    32  
    33  	kv.Set(key, key)
    34  	assert.Equal(t, 1, kv.Len())
    35  
    36  	v, ok = kv.Get(key)
    37  	assert.True(t, ok)
    38  	assert.Equal(t, key, v)
    39  
    40  	kv.Delete(key)
    41  	assert.Equal(t, 0, kv.Len())
    42  
    43  	v, ok = kv.Get(key)
    44  	assert.False(t, ok)
    45  	assert.Empty(t, v)
    46  }
    47  
    48  func TestAscendRange(t *testing.T) {
    49  	kv := NewKV()
    50  
    51  	for i := 0; i < 5; i++ {
    52  		k := []byte(fmt.Sprintf("k%d", i))
    53  		kv.Set(k, k)
    54  	}
    55  
    56  	cases := []struct {
    57  		from, to   []byte
    58  		expectKeys [][]byte
    59  	}{
    60  		{
    61  			from:       []byte("k0"),
    62  			to:         []byte("k5"),
    63  			expectKeys: [][]byte{[]byte("k0"), []byte("k1"), []byte("k2"), []byte("k3"), []byte("k4")},
    64  		},
    65  		{
    66  			from:       []byte("k0"),
    67  			to:         []byte("k6"),
    68  			expectKeys: [][]byte{[]byte("k0"), []byte("k1"), []byte("k2"), []byte("k3"), []byte("k4")},
    69  		},
    70  	}
    71  
    72  	for idx, c := range cases {
    73  		var keys [][]byte
    74  		kv.AscendRange(c.from, c.to, func(key, _ []byte) bool {
    75  			keys = append(keys, key)
    76  			return true
    77  		})
    78  		assert.Equal(t, c.expectKeys, keys, "idx %d", idx)
    79  	}
    80  }