@@ -84,6 +84,8 @@ type fakeClient struct {
84
84
// indexes maps each GroupVersionKind (GVK) to the indexes registered for that GVK.
85
85
// The inner map maps from index name to IndexerFunc.
86
86
indexes map [schema.GroupVersionKind ]map [string ]client.IndexerFunc
87
+ // indexesLock must be held when accessing indexes.
88
+ indexesLock sync.RWMutex
87
89
}
88
90
89
91
var _ client.WithWatch = & fakeClient {}
@@ -648,10 +650,11 @@ func (c *fakeClient) filterList(list []runtime.Object, gvk schema.GroupVersionKi
648
650
func (c * fakeClient ) filterWithFields (list []runtime.Object , gvk schema.GroupVersionKind , fs fields.Selector ) ([]runtime.Object , error ) {
649
651
requiresExact := selector .RequiresExactMatch (fs )
650
652
if ! requiresExact {
651
- return nil , fmt .Errorf ("field selector %s is not in one of the two supported forms \" key==val\" or \" key=val\" " ,
652
- fs )
653
+ return nil , fmt .Errorf (`field selector %s is not in one of the two supported forms "key==val" or "key=val"` , fs )
653
654
}
654
655
656
+ c .indexesLock .RLock ()
657
+ defer c .indexesLock .RUnlock ()
655
658
// Field selection is mimicked via indexes, so there's no sane answer this function can give
656
659
// if there are no indexes registered for the GroupVersionKind of the objects in the list.
657
660
indexes := c .indexes [gvk ]
@@ -1528,3 +1531,37 @@ func applyScale(obj client.Object, scale *autoscalingv1.Scale) error {
1528
1531
}
1529
1532
return nil
1530
1533
}
1534
+
1535
+ // AddIndex adds an index to a fake client. It will panic if used with a client that is not a fake client.
1536
+ // It will error if there is already an index for given object with the same name as field.
1537
+ //
1538
+ // It can be used to test code that adds indexes to the cache at runtime.
1539
+ func AddIndex (c client.Client , obj runtime.Object , field string , extractValue client.IndexerFunc ) error {
1540
+ fakeClient , isFakeClient := c .(* fakeClient )
1541
+ if ! isFakeClient {
1542
+ panic ("AddIndex can only be used with a fake client" )
1543
+ }
1544
+ fakeClient .indexesLock .Lock ()
1545
+ defer fakeClient .indexesLock .Unlock ()
1546
+
1547
+ if fakeClient .indexes == nil {
1548
+ fakeClient .indexes = make (map [schema.GroupVersionKind ]map [string ]client.IndexerFunc , 1 )
1549
+ }
1550
+
1551
+ gvk , err := apiutil .GVKForObject (obj , fakeClient .scheme )
1552
+ if err != nil {
1553
+ return fmt .Errorf ("failed to get gvk for %T: %w" , obj , err )
1554
+ }
1555
+
1556
+ if fakeClient .indexes [gvk ] == nil {
1557
+ fakeClient .indexes [gvk ] = make (map [string ]client.IndexerFunc , 1 )
1558
+ }
1559
+
1560
+ if fakeClient.indexes [gvk ][field ] != nil {
1561
+ return fmt .Errorf ("index %s already exists" , field )
1562
+ }
1563
+
1564
+ fakeClient.indexes [gvk ][field ] = extractValue
1565
+
1566
+ return nil
1567
+ }
0 commit comments