"net/http"
"net/http/httptest"
"os"
+ "os/exec"
"strconv"
"strings"
"testing"
// Test cases
func TestMain(M *testing.M) {
alarmManager = NewAlarmManager("localhost:9093", 500)
+ alarmManager.alertInterval = 20000
go alarmManager.Run(false)
time.Sleep(time.Duration(10) * time.Second)
b := alarmer.NewAlarm(alarm.TCP_CONNECTIVITY_LOST_TO_DBAAS, alarm.SeverityMinor, "Hello", "abcd 11")
assert.Nil(t, alarmer.Raise(b), "raise failed")
+ time.Sleep(time.Duration(2) * time.Second)
VerifyAlarm(t, a, 2)
VerifyAlarm(t, b, 2)
}
ts.Close()
}
+func TestGetPrometheusAlerts(t *testing.T) {
+ time.Sleep(1 * time.Second)
+ xapp.Logger.Info("TestGetPrometheusAlerts")
+ ts := CreatePromAlertSimulator2(t, "GET", "/alerts?active=true&inhibited=true&silenced=true&unprocessed=true")
+
+ commandReady := make(chan bool, 1)
+ command := "cli/alarm-cli"
+ args := []string {"gapam", "--active", "true", "--inhibited", "true", "--silenced", "--unprocessed", "true", "true", "--host", "localhost", "--port", "9093", "flushall"}
+ ExecCLICommand(commandReady, command, args...)
+ <-commandReady
+
+ ts.Close()
+}
+
func VerifyAlarm(t *testing.T, a alarm.Alarm, expectedCount int) string {
receivedAlert := waitForEvent()
- assert.Equal(t, len(alarmManager.activeAlarms), expectedCount)
+ assert.Equal(t, expectedCount, len(alarmManager.activeAlarms))
_, ok := alarmManager.IsMatchFound(a)
assert.True(t, ok)
return ts
}
+func CreatePromAlertSimulator2(t *testing.T, method, url string) *httptest.Server {
+ l, err := net.Listen("tcp", "localhost:9093")
+ if err != nil {
+ t.Error("Failed to create listener: " + err.Error())
+ }
+ ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ assert.Equal(t, r.Method, method)
+ assert.Equal(t, r.URL.String(), url)
+
+ w.Header().Add("Content-Type", "application/json")
+ w.WriteHeader(200)
+ // Read alerts from file
+ payload, err := readJSONFromFile("../testresources/prometheus-alerts.json")
+ if err != nil {
+ t.Error("Failed to send response: ", err)
+ }
+ _, err = w.Write(payload)
+ if err != nil {
+ t.Error("Failed to send response: " + err.Error())
+ }
+ }))
+ ts.Listener.Close()
+ ts.Listener = l
+ ts.Start()
+ return ts
+}
+
func waitForEvent() string {
receivedAlert := <-eventChan
return receivedAlert
}
return true
}
+
+func ExecCLICommand(commandReady chan bool, command string, args ...string) {
+ go func() {
+ xapp.Logger.Info("Giving CLI command")
+ cmd := exec.Command(command, args...)
+ cmd.Dir = "../"
+ output, err := cmd.CombinedOutput()
+ if err != nil {
+ xapp.Logger.Info("CLI command failed out: %s", err)
+ }
+ xapp.Logger.Info("CLI command output: %s", output)
+ commandReady <- true
+ xapp.Logger.Info("CLI command completed")
+ }()
+}
+
+func readJSONFromFile(filename string) ([]byte, error) {
+ file, err := ioutil.ReadFile(filename)
+ if err != nil {
+ err := fmt.Errorf("readJSONFromFile() failed: Error: %v", err)
+ return nil, err
+ }
+ return file, nil
+}