From 96a6129d8a39ff455a86af5610cb0e6a4f305e87 Mon Sep 17 00:00:00 2001 From: Dennis Buduev Date: Fri, 4 Jun 2021 13:33:18 +1200 Subject: [PATCH] feat(bolt): implement boltdb test store EE-872 --- api/bolt/bolttest/datastore.go | 73 ++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 api/bolt/bolttest/datastore.go diff --git a/api/bolt/bolttest/datastore.go b/api/bolt/bolttest/datastore.go new file mode 100644 index 000000000..ac0887b2c --- /dev/null +++ b/api/bolt/bolttest/datastore.go @@ -0,0 +1,73 @@ +package bolttest + +import ( + "io/ioutil" + "log" + "os" + + "github.com/pkg/errors" + "github.com/portainer/portainer/api/bolt" + "github.com/portainer/portainer/api/filesystem" +) + +var errTempDir = errors.New("can't create a temp dir") + +func MustNewTestStore(init bool) (*bolt.Store, func()) { + store, teardown, err := NewTestStore(init) + if err != nil { + if !errors.Is(err, errTempDir) { + teardown() + } + log.Fatal(err) + } + + return store, teardown +} + +func NewTestStore(init bool) (*bolt.Store, func(), error) { + // Creates unique temp directory in a concurrency friendly manner. + dataStorePath, err := ioutil.TempDir("", "boltdb") + if err != nil { + return nil, nil, errors.Wrap(errTempDir, err.Error()) + } + + fileService, err := filesystem.NewService(dataStorePath, "") + if err != nil { + return nil, nil, err + } + + store, err := bolt.NewStore(dataStorePath, fileService) + if err != nil { + return nil, nil, err + } + + err = store.Open() + if err != nil { + return nil, nil, err + } + + if init { + err = store.Init() + if err != nil { + return nil, nil, err + } + } + + teardown := func() { + teardown(store, dataStorePath) + } + + return store, teardown, nil +} + +func teardown(store *bolt.Store, dataStorePath string) { + err := store.Close() + if err != nil { + log.Fatalln(err) + } + + err = os.RemoveAll(dataStorePath) + if err != nil { + log.Fatalln(err) + } +}