1/*
2Copyright 2019 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package cache
18
19import (
20	"testing"
21)
22
23func TestThreadSafeStoreDeleteRemovesEmptySetsFromIndex(t *testing.T) {
24	testIndexer := "testIndexer"
25
26	indexers := Indexers{
27		testIndexer: func(obj interface{}) (strings []string, e error) {
28			indexes := []string{obj.(string)}
29			return indexes, nil
30		},
31	}
32
33	indices := Indices{}
34	store := NewThreadSafeStore(indexers, indices).(*threadSafeMap)
35
36	testKey := "testKey"
37
38	store.Add(testKey, testKey)
39
40	// Assumption check, there should be a set for the `testKey` with one element in the added index
41	set := store.indices[testIndexer][testKey]
42
43	if len(set) != 1 {
44		t.Errorf("Initial assumption of index backing string set having 1 element failed. Actual elements: %d", len(set))
45		return
46	}
47
48	store.Delete(testKey)
49	set, present := store.indices[testIndexer][testKey]
50
51	if present {
52		t.Errorf("Index backing string set not deleted from index. Set length: %d", len(set))
53	}
54}
55
56func TestThreadSafeStoreAddKeepsNonEmptySetPostDeleteFromIndex(t *testing.T) {
57	testIndexer := "testIndexer"
58	testIndex := "testIndex"
59
60	indexers := Indexers{
61		testIndexer: func(obj interface{}) (strings []string, e error) {
62			indexes := []string{testIndex}
63			return indexes, nil
64		},
65	}
66
67	indices := Indices{}
68	store := NewThreadSafeStore(indexers, indices).(*threadSafeMap)
69
70	store.Add("retain", "retain")
71	store.Add("delete", "delete")
72
73	// Assumption check, there should be a set for the `testIndex` with two elements
74	set := store.indices[testIndexer][testIndex]
75
76	if len(set) != 2 {
77		t.Errorf("Initial assumption of index backing string set having 2 elements failed. Actual elements: %d", len(set))
78		return
79	}
80
81	store.Delete("delete")
82	set, present := store.indices[testIndexer][testIndex]
83
84	if !present {
85		t.Errorf("Index backing string set erroneously deleted from index.")
86		return
87	}
88
89	if len(set) != 1 {
90		t.Errorf("Index backing string set has incorrect length, expect 1. Set length: %d", len(set))
91	}
92}
93