Skip to content

Commit cfd0b42

Browse files
authored
Merge pull request #415 from guillaume86/controller-name
derive controller name from prototype and allow custom name
2 parents a579283 + 76c90bc commit cfd0b42

File tree

2 files changed

+80
-2
lines changed

2 files changed

+80
-2
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package utils
2+
3+
import (
4+
"testing"
5+
6+
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
7+
"k8s.io/apimachinery/pkg/runtime"
8+
addonsv1alpha1 "sigs.k8s.io/kubebuilder-declarative-pattern/pkg/patterns/addon/pkg/apis/v1alpha1"
9+
)
10+
11+
type mockCommonObject struct {
12+
addonsv1alpha1.CommonObject
13+
name string
14+
}
15+
16+
func (m *mockCommonObject) ComponentName() string {
17+
return m.name
18+
}
19+
20+
func TestGetCommonName(t *testing.T) {
21+
type args struct {
22+
instance runtime.Object
23+
}
24+
tests := []struct {
25+
name string
26+
args args
27+
want string
28+
wantErr bool
29+
}{
30+
{
31+
name: "CommonObject instance",
32+
args: args{
33+
instance: &mockCommonObject{name: "test-component"},
34+
},
35+
want: "test-component",
36+
wantErr: false,
37+
},
38+
{
39+
name: "Unstructured instance",
40+
args: args{
41+
instance: &unstructured.Unstructured{
42+
Object: map[string]interface{}{
43+
"kind": "TestKind",
44+
},
45+
},
46+
},
47+
want: "testkind",
48+
wantErr: false,
49+
},
50+
{
51+
name: "Invalid instance",
52+
args: args{
53+
instance: &runtime.Unknown{},
54+
},
55+
want: "",
56+
wantErr: true,
57+
},
58+
}
59+
for _, tt := range tests {
60+
t.Run(tt.name, func(t *testing.T) {
61+
got, err := GetCommonName(tt.args.instance)
62+
if (err != nil) != tt.wantErr {
63+
t.Errorf("GetCommonName() error = %v, wantErr %v", err, tt.wantErr)
64+
return
65+
}
66+
if got != tt.want {
67+
t.Errorf("GetCommonName() = %v, want %v", got, tt.want)
68+
}
69+
})
70+
}
71+
}

pkg/patterns/declarative/reconciler.go

+9-2
Original file line numberDiff line numberDiff line change
@@ -106,10 +106,17 @@ func (e *ErrorResult) Error() string {
106106
var defaultApplier = applier.DefaultApplier
107107

108108
func (r *Reconciler) Init(mgr manager.Manager, prototype DeclarativeObject, opts ...ReconcilerOption) error {
109+
controllerName := "addon-controller"
110+
if commonName, err := utils.GetCommonName(prototype); err == nil {
111+
controllerName = commonName + "-controller"
112+
}
113+
114+
return r.InitWithName(mgr, prototype, controllerName, opts...)
115+
}
116+
117+
func (r *Reconciler) InitWithName(mgr manager.Manager, prototype DeclarativeObject, controllerName string, opts ...ReconcilerOption) error {
109118
r.prototype = prototype
110119

111-
// TODO: Can we derive the name from prototype?
112-
controllerName := "addon-controller"
113120
r.recorder = mgr.GetEventRecorderFor(controllerName)
114121

115122
r.client = mgr.GetClient()

0 commit comments

Comments
 (0)