recovery_test.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package gin
  2. import (
  3. "bytes"
  4. "log"
  5. "os"
  6. "testing"
  7. )
  8. // TestPanicInHandler assert that panic has been recovered.
  9. func TestPanicInHandler(t *testing.T) {
  10. // SETUP
  11. log.SetOutput(bytes.NewBuffer(nil)) // Disable panic logs for testing
  12. r := New()
  13. r.Use(Recovery())
  14. r.GET("/recovery", func(_ *Context) {
  15. panic("Oupps, Houston, we have a problem")
  16. })
  17. // RUN
  18. w := PerformRequest(r, "GET", "/recovery")
  19. // restore logging
  20. log.SetOutput(os.Stderr)
  21. if w.Code != 500 {
  22. t.Errorf("Response code should be Internal Server Error, was: %s", w.Code)
  23. }
  24. }
  25. // TestPanicWithAbort assert that panic has been recovered even if context.Abort was used.
  26. func TestPanicWithAbort(t *testing.T) {
  27. // SETUP
  28. log.SetOutput(bytes.NewBuffer(nil))
  29. r := New()
  30. r.Use(Recovery())
  31. r.GET("/recovery", func(c *Context) {
  32. c.Abort(400)
  33. panic("Oupps, Houston, we have a problem")
  34. })
  35. // RUN
  36. w := PerformRequest(r, "GET", "/recovery")
  37. // restore logging
  38. log.SetOutput(os.Stderr)
  39. // TEST
  40. if w.Code != 500 {
  41. t.Errorf("Response code should be Bad request, was: %s", w.Code)
  42. }
  43. }