github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/core/storage/boltdb/storage_test.go (about) 1 /* 2 * Copyright (C) 2019 The "MysteriumNetwork/node" Authors. 3 * 4 * This program is free software: you can redistribute it and/or modify 5 * it under the terms of the GNU 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 * This program 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 General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program. If not, see <http://www.gnu.org/licenses/>. 16 */ 17 18 package boltdb 19 20 import ( 21 "testing" 22 23 "github.com/stretchr/testify/assert" 24 25 "github.com/mysteriumnetwork/node/core/storage/boltdb/boltdbtest" 26 ) 27 28 type myTestType struct { 29 ID int64 `storm:"id"` 30 } 31 32 var ( 33 bucket = "test" 34 ) 35 36 func createMockStorage(t *testing.T) (*Bolt, func(), error) { 37 dir := boltdbtest.CreateTempDir(t) 38 close := func() { 39 boltdbtest.RemoveTempDir(t, dir) 40 } 41 storage, err := NewStorage(dir) 42 if err != nil { 43 close() 44 return nil, nil, err 45 } 46 close = func() { 47 storage.Close() 48 boltdbtest.RemoveTempDir(t, dir) 49 } 50 return storage, close, nil 51 } 52 53 func Test_StorageGetByID(t *testing.T) { 54 storage, close, err := createMockStorage(t) 55 assert.Nil(t, err) 56 defer close() 57 58 data := myTestType{ 59 ID: 1, 60 } 61 err = storage.Store(bucket, &data) 62 assert.Nil(t, err) 63 64 var result myTestType 65 err = storage.GetOneByField(bucket, "ID", data.ID, &result) 66 assert.Nil(t, err) 67 assert.Equal(t, data.ID, result.ID) 68 } 69 70 func Test_StorageGetByID_NotFound(t *testing.T) { 71 storage, close, err := createMockStorage(t) 72 assert.Nil(t, err) 73 defer close() 74 75 bucket := "test" 76 77 var result myTestType 78 err = storage.GetOneByField(bucket, "ID", "data.ID", &result) 79 assert.Equal(t, "not found", err.Error()) 80 } 81 82 func Test_GetLastEntryInBucket(t *testing.T) { 83 storage, close, err := createMockStorage(t) 84 assert.Nil(t, err) 85 defer close() 86 87 data1 := myTestType{ 88 ID: 1, 89 } 90 err = storage.Store(bucket, &data1) 91 assert.Nil(t, err) 92 93 data2 := myTestType{ 94 ID: 2, 95 } 96 err = storage.Store(bucket, &data2) 97 assert.Nil(t, err) 98 99 var res myTestType 100 err = storage.GetLast(bucket, &res) 101 assert.Nil(t, err) 102 assert.Equal(t, data2.ID, res.ID) 103 } 104 105 func Test_StorageGetLast_ErrsOnEmpty(t *testing.T) { 106 storage, close, err := createMockStorage(t) 107 assert.Nil(t, err) 108 defer close() 109 110 bucket := "test" 111 112 var result myTestType 113 err = storage.GetLast(bucket, &result) 114 assert.Equal(t, "not found", err.Error()) 115 }