From e7653f29ebed92f852aa55e4b399884ff8132bd7 Mon Sep 17 00:00:00 2001 From: Theron Voran Date: Mon, 2 Dec 2024 12:43:34 -0800 Subject: [PATCH] Add metrics unit test (#709) * Add metrics unit test * go mod tidy --- agent-inject/metrics_test.go | 67 ++++++++++++++++++++++++++++++++++++ go.mod | 1 + 2 files changed, 68 insertions(+) create mode 100644 agent-inject/metrics_test.go diff --git a/agent-inject/metrics_test.go b/agent-inject/metrics_test.go new file mode 100644 index 00000000..65101877 --- /dev/null +++ b/agent-inject/metrics_test.go @@ -0,0 +1,67 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package agent_inject + +import ( + "testing" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/testutil" + "github.com/stretchr/testify/assert" +) + +func Test_incrementInjections(t *testing.T) { + MustRegisterInjectorMetrics(prometheus.DefaultRegisterer) + + tests := map[string]struct { + namespace string + mutateResponse MutateResponse + expectedLabels map[string]string + }{ + "init_only": { + namespace: "init", + mutateResponse: MutateResponse{ + InjectedInit: true, + InjectedSidecar: false, + }, + expectedLabels: map[string]string{ + metricsLabelNamespace: "init", + metricsLabelType: metricsLabelTypeInitOnly, + }, + }, + "sidecar_only": { + namespace: "sidecar", + mutateResponse: MutateResponse{ + InjectedInit: false, + InjectedSidecar: true, + }, + expectedLabels: map[string]string{ + metricsLabelNamespace: "sidecar", + metricsLabelType: metricsLabelTypeSidecarOnly, + }, + }, + "init_and_sidecar": { + namespace: "both", + mutateResponse: MutateResponse{ + InjectedInit: true, + InjectedSidecar: true, + }, + expectedLabels: map[string]string{ + metricsLabelNamespace: "both", + metricsLabelType: metricsLabelTypeBoth, + }, + }, + } + for name, test := range tests { + t.Run(name, func(t *testing.T) { + t.Cleanup(func() { + injectionsByNamespace.Reset() + }) + incrementInjections(test.namespace, test.mutateResponse) + assert.Equal(t, 1, testutil.CollectAndCount(injectionsByNamespace)) + check := injectionsByNamespace.With(prometheus.Labels(test.expectedLabels)) + assert.Equal(t, float64(1), testutil.ToFloat64(check)) + }) + } +} diff --git a/go.mod b/go.mod index ec219ce3..2b75a430 100644 --- a/go.mod +++ b/go.mod @@ -58,6 +58,7 @@ require ( github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/compress v1.17.9 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect