k8s.io/client-go@v0.31.1/tools/cache/mutation_detector_test.go (about)

     1  /*
     2  Copyright 2016 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package cache
    18  
    19  import (
    20  	"testing"
    21  	"time"
    22  
    23  	"k8s.io/api/core/v1"
    24  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    25  	"k8s.io/apimachinery/pkg/runtime"
    26  	"k8s.io/apimachinery/pkg/util/wait"
    27  	"k8s.io/apimachinery/pkg/watch"
    28  )
    29  
    30  func TestMutationDetector(t *testing.T) {
    31  	fakeWatch := watch.NewFake()
    32  	lw := &testLW{
    33  		WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
    34  			return fakeWatch, nil
    35  		},
    36  		ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
    37  			return &v1.PodList{}, nil
    38  		},
    39  	}
    40  	pod := &v1.Pod{
    41  		ObjectMeta: metav1.ObjectMeta{
    42  			Name:   "anything",
    43  			Labels: map[string]string{"check": "foo"},
    44  		},
    45  	}
    46  	stopCh := make(chan struct{})
    47  	defer close(stopCh)
    48  	mutationFound := make(chan bool)
    49  
    50  	informer := NewSharedInformer(lw, &v1.Pod{}, 1*time.Second).(*sharedIndexInformer)
    51  	detector := &defaultCacheMutationDetector{
    52  		name:           "name",
    53  		period:         1 * time.Second,
    54  		retainDuration: 2 * time.Minute,
    55  		failureFunc: func(message string) {
    56  			mutationFound <- true
    57  		},
    58  	}
    59  	informer.cacheMutationDetector = detector
    60  	go informer.Run(stopCh)
    61  
    62  	fakeWatch.Add(pod)
    63  
    64  	wait.PollImmediate(100*time.Millisecond, wait.ForeverTestTimeout, func() (bool, error) {
    65  		detector.addedObjsLock.Lock()
    66  		defer detector.addedObjsLock.Unlock()
    67  		return len(detector.addedObjs) > 0, nil
    68  	})
    69  
    70  	detector.compareObjectsLock.Lock()
    71  	pod.Labels["change"] = "true"
    72  	detector.compareObjectsLock.Unlock()
    73  
    74  	select {
    75  	case <-mutationFound:
    76  	case <-time.After(wait.ForeverTestTimeout):
    77  		t.Fatalf("failed waiting for mutating detector")
    78  	}
    79  
    80  }