func compareAlertData(exp, got kapacitor.AlertData) (bool, string) { // Pull out Result for comparision expData := kapacitor.Result(exp.Data) exp.Data = influxql.Result{} gotData := kapacitor.Result(got.Data) kapacitor.ConvertResultTimes(&gotData) got.Data = influxql.Result{} if !reflect.DeepEqual(got, exp) { return false, fmt.Sprintf("\ngot %v\nexp %v", got, exp) } return compareResults(expData, gotData) }
func TestBatch_AlertStateChangesOnlyExpired(t *testing.T) { requestCount := int32(0) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ad := kapacitor.AlertData{} dec := json.NewDecoder(r.Body) err := dec.Decode(&ad) if err != nil { t.Fatal(err) } // We don't care about the data for this test ad.Data = influxql.Result{} var expAd kapacitor.AlertData atomic.AddInt32(&requestCount, 1) rc := atomic.LoadInt32(&requestCount) if rc < 3 { expAd = kapacitor.AlertData{ ID: "cpu_usage_idle:cpu=cpu-total", Message: "cpu_usage_idle:cpu=cpu-total is CRITICAL", Time: time.Date(1971, 1, 1, 0, 0, int(rc-1)*20, 0, time.UTC), Duration: time.Duration(rc-1) * 20 * time.Second, Level: kapacitor.CritAlert, } } else { expAd = kapacitor.AlertData{ ID: "cpu_usage_idle:cpu=cpu-total", Message: "cpu_usage_idle:cpu=cpu-total is OK", Time: time.Date(1971, 1, 1, 0, 0, 38, 0, time.UTC), Duration: 38 * time.Second, Level: kapacitor.OKAlert, } } if eq, msg := compareAlertData(expAd, ad); !eq { t.Errorf("unexpected alert data for request: %d %s", rc, msg) } })) defer ts.Close() var script = ` batch |query(''' SELECT mean("value") FROM "telegraf"."default".cpu_usage_idle WHERE "host" = 'serverA' AND "cpu" != 'cpu-total' ''') .period(10s) .every(10s) .groupBy(time(2s), 'cpu') |alert() .crit(lambda:"mean" > 90) .stateChangesOnly(15s) .levelField('level') .details('') .post('` + ts.URL + `') ` clock, et, replayErr, tm := testBatcher(t, "TestBatch_AlertStateChangesOnly", script) defer tm.Close() err := fastForwardTask(clock, et, replayErr, tm, 40*time.Second) if err != nil { t.Error(err) } if exp, rc := 3, int(atomic.LoadInt32(&requestCount)); rc != exp { t.Errorf("got %v exp %v", rc, exp) } }