Skip to content

Commit a48424a

Browse files
committed
✨ Add ContainsFinalizer helper to the controllerutil
1 parent a457e27 commit a48424a

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

pkg/controller/controllerutil/controllerutil.go

+21
Original file line numberDiff line numberDiff line change
@@ -280,3 +280,24 @@ func RemoveFinalizerWithError(o runtime.Object, finalizer string) error {
280280
RemoveFinalizer(m, finalizer)
281281
return nil
282282
}
283+
284+
// ContainsFinalizer checks a metav1 object that the provided finalizer is present.
285+
func ContainsFinalizer(o metav1.Object, finalizer string) bool {
286+
f := o.GetFinalizers()
287+
for _, e := range f {
288+
if e == finalizer {
289+
return true
290+
}
291+
}
292+
return false
293+
}
294+
295+
// ContainsFinalizerWithError checks a metav1 object that the provided finalizer is present.
296+
// It returns an error if the provided object cannot provide an accessor.
297+
func ContainsFinalizerWithError(o runtime.Object, finalizer string) (bool, error) {
298+
m, err := meta.Accessor(o)
299+
if err != nil {
300+
return false, err
301+
}
302+
return ContainsFinalizer(m, finalizer), nil
303+
}

pkg/controller/controllerutil/controllerutil_test.go

+19
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,13 @@ var _ = Describe("Controllerutil", func() {
422422
})
423423
})
424424

425+
Describe("ContainsFinalizerWithError", func() {
426+
It("should return an error if object can't provide accessor", func() {
427+
_, err := controllerutil.ContainsFinalizerWithError(obj, testFinalizer)
428+
Expect(err).To(HaveOccurred())
429+
})
430+
})
431+
425432
Describe("AddFinalizer", func() {
426433
deploy = &appsv1.Deployment{
427434
ObjectMeta: metav1.ObjectMeta{
@@ -446,6 +453,18 @@ var _ = Describe("Controllerutil", func() {
446453
Expect(deploy.ObjectMeta.GetFinalizers()).To(Equal([]string{}))
447454
})
448455
})
456+
457+
Describe("ContainsFinalizer", func() {
458+
It("should check that finalizer is present", func() {
459+
controllerutil.AddFinalizer(deploy, testFinalizer)
460+
Expect(controllerutil.ContainsFinalizer(deploy, testFinalizer)).To(Equal(true))
461+
})
462+
463+
It("should check that finalizer is not present after RemoveFinalizer call", func() {
464+
controllerutil.RemoveFinalizer(deploy, testFinalizer)
465+
Expect(controllerutil.ContainsFinalizer(deploy, testFinalizer)).To(Equal(false))
466+
})
467+
})
449468
})
450469
})
451470

0 commit comments

Comments
 (0)