github.com/GuanceCloud/cliutils@v1.1.21/pipeline/ptinput/plcache/cache_test.go (about)

     1  package plcache
     2  
     3  import (
     4  	"testing"
     5  	"time"
     6  
     7  	"github.com/stretchr/testify/assert"
     8  )
     9  
    10  func TestNewCache(t *testing.T) {
    11  	_, err := NewCache(time.Second, 10)
    12  	assert.Nil(t, err)
    13  }
    14  
    15  func TestCache_SetAndGet(t *testing.T) {
    16  	cache, _ := NewCache(time.Second, 10)
    17  	cache.Set("key1", "value1", 10*time.Second)
    18  	cache.Set("key2", "value2", 10*time.Second)
    19  	cache.Set("key3", "value3", 10*time.Second)
    20  	cache.Set("key4", "value4", 10*time.Second)
    21  
    22  	time.Sleep(2 * time.Second)
    23  
    24  	v1, exists1, _ := cache.Get("key1")
    25  	v2, exists2, _ := cache.Get("key2")
    26  	v3, exists3, _ := cache.Get("key3")
    27  	v4, exists4, _ := cache.Get("key4")
    28  
    29  	t.Logf(v1.(string), v2.(string), v3.(string), v4.(string))
    30  	assert.True(t, exists1 && exists2 && exists3 && exists4)
    31  }
    32  
    33  func TestCache_RemoveExpiredCache(t *testing.T) {
    34  	cache, _ := NewCache(time.Second, 10)
    35  	cache.Set("key", "value", 5*time.Second)
    36  
    37  	time.Sleep(2 * time.Second)
    38  	_, exist1, _ := cache.Get("key")
    39  	time.Sleep(10 * time.Second)
    40  	_, exist2, _ := cache.Get("key")
    41  
    42  	assert.True(t, exist1 == true && exist2 == false)
    43  }
    44  
    45  func TestCache_Stop(t *testing.T) {
    46  	cache, _ := NewCache(time.Second, 10)
    47  	cache.Stop()
    48  
    49  	err1 := cache.Set("key", "value", 10*time.Second)
    50  	_, _, err2 := cache.Get("key")
    51  
    52  	assert.NotNil(t, err1, "err1 is nil")
    53  	assert.NotNil(t, err2, "err2 is nil")
    54  }