Skip to content

Commit def49ef

Browse files
committed
✨ Add ContainsFinalizer helper to the controllerutil
1 parent 1c83ff6 commit def49ef

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

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{
@@ -452,6 +459,18 @@ var _ = Describe("Controllerutil", func() {
452459
Expect(deploy.ObjectMeta.GetFinalizers()).To(Equal([]string{}))
453460
})
454461
})
462+
463+
Describe("ContainsFinalizer", func() {
464+
It("should check that finalizer is present", func() {
465+
controllerutil.AddFinalizer(deploy, testFinalizer)
466+
Expect(controllerutil.ContainsFinalizer(deploy, testFinalizer)).To(Equal(true))
467+
})
468+
469+
It("should check that finalizer is not present after RemoveFinalizer call", func() {
470+
controllerutil.RemoveFinalizer(deploy, testFinalizer)
471+
Expect(controllerutil.ContainsFinalizer(deploy, testFinalizer)).To(Equal(false))
472+
})
473+
})
455474
})
456475
})
457476

0 commit comments

Comments
 (0)