Skip to content

Commit

Permalink
Add DeleteCollection Reactor
Browse files Browse the repository at this point in the history
The generated fake client set code doesn't implement DeleteCollection
so add a Reactor to do it.

Signed-off-by: Tom Pantelis <[email protected]>
  • Loading branch information
tpantelis committed Sep 11, 2020
1 parent 5a76d31 commit 66d9123
Showing 1 changed file with 85 additions and 0 deletions.
85 changes: 85 additions & 0 deletions pkg/fake/delete_colection_reactor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package fake

import (
"fmt"

. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/pkg/errors"
"github.com/submariner-io/admiral/pkg/syncer/test"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/testing"
)

type DeleteCollectionReactor struct {
kind string
reactors []testing.Reactor
}

func AddDeleteCollectionReactor(f *testing.Fake, kind string) {
r := &DeleteCollectionReactor{kind: kind, reactors: f.ReactionChain[0:]}
chain := []testing.Reactor{&testing.SimpleReactor{Verb: "delete-collection", Resource: "*", Reaction: r.react}}
f.ReactionChain = append(chain, f.ReactionChain...)
}

func (r *DeleteCollectionReactor) react(action testing.Action) (bool, runtime.Object, error) {
switch dc := action.(type) {
case testing.DeleteCollectionActionImpl:
defer GinkgoRecover()

gvk := schema.GroupVersionKind{
Group: action.GetResource().Group,
Version: action.GetResource().Version,
Kind: r.kind,
}

obj, err := r.invoke(testing.NewListAction(action.GetResource(), gvk, action.GetNamespace(), metav1.ListOptions{
LabelSelector: dc.ListRestrictions.Labels.String(),
FieldSelector: dc.ListRestrictions.Fields.String(),
}))

if err != nil {
return true, nil, err
}

raw := test.ToUnstructured(obj)
items, found, err := unstructured.NestedSlice(raw.Object, "items")
Expect(err).To(Succeed())
Expect(found).To(BeTrue())

for _, m := range items {
item := unstructured.Unstructured{Object: m.(map[string]interface{})}
if dc.ListRestrictions.Labels.Matches(labels.Set(item.GetLabels())) {
_, err = r.invoke(testing.NewDeleteAction(action.GetResource(), action.GetNamespace(), item.GetName()))
if err != nil {
return true, nil, err
}
}
}

return true, nil, nil
default:
return false, nil, fmt.Errorf("invalid action: %#v", action)
}
}

func (r *DeleteCollectionReactor) invoke(action testing.Action) (runtime.Object, error) {
for _, reactor := range r.reactors {
if !reactor.Handles(action) {
continue
}

handled, ret, err := reactor.React(action)
if !handled {
continue
}

return ret, err
}

return nil, errors.New("action not handled")
}

0 comments on commit 66d9123

Please sign in to comment.