github.com/cilium/cilium@v1.16.2/pkg/bgpv1/manager/store/resource_store_mock.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright Authors of Cilium
     3  
     4  package store
     5  
     6  import (
     7  	"golang.org/x/exp/maps"
     8  	"k8s.io/apimachinery/pkg/runtime"
     9  
    10  	"github.com/cilium/cilium/pkg/k8s/resource"
    11  	"github.com/cilium/cilium/pkg/lock"
    12  )
    13  
    14  var _ BGPCPResourceStore[*runtime.Unknown] = (*mockBGPCPResourceStore[*runtime.Unknown])(nil)
    15  
    16  type mockBGPCPResourceStore[T runtime.Object] struct {
    17  	objMu   lock.Mutex
    18  	objects map[resource.Key]T
    19  }
    20  
    21  func NewMockBGPCPResourceStore[T runtime.Object]() *mockBGPCPResourceStore[T] {
    22  	return &mockBGPCPResourceStore[T]{
    23  		objects: make(map[resource.Key]T),
    24  	}
    25  }
    26  
    27  func (mds *mockBGPCPResourceStore[T]) List() ([]T, error) {
    28  	mds.objMu.Lock()
    29  	defer mds.objMu.Unlock()
    30  	return maps.Values(mds.objects), nil
    31  }
    32  
    33  func (mds *mockBGPCPResourceStore[T]) GetByKey(key resource.Key) (item T, exists bool, err error) {
    34  	mds.objMu.Lock()
    35  	defer mds.objMu.Unlock()
    36  
    37  	item, exists = mds.objects[key]
    38  
    39  	return item, exists, nil
    40  }
    41  
    42  func (mds *mockBGPCPResourceStore[T]) Upsert(obj T) {
    43  	mds.objMu.Lock()
    44  	defer mds.objMu.Unlock()
    45  
    46  	key := resource.NewKey(obj)
    47  	mds.objects[key] = obj
    48  }
    49  
    50  func (mds *mockBGPCPResourceStore[T]) Delete(key resource.Key) {
    51  	mds.objMu.Lock()
    52  	defer mds.objMu.Unlock()
    53  
    54  	delete(mds.objects, key)
    55  }
    56  
    57  func InitMockStore[T runtime.Object](objects []T) BGPCPResourceStore[T] {
    58  	store := NewMockBGPCPResourceStore[T]()
    59  	for _, obj := range objects {
    60  		store.Upsert(obj)
    61  	}
    62  	return store
    63  }