|
| 1 | +package client_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "time" |
| 7 | + |
| 8 | + . "github.com/onsi/ginkgo/v2" |
| 9 | + . "github.com/onsi/gomega" |
| 10 | + |
| 11 | + "sigs.k8s.io/controller-runtime/pkg/envtest" |
| 12 | + |
| 13 | + apierrors "k8s.io/apimachinery/pkg/api/errors" |
| 14 | + "k8s.io/apimachinery/pkg/api/meta" |
| 15 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 16 | + "k8s.io/apimachinery/pkg/watch" |
| 17 | + clientfeatures "k8s.io/client-go/features" |
| 18 | + "k8s.io/client-go/kubernetes" |
| 19 | + "k8s.io/utils/ptr" |
| 20 | +) |
| 21 | + |
| 22 | +var _ = Describe("WatchList", func() { |
| 23 | + It("should work against the kube-apiserver", func() { |
| 24 | + |
| 25 | + Expect(clientfeatures.FeatureGates().Enabled(clientfeatures.WatchListClient)).To(BeTrue()) |
| 26 | + |
| 27 | + testenv = &envtest.Environment{} |
| 28 | + cfg, err := testenv.Start() |
| 29 | + Expect(err).NotTo(HaveOccurred()) |
| 30 | + clientset, err = kubernetes.NewForConfig(cfg) |
| 31 | + Expect(err).NotTo(HaveOccurred()) |
| 32 | + |
| 33 | + ctx := context.Background() |
| 34 | + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) |
| 35 | + defer cancel() |
| 36 | + opts := metav1.ListOptions{} |
| 37 | + opts.AllowWatchBookmarks = true |
| 38 | + opts.SendInitialEvents = ptr.To(true) |
| 39 | + opts.ResourceVersionMatch = metav1.ResourceVersionMatchNotOlderThan |
| 40 | + w, err := clientset.CoreV1().Secrets("kube-system").Watch(ctx, opts) |
| 41 | + Expect(err).NotTo(HaveOccurred()) |
| 42 | + defer w.Stop() |
| 43 | + |
| 44 | + receivedWatchListStreamFromTheServer := false |
| 45 | + func() { |
| 46 | + for { |
| 47 | + select { |
| 48 | + case <-ctx.Done(): |
| 49 | + return |
| 50 | + case event, ok := <-w.ResultChan(): |
| 51 | + if !ok { |
| 52 | + panic("unexpected watch close") |
| 53 | + |
| 54 | + } |
| 55 | + if event.Type == watch.Error { |
| 56 | + panic(fmt.Sprintf("unexpected watch event: %v", apierrors.FromObject(event.Object))) |
| 57 | + } |
| 58 | + meta, err := meta.Accessor(event.Object) |
| 59 | + Expect(err).NotTo(HaveOccurred()) |
| 60 | + |
| 61 | + switch event.Type { |
| 62 | + case watch.Bookmark: |
| 63 | + if meta.GetAnnotations()[metav1.InitialEventsAnnotationKey] != "true" { |
| 64 | + continue |
| 65 | + } |
| 66 | + if len(meta.GetAnnotations()["kubernetes.io/initial-events-embedded-list"]) == 0 { |
| 67 | + continue |
| 68 | + } |
| 69 | + receivedWatchListStreamFromTheServer = true |
| 70 | + return |
| 71 | + case watch.Added, watch.Modified, watch.Deleted, watch.Error: |
| 72 | + default: |
| 73 | + panic(fmt.Sprintf("unexpected watch event: %v", event.Object)) |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | + }() |
| 78 | + |
| 79 | + Expect(receivedWatchListStreamFromTheServer).To(BeTrue()) |
| 80 | + }) |
| 81 | +}) |
0 commit comments