Skip to content

Commit

Permalink
Merge pull request #1851 from mars1024/dev/bruce
Browse files Browse the repository at this point in the history
馃悰 returned objects of reference type should be unchangeable
  • Loading branch information
k8s-ci-robot committed Apr 1, 2022
2 parents b921952 + 0ba1fc8 commit 05aa087
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
34 changes: 34 additions & 0 deletions pkg/cache/cache_test.go
Expand Up @@ -1245,6 +1245,40 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca
Expect(sii).To(BeNil())
Expect(apierrors.IsTimeout(err)).To(BeTrue())
})

It("should be able not to change indexer values after indexing cluster-scope objects", func() {
By("creating the cache")
informer, err := cache.New(cfg, cache.Options{})
Expect(err).NotTo(HaveOccurred())

By("indexing the Namespace objects with fixed values before starting")
pod := &corev1.Namespace{}
indexerValues := []string{"a", "b", "c"}
fieldName := "fixedValues"
indexFunc := func(obj client.Object) []string {
return indexerValues
}
Expect(informer.IndexField(context.TODO(), pod, fieldName, indexFunc)).To(Succeed())

By("running the cache and waiting for it to sync")
go func() {
defer GinkgoRecover()
Expect(informer.Start(informerCacheCtx)).To(Succeed())
}()
Expect(informer.WaitForCacheSync(informerCacheCtx)).NotTo(BeFalse())

By("listing Namespaces with fixed indexer")
listObj := &corev1.NamespaceList{}
Expect(informer.List(context.Background(), listObj,
client.MatchingFields{fieldName: "a"})).To(Succeed())
Expect(listObj.Items).NotTo(BeZero())

By("verifying the indexing does not change fixed returned values")
Expect(indexerValues).Should(HaveLen(3))
Expect(indexerValues[0]).To(Equal("a"))
Expect(indexerValues[1]).To(Equal("b"))
Expect(indexerValues[2]).To(Equal("c"))
})
})
Context("with unstructured objects", func() {
It("should be able to get informer for the object", func() {
Expand Down
4 changes: 2 additions & 2 deletions pkg/cache/informer_cache.go
Expand Up @@ -193,8 +193,8 @@ func indexByField(indexer Informer, field string, extractor client.IndexerFunc)
rawVals := extractor(obj)
var vals []string
if ns == "" {
// if we're not doubling the keys for the namespaced case, just re-use what was returned to us
vals = rawVals
// if we're not doubling the keys for the namespaced case, just create a new slice with same length
vals = make([]string, len(rawVals))
} else {
// if we need to add non-namespaced versions too, double the length
vals = make([]string, len(rawVals)*2)
Expand Down

0 comments on commit 05aa087

Please sign in to comment.