github.com/hechain20/hechain@v0.0.0-20220316014945-b544036ba106/core/ledger/kvledger/history/kv_encoding_test.go (about)

     1  /*
     2  Copyright hechain. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package history
     8  
     9  import (
    10  	"bytes"
    11  	"testing"
    12  
    13  	"github.com/stretchr/testify/require"
    14  )
    15  
    16  func TestCompositeKeyConstruction(t *testing.T) {
    17  	type keyComponents struct {
    18  		ns, key         string
    19  		blkNum, tranNum uint64
    20  	}
    21  
    22  	testData := []*keyComponents{
    23  		{"ns1", "key1", 1, 0},
    24  		{"ns1", "key1\x00", 1, 5},
    25  		{"ns1", "key1\x00\x00", 100, 100},
    26  		{"ns1", "key\x00\x001", 100, 100},
    27  		{"ns1", "\x00key\x00\x001", 100, 100},
    28  	}
    29  
    30  	for _, testDatum := range testData {
    31  		key := constructDataKey(testDatum.ns, testDatum.key, testDatum.blkNum, testDatum.tranNum)
    32  		rangeScan := constructRangeScan(testDatum.ns, testDatum.key)
    33  		require.Equal(t, bytes.Compare(rangeScan.startKey, key), -1) // startKey should be smaller than key
    34  		require.Equal(t, bytes.Compare(rangeScan.endKey, key), 1)    // endKey should be greater than key
    35  	}
    36  
    37  	for i, testDatum := range testData {
    38  		for j, another := range testData {
    39  			if i == j {
    40  				continue
    41  			}
    42  			rangeScan := constructRangeScan(testDatum.ns, testDatum.key)
    43  			anotherKey := constructDataKey(another.ns, another.key, another.blkNum, another.tranNum)
    44  			require.False(t, bytes.Compare(anotherKey, rangeScan.startKey) == 1 && bytes.Compare(anotherKey, rangeScan.endKey) == -1) // any key should not fall in the range of start/end key range query for any other key
    45  		}
    46  	}
    47  }
    48  
    49  func TestSplitCompositeKey(t *testing.T) {
    50  	dataKey := constructDataKey("ns1", "key1", 20, 200)
    51  	rangeScan := constructRangeScan("ns1", "key1")
    52  	blkNum, txNum, err := rangeScan.decodeBlockNumTranNum(dataKey)
    53  	require.NoError(t, err)
    54  	require.Equal(t, blkNum, uint64(20))
    55  	require.Equal(t, txNum, uint64(200))
    56  }