github.com/TrueBlocks/trueblocks-core/src/apps/chifra@v0.0.0-20241022031540-b362680128f7/pkg/cache/store_test.go (about)

     1  package cache
     2  
     3  import (
     4  	"io"
     5  	"testing"
     6  )
     7  
     8  // We have to create a struct that implements Cache(un)Marshaler and Locator
     9  // interfaces, i.e. is cacheable.
    10  type testStoreData struct {
    11  	Id    string
    12  	Value string
    13  }
    14  
    15  func (t *testStoreData) MarshalCache(writer io.Writer) error {
    16  	if err := WriteValue(writer, t.Value); err != nil {
    17  		return err
    18  	}
    19  	return nil
    20  }
    21  
    22  func (t *testStoreData) UnmarshalCache(version uint64, reader io.Reader) error {
    23  	if err := ReadValue(reader, &t.Value, version); err != nil {
    24  		return err
    25  	}
    26  	return nil
    27  }
    28  
    29  func (t *testStoreData) CacheLocations() (string, string, string) {
    30  	return "test", t.Id, "bin"
    31  }
    32  
    33  func TestStoreWrite(t *testing.T) {
    34  	value := &testStoreData{
    35  		Id:    "1",
    36  		Value: "trueblocks",
    37  	}
    38  	opts := &StoreOptions{
    39  		Location: MemoryCache,
    40  	}
    41  	cacheStore, err := NewStore(opts)
    42  	if err != nil {
    43  		panic(err)
    44  	}
    45  
    46  	// Write
    47  	if err := cacheStore.Write(value, nil); err != nil {
    48  		t.Fatal(err)
    49  	}
    50  
    51  	// Retrieve the same value
    52  	result := &testStoreData{
    53  		Id: "1",
    54  	}
    55  	if err := cacheStore.Read(result, nil); err != nil {
    56  		t.Fatal(err)
    57  	}
    58  	if result.Value != value.Value {
    59  		t.Fatal("wrong value:", result.Value)
    60  	}
    61  }