ram state for testing
This commit is contained in:
parent
3d0885e419
commit
378d7a5802
2 changed files with 86 additions and 0 deletions
41
state.go
41
state.go
|
@ -2,6 +2,7 @@ package state
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
@ -11,6 +12,7 @@ type StateStore interface {
|
|||
GetState(key string, object any) error
|
||||
}
|
||||
|
||||
// Locale Filesystem
|
||||
func NewLocaleFilesystem(path string) (StateStore, error) {
|
||||
l := localeFilesystem{}
|
||||
l.path = path
|
||||
|
@ -56,3 +58,42 @@ func (s localeFilesystem) StoreState(key string, object any) error {
|
|||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ROM
|
||||
func NewRamFilesystem() (StateStore, error) {
|
||||
l := ramFilesystem{}
|
||||
l.data = make(map[string][]byte)
|
||||
|
||||
return &l, nil
|
||||
}
|
||||
|
||||
type ramFilesystem struct {
|
||||
data map[string][]byte
|
||||
}
|
||||
|
||||
func (s *ramFilesystem) GetState(key string, object any) error {
|
||||
data, ok := s.data[key]
|
||||
|
||||
if !ok {
|
||||
return errors.New("cant get state from ram")
|
||||
}
|
||||
|
||||
err := json.Unmarshal(data, object)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("%e: %v", ErrLocaleFilesystemCantReadState, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ramFilesystem) StoreState(key string, object any) error {
|
||||
data, err := json.Marshal(object)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%e: %v", ErrLocaleFilesystemCantStoreState, err)
|
||||
}
|
||||
|
||||
s.data[key] = data
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
@ -69,3 +69,48 @@ func TestStoreStateFromHDD(t *testing.T) {
|
|||
|
||||
assert.Equal(t, result, data, "should get same data from hdd")
|
||||
}
|
||||
|
||||
func TestRamState(t *testing.T) {
|
||||
store, err := NewRamFilesystem()
|
||||
assert.Nil(t, err, "should be able to create store without error")
|
||||
|
||||
data := struct {
|
||||
Name string
|
||||
Test string `json:"-"`
|
||||
Age int
|
||||
something string
|
||||
}{
|
||||
Name: "Max",
|
||||
Test: "foo",
|
||||
Age: 1337,
|
||||
something: "nothing",
|
||||
}
|
||||
|
||||
dataFromStore := struct {
|
||||
Name string
|
||||
Test string `json:"-"`
|
||||
Age int
|
||||
something string
|
||||
}{}
|
||||
|
||||
result := struct {
|
||||
Name string
|
||||
Test string `json:"-"`
|
||||
Age int
|
||||
something string
|
||||
}{
|
||||
Name: "Max",
|
||||
Test: "",
|
||||
Age: 1337,
|
||||
something: "",
|
||||
}
|
||||
|
||||
err = store.StoreState("something", data)
|
||||
assert.Nil(t, err, "should be save stater without error")
|
||||
|
||||
err = store.GetState("something", &dataFromStore)
|
||||
assert.Nil(t, err, "should be able to get data from stroe without error")
|
||||
|
||||
assert.Equal(t, result, dataFromStore, "should get correct data from store")
|
||||
|
||||
}
|
||||
|
|
Reference in a new issue