github.com/jimmyx0x/go-ethereum@v1.10.28/core/rawdb/key_length_iterator_test.go (about) 1 // Copyright 2022 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package rawdb 18 19 import ( 20 "encoding/binary" 21 "testing" 22 ) 23 24 func TestKeyLengthIterator(t *testing.T) { 25 db := NewMemoryDatabase() 26 27 keyLen := 8 28 expectedKeys := make(map[string]struct{}) 29 for i := 0; i < 100; i++ { 30 key := make([]byte, keyLen) 31 binary.BigEndian.PutUint64(key, uint64(i)) 32 if err := db.Put(key, []byte{0x1}); err != nil { 33 t.Fatal(err) 34 } 35 expectedKeys[string(key)] = struct{}{} 36 37 longerKey := make([]byte, keyLen*2) 38 binary.BigEndian.PutUint64(longerKey, uint64(i)) 39 if err := db.Put(longerKey, []byte{0x1}); err != nil { 40 t.Fatal(err) 41 } 42 } 43 44 it := NewKeyLengthIterator(db.NewIterator(nil, nil), keyLen) 45 for it.Next() { 46 key := it.Key() 47 _, exists := expectedKeys[string(key)] 48 if !exists { 49 t.Fatalf("Found unexpected key %d", binary.BigEndian.Uint64(key)) 50 } 51 delete(expectedKeys, string(key)) 52 if len(key) != keyLen { 53 t.Fatalf("Found unexpected key in key length iterator with length %d", len(key)) 54 } 55 } 56 57 if len(expectedKeys) != 0 { 58 t.Fatalf("Expected all keys of length %d to be removed from expected keys during iteration", keyLen) 59 } 60 }