github.com/keybase/client/go@v0.0.0-20240309051027-028f7c731f8b/stellar/time_cache_test.go (about)

     1  package stellar
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/keybase/client/go/libkb"
     9  	"github.com/stretchr/testify/require"
    10  )
    11  
    12  func TestTimeCache(t *testing.T) {
    13  	tc := libkb.SetupTest(t, "loaderclean", 1)
    14  	defer tc.Cleanup()
    15  
    16  	var a int
    17  	c := NewTimeCache("xyz", 50, time.Minute)
    18  	c.Put(tc.MetaContext(), "k", 1)
    19  	ok := c.Get(tc.MetaContext(), "k", &a)
    20  	require.True(t, ok)
    21  	require.Equal(t, 1, a)
    22  
    23  	fill2 := func() (interface{}, error) {
    24  		return 2, nil
    25  	}
    26  	fillErr := func() (interface{}, error) {
    27  		return 3, fmt.Errorf("eek")
    28  	}
    29  	err := c.GetWithFill(tc.MetaContext(), "l", &a, fill2)
    30  	require.NoError(t, err)
    31  	require.Equal(t, 2, a)
    32  	err = c.GetWithFill(tc.MetaContext(), "l", &a, fillErr)
    33  	require.NoError(t, err)
    34  	require.Equal(t, 2, a)
    35  
    36  	err = c.GetWithFill(tc.MetaContext(), "m", &a, fillErr)
    37  	require.Error(t, err)
    38  	require.Equal(t, 2, a)
    39  }
    40  
    41  func TestTimeCacheWrongType(t *testing.T) {
    42  	tc := libkb.SetupTest(t, "loaderclean", 1)
    43  	defer tc.Cleanup()
    44  
    45  	var a int
    46  	c := NewTimeCache("xyz", 50, time.Minute)
    47  	c.Put(tc.MetaContext(), "k", "b")
    48  	t.Logf("+ t1")
    49  	ok := c.Get(tc.MetaContext(), "k", &a)
    50  	require.False(t, ok)
    51  
    52  	t.Logf("+ t2")
    53  	c.Put(tc.MetaContext(), "k", "b")
    54  	ok = c.Get(tc.MetaContext(), "k", a)
    55  	require.False(t, ok)
    56  
    57  	t.Logf("+ t3")
    58  	c.Put(tc.MetaContext(), "k", "b")
    59  	ok = c.Get(tc.MetaContext(), "k", "z")
    60  	require.False(t, ok)
    61  }
    62  
    63  func TestTimeCacheWrongTypeStructs(t *testing.T) {
    64  	tc := libkb.SetupTest(t, "loaderclean", 1)
    65  	defer tc.Cleanup()
    66  
    67  	type T1 struct{}
    68  	type T2 struct{ y string }
    69  
    70  	var a T1
    71  	c := NewTimeCache("xyz", 50, time.Minute)
    72  	c.Put(tc.MetaContext(), "k", T2{y: "b"})
    73  	ok := c.Get(tc.MetaContext(), "k", &a)
    74  	require.False(t, ok)
    75  }