github.com/verrazzano/verrazzano@v1.7.1/tools/psr/backend/workers/prometheus/alerts/alerts_test.go (about)

     1  // Copyright (c) 2022, Oracle and/or its affiliates.
     2  // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
     3  
     4  package alerts
     5  
     6  import (
     7  	"context"
     8  	"github.com/stretchr/testify/assert"
     9  	"github.com/verrazzano/verrazzano/pkg/log/vzlog"
    10  	"github.com/verrazzano/verrazzano/platform-operator/apis/verrazzano/v1alpha1"
    11  	vpoFakeClient "github.com/verrazzano/verrazzano/platform-operator/clientset/versioned/fake"
    12  	"github.com/verrazzano/verrazzano/tools/psr/backend/config"
    13  	"github.com/verrazzano/verrazzano/tools/psr/backend/osenv"
    14  	"github.com/verrazzano/verrazzano/tools/psr/backend/pkg/k8sclient"
    15  	psrprom "github.com/verrazzano/verrazzano/tools/psr/backend/pkg/prometheus"
    16  	corev1 "k8s.io/api/core/v1"
    17  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    18  	"k8s.io/apimachinery/pkg/runtime"
    19  	"k8s.io/apimachinery/pkg/types"
    20  	crtFakeClient "sigs.k8s.io/controller-runtime/pkg/client/fake"
    21  	"strings"
    22  	"testing"
    23  )
    24  
    25  type fakeEnv struct {
    26  	data map[string]string
    27  }
    28  
    29  type fakePsrClient struct {
    30  	psrClient *k8sclient.PsrClient
    31  }
    32  
    33  // TestGetters tests the worker getters
    34  // GIVEN a worker
    35  //
    36  //	WHEN the getter methods are calls
    37  //	THEN ensure that the correct results are returned
    38  func TestGetters(t *testing.T) {
    39  	w, err := NewAlertsWorker()
    40  	assert.NoError(t, err)
    41  
    42  	wd := w.GetWorkerDesc()
    43  	assert.Equal(t, config.WorkerTypeHTTPGet, wd.WorkerType)
    44  	assert.Equal(t, "The alerts receiver worker configures alertmanger and receives alerts and writes them to events", wd.Description)
    45  	assert.Equal(t, metricsPrefix, wd.MetricsPrefix)
    46  
    47  	logged := w.WantLoopInfoLogged()
    48  	assert.False(t, logged)
    49  }
    50  
    51  // TestGetMetricDescList tests the GetEnvDescList method
    52  // GIVEN a worker
    53  //
    54  //	WHEN the GetEnvDescList methods is called
    55  //	THEN ensure that the correct results are returned
    56  func TestGetMetricDescList(t *testing.T) {
    57  	tests := []struct {
    58  		name   string
    59  		fqName string
    60  		help   string
    61  	}{
    62  		{name: "1", fqName: "alerts_firing_received_count", help: "The total number of alerts received from alertmanager"},
    63  		{name: "2", fqName: "alerts_resolved_received_count", help: "The total number of alerts received from alertmanager"},
    64  	}
    65  	for _, test := range tests {
    66  		t.Run(test.name, func(t *testing.T) {
    67  
    68  			wi, err := NewAlertsWorker()
    69  			w := wi.(worker)
    70  			assert.NoError(t, err)
    71  			dl := w.GetMetricDescList()
    72  			var found int
    73  			for _, d := range dl {
    74  				s := d.String()
    75  				if strings.Contains(s, test.fqName) && strings.Contains(s, test.help) {
    76  					found++
    77  				}
    78  			}
    79  			assert.Equal(t, 1, found)
    80  		})
    81  	}
    82  }
    83  
    84  // TestGetMetricList tests the GetMetricList method
    85  // GIVEN a worker
    86  //
    87  //	WHEN the GetMetricList methods is called
    88  //	THEN ensure that the correct results are returned
    89  func TestGetMetricList(t *testing.T) {
    90  	tests := []struct {
    91  		name   string
    92  		fqName string
    93  		help   string
    94  	}{
    95  		{name: "1", fqName: "alerts_firing_received_count", help: "The total number of alerts received from alertmanager"},
    96  		{name: "2", fqName: "alerts_resolved_received_count", help: "The total number of alerts received from alertmanager"},
    97  	}
    98  	for _, test := range tests {
    99  		t.Run(test.name, func(t *testing.T) {
   100  			wi, err := NewAlertsWorker()
   101  			w := wi.(worker)
   102  			assert.NoError(t, err)
   103  			ml := w.GetMetricList()
   104  			var found int
   105  			for _, m := range ml {
   106  				s := m.Desc().String()
   107  				if strings.Contains(s, test.fqName) && strings.Contains(s, test.help) {
   108  					found++
   109  				}
   110  			}
   111  			assert.Equal(t, 1, found)
   112  		})
   113  	}
   114  }
   115  
   116  // Test_updateVZForAlertmanager tests the updateVZForAlertmanager method
   117  // GIVEN a VZ CR
   118  //
   119  //	WHEN the updateVZForAlertmanager method is called
   120  //	THEN ensure that the client objects have been successfully created and mutated and there are no errors
   121  func Test_updateVZForAlertmanager(t *testing.T) {
   122  	envMap := map[string]string{
   123  		config.PsrWorkerType:        config.WorkerTypeReceiveAlerts,
   124  		config.PsrWorkerReleaseName: "test-alerts",
   125  		config.PsrWorkerNamespace:   "test-psr",
   126  	}
   127  	f := fakeEnv{data: envMap}
   128  	saveEnv := osenv.GetEnvFunc
   129  	osenv.GetEnvFunc = f.GetEnv
   130  	defer func() {
   131  		osenv.GetEnvFunc = saveEnv
   132  	}()
   133  
   134  	// Setup fake VZ client
   135  	cr := &v1alpha1.Verrazzano{
   136  		ObjectMeta: metav1.ObjectMeta{
   137  			Name:      "test-vz",
   138  			Namespace: "test-ns",
   139  		},
   140  	}
   141  	vzclient := vpoFakeClient.NewSimpleClientset(cr)
   142  
   143  	// Setup fake K8s client
   144  	scheme := runtime.NewScheme()
   145  	_ = corev1.AddToScheme(scheme)
   146  	_ = v1alpha1.AddToScheme(scheme)
   147  	builder := crtFakeClient.NewClientBuilder().WithScheme(scheme).WithObjects(cr)
   148  	crtClient := builder.Build()
   149  
   150  	// Load the PsrClient with both fake clients
   151  	psrClient := fakePsrClient{
   152  		psrClient: &k8sclient.PsrClient{
   153  			CrtlRuntime: crtClient,
   154  			VzInstall:   vzclient,
   155  		},
   156  	}
   157  	origFc := funcNewPsrClient
   158  	defer func() {
   159  		funcNewPsrClient = origFc
   160  	}()
   161  	funcNewPsrClient = psrClient.NewPsrClient
   162  
   163  	log := vzlog.DefaultLogger()
   164  	conf, err := config.GetCommonConfig(log)
   165  	assert.NoError(t, err)
   166  	err = updateVZForAlertmanager(log, conf)
   167  	assert.NoError(t, err)
   168  
   169  	var cm corev1.ConfigMap
   170  	err = psrClient.psrClient.CrtlRuntime.Get(context.TODO(), types.NamespacedName{
   171  		Name:      psrprom.AlertmanagerCMName,
   172  		Namespace: cr.Namespace,
   173  	}, &cm)
   174  	assert.NoError(t, err)
   175  	assert.Equal(t, `alertmanager:
   176    alertmanagerSpec:
   177      podMetadata:
   178        annotations:
   179          sidecar.istio.io/inject: "false"
   180    config:
   181      receivers:
   182      - webhook_configs:
   183        - url: http://test-alerts-prom-alerts.test-psr:9090/alerts
   184        name: webhook
   185      route:
   186        group_by:
   187        - alertname
   188        receiver: webhook
   189        routes:
   190        - match:
   191            alertname: Watchdog
   192          receiver: webhook
   193    enabled: true
   194  `, cm.Data[psrprom.AlertmanagerCMKey])
   195  
   196  	cr, err = psrClient.psrClient.VzInstall.VerrazzanoV1alpha1().Verrazzanos(cr.Namespace).Get(context.TODO(), cr.Name, metav1.GetOptions{})
   197  	assert.NoError(t, err)
   198  	assert.Equal(t, &corev1.ConfigMapKeySelector{
   199  		LocalObjectReference: corev1.LocalObjectReference{
   200  			Name: psrprom.AlertmanagerCMName,
   201  		},
   202  		Key: psrprom.AlertmanagerCMKey,
   203  	}, cr.Spec.Components.PrometheusOperator.ValueOverrides[0].ConfigMapRef)
   204  }
   205  
   206  func (f *fakeEnv) GetEnv(key string) string {
   207  	return f.data[key]
   208  }
   209  
   210  func (f *fakePsrClient) NewPsrClient() (k8sclient.PsrClient, error) {
   211  	return *f.psrClient, nil
   212  }