recovery_test.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. "net/http"
  8. "testing"
  9. "github.com/stretchr/testify/assert"
  10. )
  11. // TestPanicInHandler assert that panic has been recovered.
  12. func TestPanicInHandler(t *testing.T) {
  13. buffer := new(bytes.Buffer)
  14. router := New()
  15. router.Use(RecoveryWithWriter(buffer))
  16. router.GET("/recovery", func(_ *Context) {
  17. panic("Oupps, Houston, we have a problem")
  18. })
  19. // RUN
  20. w := performRequest(router, "GET", "/recovery")
  21. // TEST
  22. assert.Equal(t, http.StatusInternalServerError, w.Code)
  23. assert.Contains(t, buffer.String(), "GET /recovery")
  24. assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem")
  25. assert.Contains(t, buffer.String(), "TestPanicInHandler")
  26. }
  27. // TestPanicWithAbort assert that panic has been recovered even if context.Abort was used.
  28. func TestPanicWithAbort(t *testing.T) {
  29. router := New()
  30. router.Use(RecoveryWithWriter(nil))
  31. router.GET("/recovery", func(c *Context) {
  32. c.AbortWithStatus(http.StatusBadRequest)
  33. panic("Oupps, Houston, we have a problem")
  34. })
  35. // RUN
  36. w := performRequest(router, "GET", "/recovery")
  37. // TEST
  38. assert.Equal(t, http.StatusBadRequest, w.Code)
  39. }
  40. func TestSource(t *testing.T) {
  41. bs := source(nil, 0)
  42. assert.Equal(t, []byte("???"), bs)
  43. in := [][]byte{
  44. []byte("Hello world."),
  45. []byte("Hi, gin.."),
  46. }
  47. bs = source(in, 10)
  48. assert.Equal(t, []byte("???"), bs)
  49. bs = source(in, 1)
  50. assert.Equal(t, []byte("Hello world."), bs)
  51. }
  52. func TestFunction(t *testing.T) {
  53. bs := function(1)
  54. assert.Equal(t, []byte("???"), bs)
  55. }