diff --git a/test/monitoring/component-alerts_test.go b/test/monitoring/component-alerts_test.go new file mode 100644 index 000000000..2923304eb --- /dev/null +++ b/test/monitoring/component-alerts_test.go @@ -0,0 +1,108 @@ +// Copyright 2020 The Lokomotive Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build aws packet +// +build poste2e + +package monitoring + +import ( + "context" + "fmt" + "reflect" + "testing" + "time" + + testutil "github.com/kinvolk/lokomotive/test/components/util" + + "github.com/prometheus/client_golang/api" + v1 "github.com/prometheus/client_golang/api/prometheus/v1" +) + +// nolint:funlen +func TestComponentAlerts(t *testing.T) { + const prometheusPodPort = 9090 + + p := &testutil.PortForwardInfo{ + PodName: "prometheus-prometheus-operator-prometheus-0", + Namespace: "monitoring", + PodPort: prometheusPodPort, + } + + p.PortForward(t) + defer p.CloseChan() + p.WaitUntilForwardingAvailable(t) + + promClient, err := api.NewClient(api.Config{ + Address: fmt.Sprintf("http://127.0.0.1:%d", p.LocalPort), + }) + if err != nil { + t.Fatalf("Error creating client: %v", err) + } + + v1api := v1.NewAPI(promClient) + + const contextTimeout = 10 + + ctx, cancel := context.WithTimeout(context.Background(), contextTimeout*time.Second) + defer cancel() + + result, err := v1api.Rules(ctx) + if err != nil { + t.Fatalf("%v", err) + } + + alertTestCases := []struct { + Name string + Alerts []string + }{ + { + Name: "metallb-rules", + Alerts: []string{ + "MetalLBNoBGPSession", "MetalLBConfigStale", + }, + }, + } + + // This map will store information from cluster so that it is easier to query it against the test cases + ruleGroups := make(map[string][]string, len(result.Groups)) + + for _, ruleGroup := range result.Groups { + rules := make([]string, 0) + + for _, rule := range ruleGroup.Rules { + switch v := rule.(type) { + case v1.AlertingRule: + rules = append(rules, v.Name) + default: + } + } + + ruleGroups[ruleGroup.Name] = rules + } + + for _, alertTestCase := range alertTestCases { + alertTestCase := alertTestCase + t.Run(alertTestCase.Name, func(t *testing.T) { + rules, ok := ruleGroups[alertTestCase.Name] + if !ok { + t.Errorf("RuleGroup %q not found", alertTestCase.Name) + return + } + if !reflect.DeepEqual(rules, alertTestCase.Alerts) { + t.Errorf("Rules don't match. Expected: %#v and \ngot %#v", alertTestCase.Alerts, rules) + } + }) + } +}