Skip to content

Commit

Permalink
test: added tests
Browse files Browse the repository at this point in the history
Signed-off-by: RealAnna <[email protected]>
  • Loading branch information
RealAnna committed Nov 17, 2022
1 parent 2579c76 commit 56a7241
Show file tree
Hide file tree
Showing 9 changed files with 451 additions and 63 deletions.
27 changes: 27 additions & 0 deletions operator/api/v1alpha1/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package common

import (
"fmt"
"go.opentelemetry.io/otel/metric/instrument"
"go.opentelemetry.io/otel/sdk/metric"
"math/rand"

"go.opentelemetry.io/otel/attribute"
Expand Down Expand Up @@ -165,3 +167,28 @@ type GaugeFloatValue struct {
Value float64
Attributes []attribute.KeyValue
}

func InitKeptnMeters() KeptnMeters {
provider := metric.NewMeterProvider()
meter := provider.Meter("keptn/task")
deploymentCount, _ := meter.SyncInt64().Counter("keptn.deployment.count", instrument.WithDescription("a simple counter for Keptn Deployments"))
deploymentDuration, _ := meter.SyncFloat64().Histogram("keptn.deployment.duration", instrument.WithDescription("a histogram of duration for Keptn Deployments"), instrument.WithUnit("s"))
taskCount, _ := meter.SyncInt64().Counter("keptn.task.count", instrument.WithDescription("a simple counter for Keptn Tasks"))
taskDuration, _ := meter.SyncFloat64().Histogram("keptn.task.duration", instrument.WithDescription("a histogram of duration for Keptn Tasks"), instrument.WithUnit("s"))
appCount, _ := meter.SyncInt64().Counter("keptn.app.count", instrument.WithDescription("a simple counter for Keptn Apps"))
appDuration, _ := meter.SyncFloat64().Histogram("keptn.app.duration", instrument.WithDescription("a histogram of duration for Keptn Apps"), instrument.WithUnit("s"))
evaluationCount, _ := meter.SyncInt64().Counter("keptn.evaluation.count", instrument.WithDescription("a simple counter for Keptn Evaluations"))
evaluationDuration, _ := meter.SyncFloat64().Histogram("keptn.evaluation.duration", instrument.WithDescription("a histogram of duration for Keptn Evaluations"), instrument.WithUnit("s"))

meters := KeptnMeters{
TaskCount: taskCount,
TaskDuration: taskDuration,
DeploymentCount: deploymentCount,
DeploymentDuration: deploymentDuration,
AppCount: appCount,
AppDuration: appDuration,
EvaluationCount: evaluationCount,
EvaluationDuration: evaluationDuration,
}
return meters
}
2 changes: 0 additions & 2 deletions operator/controllers/common/ITracer.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,5 @@ package common

import "go.opentelemetry.io/otel/trace"

// TODO Autogenerated mock uses pointers, I changed it manually

//go:generate moq -pkg fake -skip-ensure -out ./fake/tracer.go . ITracer
type ITracer = trace.Tracer
141 changes: 141 additions & 0 deletions operator/controllers/common/fake/spanhandler_mock.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

38 changes: 38 additions & 0 deletions operator/controllers/common/fake/test_generators.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package fake

import (
"context"
lfcv1alpha1 "github.com/keptn/lifecycle-toolkit/operator/api/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
)

func AddApp(c client.Client, name string) error {
app := &lfcv1alpha1.KeptnApp{
TypeMeta: metav1.TypeMeta{},
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: "default",
},
Spec: lfcv1alpha1.KeptnAppSpec{
Version: "1.0.0",
},
Status: lfcv1alpha1.KeptnAppStatus{},
}
return c.Create(context.TODO(), app)

}

func AddAppVersion(c client.Client, name string, status lfcv1alpha1.KeptnAppVersionStatus) error {
app := &lfcv1alpha1.KeptnAppVersion{
TypeMeta: metav1.TypeMeta{},
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: "default",
},
Spec: lfcv1alpha1.KeptnAppVersionSpec{KeptnAppSpec: lfcv1alpha1.KeptnAppSpec{Version: "1.0.0"}},
Status: status,
}
return c.Create(context.TODO(), app)

}
2 changes: 1 addition & 1 deletion operator/controllers/common/phasehandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ type PhaseHandler struct {
client.Client
Recorder record.EventRecorder
Log logr.Logger
SpanHandler *SpanHandler
SpanHandler ISpanHandler
}

type PhaseResult struct {
Expand Down
6 changes: 6 additions & 0 deletions operator/controllers/common/spanhandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"
)

//go:generate moq -pkg fake -skip-ensure -out ./fake/spanhandler_mock.go . ISpanHandler
type ISpanHandler interface {
GetSpan(ctx context.Context, tracer trace.Tracer, reconcileObject client.Object, phase string) (context.Context, trace.Span, error)
UnbindSpan(reconcileObject client.Object, phase string) error
}

