summaryrefslogtreecommitdiff
path: root/pkg/cache/memcache_test.go
blob: 8fcb47bb99bc94962a4b990f90472a6950b2e76f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package cache

import (
	"testing"
	"time"

	memcache "github.com/patrickmn/go-cache"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"github.com/argoproj-labs/argocd-image-updater/pkg/tag"
)

func Test_MemCache(t *testing.T) {
	imageName := "foo/bar"
	imageTag := "v1.0.0"
	t.Run("Cache hit", func(t *testing.T) {
		mc := NewMemCache()
		newTag := tag.NewImageTag(imageTag, time.Unix(0, 0), "")
		mc.SetTag(imageName, newTag)
		cachedTag, err := mc.GetTag(imageName, imageTag)
		require.NoError(t, err)
		require.NotNil(t, cachedTag)
		assert.Equal(t, imageTag, cachedTag.TagName)
		assert.True(t, mc.HasTag(imageName, imageTag))
		assert.Equal(t, 1, mc.NumEntries())
	})

	t.Run("Cache miss", func(t *testing.T) {
		mc := NewMemCache()
		newTag := tag.NewImageTag(imageTag, time.Unix(0, 0), "")
		mc.SetTag(imageName, newTag)
		assert.Equal(t, 1, mc.NumEntries())
		cachedTag, err := mc.GetTag(imageName, "v1.0.1")
		require.NoError(t, err)
		require.Nil(t, cachedTag)
		assert.False(t, mc.HasTag(imageName, "v1.0.1"))
	})

	t.Run("Cache clear", func(t *testing.T) {
		mc := NewMemCache()
		newTag := tag.NewImageTag(imageTag, time.Unix(0, 0), "")
		mc.SetTag(imageName, newTag)
		cachedTag, err := mc.GetTag(imageName, imageTag)
		require.NoError(t, err)
		require.NotNil(t, cachedTag)
		assert.Equal(t, imageTag, cachedTag.TagName)
		assert.True(t, mc.HasTag(imageName, imageTag))
		assert.Equal(t, 1, mc.NumEntries())
		mc.ClearCache()
		assert.Equal(t, 0, mc.NumEntries())
		cachedTag, err = mc.GetTag(imageName, imageTag)
		require.NoError(t, err)
		require.Nil(t, cachedTag)
	})
	t.Run("Image Cache Key", func(t *testing.T) {
		mc := MemCache{
			cache: memcache.New(0, 0),
		}
		application := "application1"
		key := imageCacheKey(imageName)
		mc.SetImage(imageName, application)
		app, b := mc.cache.Get(key)
		assert.True(t, b)
		assert.Equal(t, application, app)
		assert.Equal(t, 1, mc.NumEntries())
		mc.ClearCache()
		assert.Equal(t, 0, mc.NumEntries())
	})
}