github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/core/storage/boltdb/boltdbtest/db.go (about)

     1  /*
     2   * Copyright (C) 2018 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 boltdbtest contains the utitilies needed for boltdb testing
    19  package boltdbtest
    20  
    21  import (
    22  	"os"
    23  	"testing"
    24  
    25  	"github.com/asdine/storm/v3"
    26  	"github.com/stretchr/testify/assert"
    27  )
    28  
    29  // CreateDB creates a new boltdb instance with a temp file and returns the underlying file and database
    30  func CreateDB(t *testing.T) (string, *storm.DB) {
    31  	file := CreateTempFile(t)
    32  	db, err := storm.Open(file)
    33  	assert.Nil(t, err)
    34  
    35  	return file, db
    36  }
    37  
    38  // CleanupDB removes the provided file after stopping the given db
    39  func CleanupDB(t *testing.T, fileName string, db *storm.DB) {
    40  	err := db.Close()
    41  	if err != nil {
    42  		t.Logf("Could not close db %v\n", err)
    43  	}
    44  	CleanupTempFile(t, fileName)
    45  }
    46  
    47  // CreateTempFile creates a temporary file and returns its path
    48  func CreateTempFile(t *testing.T) string {
    49  	file, err := os.CreateTemp("", "")
    50  	assert.Nil(t, err)
    51  	return file.Name()
    52  }
    53  
    54  // CleanupTempFile removes the given temp file
    55  func CleanupTempFile(t *testing.T, fileName string) {
    56  	err := os.Remove(fileName)
    57  	if err != nil {
    58  		t.Logf("Could not remove temp file: %v. Err: %v\n", fileName, err)
    59  	}
    60  }
    61  
    62  // CreateTempDir creates a temporary directory
    63  func CreateTempDir(t *testing.T) string {
    64  	dir, err := os.MkdirTemp("", "")
    65  	assert.Nil(t, err)
    66  	return dir
    67  }
    68  
    69  // RemoveTempDir removes a temporary directory
    70  func RemoveTempDir(t *testing.T, dir string) {
    71  	err := os.RemoveAll(dir)
    72  	if err != nil {
    73  		t.Logf("Could not remove temp dir: %v. Err: %v\n", dir, err)
    74  	}
    75  }