github.com/kaituanwang/hyperledger@v2.0.1+incompatible/core/ledger/util/util_test.go (about) 1 /* 2 Copyright IBM Corp. 2017 All Rights Reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package util 18 19 import ( 20 "bytes" 21 "testing" 22 23 "github.com/stretchr/testify/assert" 24 ) 25 26 func TestGetSortedKeys(t *testing.T) { 27 mapKeyValue := make(map[string]int) 28 mapKeyValue["blue"] = 10 29 mapKeyValue["apple"] = 15 30 mapKeyValue["red"] = 12 31 mapKeyValue["123"] = 22 32 mapKeyValue["a"] = 33 33 mapKeyValue[""] = 30 34 assert.Equal(t, []string{"", "123", "a", "apple", "blue", "red"}, GetSortedKeys(mapKeyValue)) 35 } 36 37 func TestGetValuesBySortedKeys(t *testing.T) { 38 type name struct { 39 fName string 40 lName string 41 } 42 mapKeyValue := make(map[string]*name) 43 mapKeyValue["2"] = &name{"Two", "two"} 44 mapKeyValue["3"] = &name{"Three", "three"} 45 mapKeyValue["5"] = &name{"Five", "five"} 46 mapKeyValue[""] = &name{"None", "none"} 47 48 sortedRes := []*name{} 49 GetValuesBySortedKeys(&mapKeyValue, &sortedRes) 50 assert.Equal( 51 t, 52 []*name{{"None", "none"}, {"Two", "two"}, {"Three", "three"}, {"Five", "five"}}, 53 sortedRes, 54 ) 55 } 56 57 func TestBasicEncodingDecoding(t *testing.T) { 58 for i := 0; i < 10000; i++ { 59 value := EncodeReverseOrderVarUint64(uint64(i)) 60 nextValue := EncodeReverseOrderVarUint64(uint64(i + 1)) 61 if !(bytes.Compare(value, nextValue) > 0) { 62 t.Fatalf("A smaller integer should result into greater bytes. Encoded bytes for [%d] is [%x] and for [%d] is [%x]", 63 i, i+1, value, nextValue) 64 } 65 decodedValue, _ := DecodeReverseOrderVarUint64(value) 66 if decodedValue != uint64(i) { 67 t.Fatalf("Value not same after decoding. Original value = [%d], decode value = [%d]", i, decodedValue) 68 } 69 } 70 } 71 72 func TestDecodingAppendedValues(t *testing.T) { 73 appendedValues := []byte{} 74 for i := 0; i < 1000; i++ { 75 appendedValues = append(appendedValues, EncodeReverseOrderVarUint64(uint64(i))...) 76 } 77 78 len := 0 79 value := uint64(0) 80 for i := 0; i < 1000; i++ { 81 appendedValues = appendedValues[len:] 82 value, len = DecodeReverseOrderVarUint64(appendedValues) 83 if value != uint64(i) { 84 t.Fatalf("expected value = [%d], decode value = [%d]", i, value) 85 } 86 } 87 }