errors_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. "errors"
  7. "testing"
  8. "github.com/stretchr/testify/assert"
  9. )
  10. func TestError(t *testing.T) {
  11. baseError := errors.New("test error")
  12. err := &Error{
  13. Err: baseError,
  14. Type: ErrorTypePrivate,
  15. }
  16. assert.Equal(t, err.Error(), baseError.Error())
  17. assert.Equal(t, err.JSON(), H{"error": baseError.Error()})
  18. assert.Equal(t, err.SetType(ErrorTypePublic), err)
  19. assert.Equal(t, err.Type, ErrorTypePublic)
  20. assert.Equal(t, err.SetMeta("some data"), err)
  21. assert.Equal(t, err.Meta, "some data")
  22. assert.Equal(t, err.JSON(), H{
  23. "error": baseError.Error(),
  24. "meta": "some data",
  25. })
  26. err.SetMeta(H{
  27. "status": "200",
  28. "data": "some data",
  29. })
  30. assert.Equal(t, err.JSON(), H{
  31. "error": baseError.Error(),
  32. "status": "200",
  33. "data": "some data",
  34. })
  35. err.SetMeta(H{
  36. "error": "custom error",
  37. "status": "200",
  38. "data": "some data",
  39. })
  40. assert.Equal(t, err.JSON(), H{
  41. "error": "custom error",
  42. "status": "200",
  43. "data": "some data",
  44. })
  45. }
  46. func TestErrorSlice(t *testing.T) {
  47. errs := errorMsgs{
  48. {Err: errors.New("first"), Type: ErrorTypePrivate},
  49. {Err: errors.New("second"), Type: ErrorTypePrivate, Meta: "some data"},
  50. {Err: errors.New("third"), Type: ErrorTypePublic, Meta: H{"status": "400"}},
  51. }
  52. assert.Equal(t, errs.Last().Error(), "third")
  53. assert.Equal(t, errs.Errors(), []string{"first", "second", "third"})
  54. assert.Equal(t, errs.ByType(ErrorTypePublic).Errors(), []string{"third"})
  55. assert.Equal(t, errs.ByType(ErrorTypePrivate).Errors(), []string{"first", "second"})
  56. assert.Equal(t, errs.ByType(ErrorTypePublic|ErrorTypePrivate).Errors(), []string{"first", "second", "third"})
  57. assert.Empty(t, errs.ByType(ErrorTypeBind))
  58. assert.Equal(t, errs.String(), `Error #01: first
  59. Error #02: second
  60. Meta: some data
  61. Error #03: third
  62. Meta: map[status:400]
  63. `)
  64. assert.Equal(t, errs.JSON(), []interface{}{
  65. H{"error": "first"},
  66. H{"error": "second", "meta": "some data"},
  67. H{"error": "third", "status": "400"},
  68. })
  69. errs = errorMsgs{
  70. {Err: errors.New("first"), Type: ErrorTypePrivate},
  71. }
  72. assert.Equal(t, errs.JSON(), H{"error": "first"})
  73. errs = errorMsgs{}
  74. assert.Nil(t, errs.Last())
  75. assert.Nil(t, errs.JSON())
  76. assert.Empty(t, errs.String())
  77. }