recovery_test.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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(RecoveryWithWriter(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, 500, w.Code)
  22. assert.Contains(t, buffer.String(), "GET /recovery")
  23. assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem")
  24. assert.Contains(t, buffer.String(), "TestPanicInHandler")
  25. }
  26. // TestPanicWithAbort assert that panic has been recovered even if context.Abort was used.
  27. func TestPanicWithAbort(t *testing.T) {
  28. router := New()
  29. router.Use(RecoveryWithWriter(nil))
  30. router.GET("/recovery", func(c *Context) {
  31. c.AbortWithStatus(400)
  32. panic("Oupps, Houston, we have a problem")
  33. })
  34. // RUN
  35. w := performRequest(router, "GET", "/recovery")
  36. // TEST
  37. assert.Equal(t, 400, w.Code)
  38. }
  39. func TestSource(t *testing.T) {
  40. bs := source(nil, 0)
  41. assert.Equal(t, []byte("???"), bs)
  42. in := [][]byte{
  43. []byte("Hello world."),
  44. []byte("Hi, gin.."),
  45. }
  46. bs = source(in, 10)
  47. assert.Equal(t, []byte("???"), bs)
  48. bs = source(in, 1)
  49. assert.Equal(t, []byte("Hello world."), bs)
  50. }
  51. func TestFunction(t *testing.T) {
  52. bs := function(1)
  53. assert.Equal(t, []byte("???"), bs)
  54. }