recovery_test.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. "testing"
  8. "github.com/stretchr/testify/assert"
  9. )
  10. // TestPanicInHandler assert that panic has been recovered.
  11. func TestPanicInHandler(t *testing.T) {
  12. buffer := new(bytes.Buffer)
  13. router := New()
  14. router.Use(RecoveryWithFile(buffer))
  15. router.GET("/recovery", func(_ *Context) {
  16. panic("Oupps, Houston, we have a problem")
  17. })
  18. // RUN
  19. w := performRequest(router, "GET", "/recovery")
  20. // TEST
  21. assert.Equal(t, w.Code, 500)
  22. assert.Contains(t, buffer.String(), "Gin Panic Recover!! -> Oupps, Houston, we have a problem")
  23. assert.Contains(t, buffer.String(), "TestPanicInHandler")
  24. }
  25. // TestPanicWithAbort assert that panic has been recovered even if context.Abort was used.
  26. func TestPanicWithAbort(t *testing.T) {
  27. router := New()
  28. router.Use(RecoveryWithFile(nil))
  29. router.GET("/recovery", func(c *Context) {
  30. c.AbortWithStatus(400)
  31. panic("Oupps, Houston, we have a problem")
  32. })
  33. // RUN
  34. w := performRequest(router, "GET", "/recovery")
  35. // TEST
  36. assert.Equal(t, w.Code, 500) // NOT SURE
  37. }