Skip to content

Commit

Permalink
add more testing to assert on cases not handled
Browse files Browse the repository at this point in the history
Signed-off-by: Troy Connor <troy0820@users.noreply.github.com>
  • Loading branch information
troy0820 committed Aug 25, 2023
1 parent d0ae418 commit 770c4ab
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
14 changes: 8 additions & 6 deletions pkg/controller/controllerutil/controllerutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,19 +96,21 @@ func SetControllerReference(owner, controlled metav1.Object, scheme *runtime.Sch
func RemoveControllerReference(owner, controlled metav1.Object) error {
owners := controlled.GetOwnerReferences()
length := len(owners)
result := []metav1.OwnerReference{}
if length < 1 {
return fmt.Errorf("%T does not have any owner references", controlled)
}
index := 0
for i := 0; i < length; i++ {
if owners[i].Name == owner.GetName() {
owners = append(owners[:index], owners[index+1:]...)
for _, ownerref := range owners {
if ownerref.Name == owner.GetName() {
continue
}
index++
result = append(result, ownerref)
}
if length == len(owners) {

if len(result) == len(owners) {
return fmt.Errorf("%T does not have an owner reference for %T", controlled, owner)
}
controlled.SetOwnerReferences(result)
return nil
}

Expand Down
16 changes: 15 additions & 1 deletion pkg/controller/controllerutil/controllerutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -272,8 +272,8 @@ var _ = Describe("Controllerutil", func() {
Controller: &t,
BlockOwnerDeletion: &t,
}))

Expect(controllerutil.RemoveControllerReference(dep, rs)).NotTo(HaveOccurred())
Expect(len(rs.GetOwnerReferences())).To(BeEquivalentTo(0))
})
It("should fail and return an error if the length is less than 1", func() {
rs := &appsv1.ReplicaSet{}
Expand All @@ -293,6 +293,20 @@ var _ = Describe("Controllerutil", func() {
Expect(controllerutil.SetControllerReference(dep, rs, scheme.Scheme)).NotTo(HaveOccurred())
Expect(controllerutil.RemoveControllerReference(dep2, rs)).To(HaveOccurred())
})
It("should only delete the controller reference and not the other owner references", func() {
rs := &appsv1.ReplicaSet{}
dep := &extensionsv1beta1.Deployment{
ObjectMeta: metav1.ObjectMeta{Name: "foo", UID: "foo-uid"},
}
dep2 := &extensionsv1beta1.Deployment{
ObjectMeta: metav1.ObjectMeta{Name: "bar", UID: "bar-uid"},
}
Expect(controllerutil.SetControllerReference(dep, rs, scheme.Scheme)).NotTo(HaveOccurred())
Expect(controllerutil.SetOwnerReference(dep2, rs, scheme.Scheme)).NotTo(HaveOccurred())
Expect(len(rs.GetOwnerReferences())).To(BeEquivalentTo(2))
Expect(controllerutil.RemoveControllerReference(dep, rs)).NotTo(HaveOccurred())
Expect(len(rs.GetOwnerReferences())).To(BeEquivalentTo(1))
})

})

Expand Down

0 comments on commit 770c4ab

Please sign in to comment.