github.com/klaytn/klaytn@v1.12.1/storage/statedb/cache_test.go (about) 1 // Copyright 2020 The klaytn Authors 2 // This file is part of the klaytn library. 3 // 4 // The klaytn 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 klaytn 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 klaytn library. If not, see <http://www.gnu.org/licenses/>. 16 17 package statedb 18 19 import ( 20 "os" 21 "reflect" 22 "runtime" 23 "testing" 24 25 "github.com/klaytn/klaytn/common" 26 "github.com/stretchr/testify/assert" 27 ) 28 29 // TestNewTrieNodeCache tests creating all kinds of supported trie node caches. 30 func TestNewTrieNodeCache(t *testing.T) { 31 testCases := []struct { 32 cacheConfig *TrieNodeCacheConfig 33 expectedType reflect.Type 34 err error 35 }{ 36 {getTestFastCacheConfig(), reflect.TypeOf(&FastCache{}), nil}, 37 {getTestRedisConfig(), reflect.TypeOf(&RedisCache{}), nil}, 38 {getTestHybridConfig(), reflect.TypeOf(&HybridCache{}), nil}, 39 {nil, nil, errNilTrieNodeCacheConfig}, 40 } 41 42 for _, tc := range testCases { 43 cache, err := NewTrieNodeCache(tc.cacheConfig) 44 assert.Equal(t, err, tc.err) 45 assert.Equal(t, reflect.TypeOf(cache), tc.expectedType) 46 } 47 } 48 49 func TestFastCache_SaveAndLoad(t *testing.T) { 50 // Create test directory 51 dirName, err := os.MkdirTemp(os.TempDir(), "fastcache_saveandload") 52 if err != nil { 53 t.Fatal(err) 54 } 55 defer os.RemoveAll(dirName) 56 57 // Generate test data 58 var keys [][]byte 59 var vals [][]byte 60 for i := 0; i < 10; i++ { 61 keys = append(keys, common.MakeRandomBytes(128)) 62 vals = append(vals, common.MakeRandomBytes(128)) 63 } 64 65 config := getTestHybridConfig() 66 config.FastCacheFileDir = dirName 67 68 // Create a fastcache from the file and save the data to the cache 69 fastCache := newFastCache(config) 70 for idx, key := range keys { 71 assert.Equal(t, fastCache.Get(key), []byte(nil)) 72 fastCache.Set(key, vals[idx]) 73 assert.Equal(t, fastCache.Get(key), vals[idx]) 74 } 75 // Save the cache to the file 76 assert.NoError(t, fastCache.SaveToFile(dirName, runtime.NumCPU())) 77 78 // Create a fastcache from the file and check if the data exists 79 fastCacheFromFile := newFastCache(config) 80 for idx, key := range keys { 81 assert.Equal(t, fastCacheFromFile.Get(key), vals[idx]) 82 } 83 }