You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

63 lines
1.2 KiB

  1. package handlers
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "testing"
  6. )
  7. func TestPanic(t *testing.T) {
  8. h := PanicHandler(http.HandlerFunc(
  9. func(w http.ResponseWriter, r *http.Request) {
  10. panic("test")
  11. }), nil)
  12. s := httptest.NewServer(h)
  13. defer s.Close()
  14. res, err := http.Get(s.URL)
  15. if err != nil {
  16. panic(err)
  17. }
  18. assertStatus(http.StatusInternalServerError, res.StatusCode, t)
  19. }
  20. func TestNoPanic(t *testing.T) {
  21. h := PanicHandler(http.HandlerFunc(
  22. func(w http.ResponseWriter, r *http.Request) {
  23. }), nil)
  24. s := httptest.NewServer(h)
  25. defer s.Close()
  26. res, err := http.Get(s.URL)
  27. if err != nil {
  28. panic(err)
  29. }
  30. assertStatus(http.StatusOK, res.StatusCode, t)
  31. }
  32. func TestPanicCustom(t *testing.T) {
  33. h := PanicHandler(http.HandlerFunc(
  34. func(w http.ResponseWriter, r *http.Request) {
  35. panic("ok")
  36. }),
  37. http.HandlerFunc(
  38. func(w http.ResponseWriter, r *http.Request) {
  39. err, ok := GetPanicError(w)
  40. if !ok {
  41. panic("no panic error found")
  42. }
  43. w.WriteHeader(501)
  44. w.Write([]byte(err.(string)))
  45. }))
  46. s := httptest.NewServer(h)
  47. defer s.Close()
  48. res, err := http.Get(s.URL)
  49. if err != nil {
  50. panic(err)
  51. }
  52. assertStatus(501, res.StatusCode, t)
  53. assertBody([]byte("ok"), res, t)
  54. }