package httpapi_test import ( "fmt" "net/http" "testing" "time" "github.com/gnacho/netpulse/server-go/internal/alerts" ) func TestAlertExceptionsAPI(t *testing.T) { ts := makeTestServer(t) _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456") res := get(t, ts.URL, "/api/alerts/exceptions", cookie) if res.StatusCode != http.StatusOK { t.Fatalf("list empty: %d", res.StatusCode) } res.Body.Close() expires := time.Now().Add(24 * time.Hour).UnixMilli() body := fmt.Sprintf(`{"kind":"high-temperature","host":"gw","target":"lan5","comment":"known","expiresAt":%d}`, expires) res = doJSON(t, "POST", ts.URL, "/api/alerts/exceptions", cookie, body) if res.StatusCode != http.StatusCreated { t.Fatalf("create: %d", res.StatusCode) } res.Body.Close() xs, err := alerts.ListExceptions(ts.db) if err != nil || len(xs) != 1 { t.Fatalf("list after create: err=%v len=%d", err, len(xs)) } id := xs[0].ID body = fmt.Sprintf(`{"kind":"high-temperature","host":"gw","target":"","comment":"updated","expiresAt":%d}`, expires) res = doJSON(t, "PUT", ts.URL, fmt.Sprintf("/api/alerts/exceptions/%d", id), cookie, body) if res.StatusCode != http.StatusOK { t.Fatalf("update: %d", res.StatusCode) } res.Body.Close() got, _ := alerts.GetException(ts.db, id) if got.Comment != "updated" || got.Target != "" { t.Fatalf("update not applied: %+v", got) } res = doJSON(t, "POST", ts.URL, "/api/alerts/exceptions", cookie, `{"kind":"","host":"","target":"","comment":""}`) if res.StatusCode != http.StatusBadRequest { t.Fatalf("empty exception must be 400, got %d", res.StatusCode) } res.Body.Close() past := time.Now().Add(-time.Hour).UnixMilli() res = doJSON(t, "POST", ts.URL, "/api/alerts/exceptions", cookie, fmt.Sprintf(`{"kind":"x","expiresAt":%d}`, past)) if res.StatusCode != http.StatusBadRequest { t.Fatalf("past expiry must be 400, got %d", res.StatusCode) } res.Body.Close() res = doJSON(t, "DELETE", ts.URL, fmt.Sprintf("/api/alerts/exceptions/%d", id), cookie, "") if res.StatusCode != http.StatusOK { t.Fatalf("delete: %d", res.StatusCode) } res.Body.Close() xs, _ = alerts.ListExceptions(ts.db) if len(xs) != 0 { t.Fatalf("expected 0 after delete, got %d", len(xs)) } res = doJSON(t, "DELETE", ts.URL, fmt.Sprintf("/api/alerts/exceptions/%d", id), cookie, "") if res.StatusCode != http.StatusNotFound { t.Fatalf("second delete must be 404, got %d", res.StatusCode) } res.Body.Close() }