Skip to content

Commit 0ba1fc8

Browse files
committed
returned objects of reference type should be unchangeable
Signed-off-by: Bruce Ma <[email protected]>
1 parent c46b410 commit 0ba1fc8

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

pkg/cache/cache_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1245,6 +1245,40 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca
12451245
Expect(sii).To(BeNil())
12461246
Expect(apierrors.IsTimeout(err)).To(BeTrue())
12471247
})
1248+
1249+
It("should be able not to change indexer values after indexing cluster-scope objects", func() {
1250+
By("creating the cache")
1251+
informer, err := cache.New(cfg, cache.Options{})
1252+
Expect(err).NotTo(HaveOccurred())
1253+
1254+
By("indexing the Namespace objects with fixed values before starting")
1255+
pod := &corev1.Namespace{}
1256+
indexerValues := []string{"a", "b", "c"}
1257+
fieldName := "fixedValues"
1258+
indexFunc := func(obj client.Object) []string {
1259+
return indexerValues
1260+
}
1261+
Expect(informer.IndexField(context.TODO(), pod, fieldName, indexFunc)).To(Succeed())
1262+
1263+
By("running the cache and waiting for it to sync")
1264+
go func() {
1265+
defer GinkgoRecover()
1266+
Expect(informer.Start(informerCacheCtx)).To(Succeed())
1267+
}()
1268+
Expect(informer.WaitForCacheSync(informerCacheCtx)).NotTo(BeFalse())
1269+
1270+
By("listing Namespaces with fixed indexer")
1271+
listObj := &corev1.NamespaceList{}
1272+
Expect(informer.List(context.Background(), listObj,
1273+
client.MatchingFields{fieldName: "a"})).To(Succeed())
1274+
Expect(listObj.Items).NotTo(BeZero())
1275+
1276+
By("verifying the indexing does not change fixed returned values")
1277+
Expect(indexerValues).Should(HaveLen(3))
1278+
Expect(indexerValues[0]).To(Equal("a"))
1279+
Expect(indexerValues[1]).To(Equal("b"))
1280+
Expect(indexerValues[2]).To(Equal("c"))
1281+
})
12481282
})
12491283
Context("with unstructured objects", func() {
12501284
It("should be able to get informer for the object", func() {

pkg/cache/informer_cache.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -193,8 +193,8 @@ func indexByField(indexer Informer, field string, extractor client.IndexerFunc)
193193
rawVals := extractor(obj)
194194
var vals []string
195195
if ns == "" {
196-
// if we're not doubling the keys for the namespaced case, just re-use what was returned to us
197-
vals = rawVals
196+
// if we're not doubling the keys for the namespaced case, just create a new slice with same length
197+
vals = make([]string, len(rawVals))
198198
} else {
199199
// if we need to add non-namespaced versions too, double the length
200200
vals = make([]string, len(rawVals)*2)

0 commit comments

Comments
 (0)