Skip to content

Commit 9fe547c

Browse files
authored
Fix a bug with Limit list opt. (#1618)
Previously, `Limit(n)` only looks at the first `n` objects. This could cause `List` to return less than `n` objects if other `opts` apply further filtering, even though there are more than `n` total number of objects matching the list options.
1 parent a4602c0 commit 9fe547c

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

pkg/cache/cache_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,15 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca
312312
Expect(informerCache.List(context.Background(), listObj, opts)).To(Succeed())
313313
Expect(listObj.Items).Should(HaveLen(3))
314314
})
315+
316+
It("should return a limited result set matching the correct label", func() {
317+
listObj := &corev1.PodList{}
318+
labelOpt := client.MatchingLabels(map[string]string{"common-label": "common"})
319+
limitOpt := client.Limit(1)
320+
By("verifying that only Limit (1) number of objects are retrieved from the cache")
321+
Expect(informerCache.List(context.Background(), listObj, labelOpt, limitOpt)).To(Succeed())
322+
Expect(listObj.Items).Should(HaveLen(1))
323+
})
315324
})
316325

317326
Context("with unstructured objects", func() {

pkg/cache/internal/cache_reader.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -129,10 +129,10 @@ func (c *CacheReader) List(_ context.Context, out client.ObjectList, opts ...cli
129129
limitSet := listOpts.Limit > 0
130130

131131
runtimeObjs := make([]runtime.Object, 0, len(objs))
132-
for i, item := range objs {
132+
for _, item := range objs {
133133
// if the Limit option is set and the number of items
134134
// listed exceeds this limit, then stop reading.
135-
if limitSet && int64(i) >= listOpts.Limit {
135+
if limitSet && int64(len(runtimeObjs)) >= listOpts.Limit {
136136
break
137137
}
138138
obj, isObj := item.(runtime.Object)

0 commit comments

Comments
 (0)