recovery_test.go 1.2 KB

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