recovery_test.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package gin
  2. import (
  3. "bytes"
  4. "log"
  5. "net/http"
  6. "net/http/httptest"
  7. "os"
  8. "testing"
  9. )
  10. // TestPanicInHandler assert that panic has been recovered.
  11. func TestPanicInHandler(t *testing.T) {
  12. req, _ := http.NewRequest("GET", "/recovery", nil)
  13. w := httptest.NewRecorder()
  14. // Disable panic logs for testing
  15. log.SetOutput(bytes.NewBuffer(nil))
  16. r := Default()
  17. r.GET("/recovery", func(_ *Context) {
  18. panic("Oupps, Houston, we have a problem")
  19. })
  20. r.ServeHTTP(w, req)
  21. // restore logging
  22. log.SetOutput(os.Stderr)
  23. if w.Code != 500 {
  24. t.Errorf("Response code should be Internal Server Error, was: %s", w.Code)
  25. }
  26. bodyAsString := w.Body.String()
  27. //fixme: no message provided?
  28. if bodyAsString != "" {
  29. t.Errorf("Response body should be empty, was %s", bodyAsString)
  30. }
  31. //fixme:
  32. if len(w.HeaderMap) != 0 {
  33. t.Errorf("No headers should be provided, was %s", w.HeaderMap)
  34. }
  35. }
  36. // TestPanicWithAbort assert that panic has been recovered even if context.Abort was used.
  37. func TestPanicWithAbort(t *testing.T) {
  38. req, _ := http.NewRequest("GET", "/recovery", nil)
  39. w := httptest.NewRecorder()
  40. // Disable panic logs for testing
  41. log.SetOutput(bytes.NewBuffer(nil))
  42. r := Default()
  43. r.GET("/recovery", func(c *Context) {
  44. c.Abort(400)
  45. panic("Oupps, Houston, we have a problem")
  46. })
  47. r.ServeHTTP(w, req)
  48. // restore logging
  49. log.SetOutput(os.Stderr)
  50. // fixme: why not 500?
  51. if w.Code != 400 {
  52. t.Errorf("Response code should be Bad request, was: %s", w.Code)
  53. }
  54. bodyAsString := w.Body.String()
  55. //fixme: no message provided?
  56. if bodyAsString != "" {
  57. t.Errorf("Response body should be empty, was %s", bodyAsString)
  58. }
  59. //fixme:
  60. if len(w.HeaderMap) != 0 {
  61. t.Errorf("No headers should be provided, was %s", w.HeaderMap)
  62. }
  63. }