github.com/thanos-io/thanos@v0.32.5/internal/cortex/chunk/cache/redis_cache_test.go (about)

     1  // Copyright (c) The Cortex Authors.
     2  // Licensed under the Apache License 2.0.
     3  
     4  package cache
     5  
     6  import (
     7  	"context"
     8  	"testing"
     9  	"time"
    10  
    11  	"github.com/alicebob/miniredis/v2"
    12  	"github.com/go-kit/log"
    13  	"github.com/redis/rueidis"
    14  	"github.com/stretchr/testify/require"
    15  )
    16  
    17  func TestRedisCache(t *testing.T) {
    18  	c, err := mockRedisCache()
    19  	require.Nil(t, err)
    20  	defer c.redis.Close()
    21  
    22  	keys := []string{"key1", "key2", "key3"}
    23  	bufs := [][]byte{[]byte("data1"), []byte("data2"), []byte("data3")}
    24  	miss := []string{"miss1", "miss2"}
    25  
    26  	// ensure input correctness
    27  	nHit := len(keys)
    28  	require.Len(t, bufs, nHit)
    29  
    30  	nMiss := len(miss)
    31  
    32  	ctx := context.Background()
    33  
    34  	c.Store(ctx, keys, bufs)
    35  
    36  	// test hits
    37  	found, data, missed := c.Fetch(ctx, keys)
    38  
    39  	require.Len(t, found, nHit)
    40  	require.Len(t, missed, 0)
    41  	for i := 0; i < nHit; i++ {
    42  		require.Equal(t, keys[i], found[i])
    43  		require.Equal(t, bufs[i], data[i])
    44  	}
    45  
    46  	// test misses
    47  	found, _, missed = c.Fetch(ctx, miss)
    48  
    49  	require.Len(t, found, 0)
    50  	require.Len(t, missed, nMiss)
    51  	for i := 0; i < nMiss; i++ {
    52  		require.Equal(t, miss[i], missed[i])
    53  	}
    54  }
    55  
    56  func mockRedisCache() (*RedisCache, error) {
    57  	redisServer, err := miniredis.Run()
    58  	if err != nil {
    59  		return nil, err
    60  	}
    61  	cl, err := rueidis.NewClient(rueidis.ClientOption{
    62  		InitAddress:  []string{redisServer.Addr()},
    63  		DisableCache: true,
    64  	})
    65  	if err != nil {
    66  		return nil, err
    67  	}
    68  	redisClient := &RedisClient{
    69  		expiration: time.Minute,
    70  		timeout:    100 * time.Millisecond,
    71  		rdb:        cl,
    72  	}
    73  	return NewRedisCache("mock", redisClient, nil, log.NewNopLogger()), nil
    74  }