github.com/argoproj/argo-cd/v2@v2.10.9/reposerver/cache/mocks/reposervercache.go (about)

     1  package mocks
     2  
     3  import (
     4  	"testing"
     5  	"time"
     6  
     7  	"github.com/alicebob/miniredis/v2"
     8  	cacheutil "github.com/argoproj/argo-cd/v2/util/cache"
     9  	cacheutilmocks "github.com/argoproj/argo-cd/v2/util/cache/mocks"
    10  	"github.com/redis/go-redis/v9"
    11  	"github.com/stretchr/testify/mock"
    12  )
    13  
    14  type MockCacheType int
    15  
    16  const (
    17  	MockCacheTypeRedis MockCacheType = iota
    18  	MockCacheTypeInMem
    19  )
    20  
    21  type MockRepoCache struct {
    22  	mock.Mock
    23  	RedisClient       *cacheutilmocks.MockCacheClient
    24  	StopRedisCallback func()
    25  }
    26  
    27  type MockCacheOptions struct {
    28  	RepoCacheExpiration     time.Duration
    29  	RevisionCacheExpiration time.Duration
    30  	ReadDelay               time.Duration
    31  	WriteDelay              time.Duration
    32  }
    33  
    34  type CacheCallCounts struct {
    35  	ExternalSets    int
    36  	ExternalGets    int
    37  	ExternalDeletes int
    38  }
    39  
    40  // Checks that the cache was called the expected number of times
    41  func (mockCache *MockRepoCache) AssertCacheCalledTimes(t *testing.T, calls *CacheCallCounts) {
    42  	mockCache.RedisClient.AssertNumberOfCalls(t, "Get", calls.ExternalGets)
    43  	mockCache.RedisClient.AssertNumberOfCalls(t, "Set", calls.ExternalSets)
    44  	mockCache.RedisClient.AssertNumberOfCalls(t, "Delete", calls.ExternalDeletes)
    45  }
    46  
    47  func (mockCache *MockRepoCache) ConfigureDefaultCallbacks() {
    48  	mockCache.RedisClient.On("Get", mock.Anything, mock.Anything).Return(nil)
    49  	mockCache.RedisClient.On("Set", mock.Anything).Return(nil)
    50  	mockCache.RedisClient.On("Delete", mock.Anything).Return(nil)
    51  }
    52  
    53  func NewInMemoryRedis() (*redis.Client, func()) {
    54  	cacheutil.NewInMemoryCache(5 * time.Second)
    55  	mr, err := miniredis.Run()
    56  	if err != nil {
    57  		panic(err)
    58  	}
    59  	return redis.NewClient(&redis.Options{Addr: mr.Addr()}), mr.Close
    60  }
    61  
    62  func NewMockRepoCache(cacheOpts *MockCacheOptions) *MockRepoCache {
    63  	redisClient, stopRedis := NewInMemoryRedis()
    64  	redisCacheClient := &cacheutilmocks.MockCacheClient{
    65  		ReadDelay:  cacheOpts.ReadDelay,
    66  		WriteDelay: cacheOpts.WriteDelay,
    67  		BaseCache:  cacheutil.NewRedisCache(redisClient, cacheOpts.RepoCacheExpiration, cacheutil.RedisCompressionNone)}
    68  	newMockCache := &MockRepoCache{RedisClient: redisCacheClient, StopRedisCallback: stopRedis}
    69  	newMockCache.ConfigureDefaultCallbacks()
    70  	return newMockCache
    71  }