type SpanHandler struct {
bindCRDSpan map[string]trace.Span
mtx sync.Mutex
Expand Down
46 changes: 7 additions & 39 deletions operator/controllers/keptnapp/controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package keptnapp

import (
"context"
lfcv1alpha1 "github.com/keptn/lifecycle-toolkit/operator/api/v1alpha1"
klcv1alpha1 "github.com/keptn/lifecycle-toolkit/operator/api/v1alpha1"
keptncommon "github.com/keptn/lifecycle-toolkit/operator/api/v1alpha1/common"
"github.com/keptn/lifecycle-toolkit/operator/controllers/common/fake"
"github.com/magiconair/properties/assert"
Expand All @@ -20,16 +20,16 @@ import (
// Example Unit test on help function
func TestKeptnAppReconciler_createAppVersionSuccess(t *testing.T) {

app := &lfcv1alpha1.KeptnApp{
app := &klcv1alpha1.KeptnApp{
TypeMeta: metav1.TypeMeta{},
ObjectMeta: metav1.ObjectMeta{
Name: "my-app",
Namespace: "default",
},
Spec: lfcv1alpha1.KeptnAppSpec{
Spec: klcv1alpha1.KeptnAppSpec{
Version: "1.0.0",
},
Status: lfcv1alpha1.KeptnAppStatus{},
Status: klcv1alpha1.KeptnAppStatus{},
}
r, _, _ := setupReconciler(t)

Expand Down Expand Up @@ -88,9 +88,9 @@ func TestKeptnAppReconciler_Reconcile(t *testing.T) {

//setting up fakeclient CRD data

addApp(r, "myapp")
addApp(r, "myfinishedapp")
addAppVersion(r, "myfinishedapp-1.0.0", keptncommon.StateSucceeded)
fake.AddApp(r.Client, "myapp")
fake.AddApp(r.Client, "myfinishedapp")
fake.AddAppVersion(r.Client, "myfinishedapp-1.0.0", klcv1alpha1.KeptnAppVersionStatus{Status: keptncommon.StateSucceeded})

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down Expand Up @@ -146,35 +146,3 @@ func setupReconciler(t *testing.T) (*KeptnAppReconciler, chan string, *fake.ITra
}
return r, recorder.Events, tr
}

func addApp(r *KeptnAppReconciler, name string) error {
app := &lfcv1alpha1.KeptnApp{
TypeMeta: metav1.TypeMeta{},
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: "default",
},
Spec: lfcv1alpha1.KeptnAppSpec{
Version: "1.0.0",
},
Status: lfcv1alpha1.KeptnAppStatus{},
}
return r.Client.Create(context.TODO(), app)

}

func addAppVersion(r *KeptnAppReconciler, name string, status keptncommon.KeptnState) error {
app := &lfcv1alpha1.KeptnAppVersion{
TypeMeta: metav1.TypeMeta{},
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: "default",
},
Spec: lfcv1alpha1.KeptnAppVersionSpec{},
Status: lfcv1alpha1.KeptnAppVersionStatus{
Status: status,
},
}
return r.Client.Create(context.TODO(), app)

}
49 changes: 28 additions & 21 deletions operator/controllers/keptnappversion/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ type KeptnAppVersionReconciler struct {
client.Client
Log logr.Logger
Recorder record.EventRecorder
Tracer trace.Tracer
Tracer controllercommon.ITracer
Meters common.KeptnMeters
SpanHandler *controllercommon.SpanHandler
SpanHandler controllercommon.ISpanHandler
}

//+kubebuilder:rbac:groups=lifecycle.keptn.sh,resources=keptnappversions,verbs=get;list;watch;create;update;patch;delete
Expand Down Expand Up @@ -82,26 +82,9 @@ func (r *KeptnAppVersionReconciler) Reconcile(ctx context.Context, req ctrl.Requ
return reconcile.Result{}, fmt.Errorf(controllercommon.ErrCannotFetchAppVersionMsg, err)
}

appVersion.SetStartTime()

traceContextCarrier := propagation.MapCarrier(appVersion.Annotations)
ctx = otel.GetTextMapPropagator().Extract(ctx, traceContextCarrier)

appTraceContextCarrier := propagation.MapCarrier(appVersion.Spec.TraceId)
ctxAppTrace := otel.GetTextMapPropagator().Extract(context.TODO(), appTraceContextCarrier)
ctx, ctxAppTrace, span, endSpan := setupSpansContexts(ctx, appVersion, r)

ctx, span := r.Tracer.Start(ctx, "reconcile_app_version", trace.WithSpanKind(trace.SpanKindConsumer))

defer func(span trace.Span, appVersion *klcv1alpha1.KeptnAppVersion) {
if appVersion.IsEndTimeSet() {
r.Log.Info("Increasing app count")
attrs := appVersion.GetMetricsAttributes()
r.Meters.AppCount.Add(ctx, 1, attrs...)
}
span.End()
}(span, appVersion)

appVersion.SetSpanAttributes(span)
defer endSpan()

phase := common.PhaseAppPreDeployment

Expand Down Expand Up @@ -210,6 +193,30 @@ func (r *KeptnAppVersionReconciler) Reconcile(ctx context.Context, req ctrl.Requ
return ctrl.Result{}, nil
}

func setupSpansContexts(ctx context.Context, appVersion *klcv1alpha1.KeptnAppVersion, r *KeptnAppVersionReconciler) (context.Context, context.Context, trace.Span, func()) {
appVersion.SetStartTime()

traceContextCarrier := propagation.MapCarrier(appVersion.Annotations)
ctx = otel.GetTextMapPropagator().Extract(ctx, traceContextCarrier)

appTraceContextCarrier := propagation.MapCarrier(appVersion.Spec.TraceId)
ctxAppTrace := otel.GetTextMapPropagator().Extract(context.TODO(), appTraceContextCarrier)

ctx, span := r.Tracer.Start(ctx, "reconcile_app_version", trace.WithSpanKind(trace.SpanKindConsumer))

endFunc := func() {
if appVersion.IsEndTimeSet() {
r.Log.Info("Increasing app count")
attrs := appVersion.GetMetricsAttributes()
r.Meters.AppCount.Add(ctx, 1, attrs...)
}
span.End()
}

appVersion.SetSpanAttributes(span)
return ctx, ctxAppTrace, span, endFunc
}

// SetupWithManager sets up the controller with the Manager.
func (r *KeptnAppVersionReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
Expand Down
Loading

0 comments on commit 56a7241

Please sign in to comment.