alert_exceptions_api_test.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package httpapi_test
  2. import (
  3. "fmt"
  4. "net/http"
  5. "testing"
  6. "time"
  7. "github.com/gnacho/netpulse/server-go/internal/alerts"
  8. )
  9. func TestAlertExceptionsAPI(t *testing.T) {
  10. ts := makeTestServer(t)
  11. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  12. res := get(t, ts.URL, "/api/alerts/exceptions", cookie)
  13. if res.StatusCode != http.StatusOK {
  14. t.Fatalf("list empty: %d", res.StatusCode)
  15. }
  16. res.Body.Close()
  17. expires := time.Now().Add(24 * time.Hour).UnixMilli()
  18. body := fmt.Sprintf(`{"kind":"high-temperature","host":"gw","target":"lan5","comment":"known","expiresAt":%d}`, expires)
  19. res = doJSON(t, "POST", ts.URL, "/api/alerts/exceptions", cookie, body)
  20. if res.StatusCode != http.StatusCreated {
  21. t.Fatalf("create: %d", res.StatusCode)
  22. }
  23. res.Body.Close()
  24. xs, err := alerts.ListExceptions(ts.db)
  25. if err != nil || len(xs) != 1 {
  26. t.Fatalf("list after create: err=%v len=%d", err, len(xs))
  27. }
  28. id := xs[0].ID
  29. body = fmt.Sprintf(`{"kind":"high-temperature","host":"gw","target":"","comment":"updated","expiresAt":%d}`, expires)
  30. res = doJSON(t, "PUT", ts.URL, fmt.Sprintf("/api/alerts/exceptions/%d", id), cookie, body)
  31. if res.StatusCode != http.StatusOK {
  32. t.Fatalf("update: %d", res.StatusCode)
  33. }
  34. res.Body.Close()
  35. got, _ := alerts.GetException(ts.db, id)
  36. if got.Comment != "updated" || got.Target != "" {
  37. t.Fatalf("update not applied: %+v", got)
  38. }
  39. res = doJSON(t, "POST", ts.URL, "/api/alerts/exceptions", cookie, `{"kind":"","host":"","target":"","comment":""}`)
  40. if res.StatusCode != http.StatusBadRequest {
  41. t.Fatalf("empty exception must be 400, got %d", res.StatusCode)
  42. }
  43. res.Body.Close()
  44. past := time.Now().Add(-time.Hour).UnixMilli()
  45. res = doJSON(t, "POST", ts.URL, "/api/alerts/exceptions", cookie, fmt.Sprintf(`{"kind":"x","expiresAt":%d}`, past))
  46. if res.StatusCode != http.StatusBadRequest {
  47. t.Fatalf("past expiry must be 400, got %d", res.StatusCode)
  48. }
  49. res.Body.Close()
  50. res = doJSON(t, "DELETE", ts.URL, fmt.Sprintf("/api/alerts/exceptions/%d", id), cookie, "")
  51. if res.StatusCode != http.StatusOK {
  52. t.Fatalf("delete: %d", res.StatusCode)
  53. }
  54. res.Body.Close()
  55. xs, _ = alerts.ListExceptions(ts.db)
  56. if len(xs) != 0 {
  57. t.Fatalf("expected 0 after delete, got %d", len(xs))
  58. }
  59. res = doJSON(t, "DELETE", ts.URL, fmt.Sprintf("/api/alerts/exceptions/%d", id), cookie, "")
  60. if res.StatusCode != http.StatusNotFound {
  61. t.Fatalf("second delete must be 404, got %d", res.StatusCode)
  62. }
  63. res.Body.Close()
  64. }