errors_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright 2018 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package errors
  5. import (
  6. "errors"
  7. "reflect"
  8. "testing"
  9. )
  10. func TestNonFatal(t *testing.T) {
  11. type (
  12. method = interface{} // merge | appendRequiredNotSet | appendInvalidUTF8
  13. merge struct {
  14. inErr error
  15. wantOk bool
  16. }
  17. appendRequiredNotSet struct{ inField string }
  18. appendInvalidUTF8 struct{ inField string }
  19. )
  20. tests := []struct {
  21. label string
  22. methods []method
  23. wantErr error
  24. }{{
  25. label: "IgnoreNil",
  26. methods: []method{
  27. merge{inErr: nil, wantOk: true},
  28. },
  29. }, {
  30. label: "IgnoreFatal",
  31. methods: []method{
  32. merge{inErr: errors.New("fatal error")},
  33. },
  34. }, {
  35. label: "MergeNonFatal",
  36. methods: []method{
  37. appendRequiredNotSet{"foo"},
  38. merge{inErr: customRequiredNotSetError{}, wantOk: true},
  39. appendInvalidUTF8{"bar"},
  40. merge{inErr: customInvalidUTF8Error{}, wantOk: true},
  41. merge{inErr: NonFatalErrors{
  42. requiredNotSetError("fizz"),
  43. invalidUTF8Error("buzz"),
  44. }, wantOk: true},
  45. merge{inErr: errors.New("fatal error")}, // not stored
  46. },
  47. wantErr: NonFatalErrors{
  48. requiredNotSetError("foo"),
  49. customRequiredNotSetError{},
  50. invalidUTF8Error("bar"),
  51. customInvalidUTF8Error{},
  52. requiredNotSetError("fizz"),
  53. invalidUTF8Error("buzz"),
  54. },
  55. }}
  56. for _, tt := range tests {
  57. t.Run(tt.label, func(t *testing.T) {
  58. var nerr NonFatal
  59. for _, m := range tt.methods {
  60. switch m := m.(type) {
  61. case merge:
  62. if gotOk := nerr.Merge(m.inErr); gotOk != m.wantOk {
  63. t.Errorf("Merge() = %v, want %v", gotOk, m.wantOk)
  64. }
  65. case appendRequiredNotSet:
  66. nerr.AppendRequiredNotSet(m.inField)
  67. case appendInvalidUTF8:
  68. nerr.AppendInvalidUTF8(m.inField)
  69. default:
  70. t.Fatalf("invalid method: %T", m)
  71. }
  72. }
  73. if !reflect.DeepEqual(nerr.E, tt.wantErr) {
  74. t.Errorf("NonFatal.E = %v, want %v", nerr.E, tt.wantErr)
  75. }
  76. })
  77. }
  78. }
  79. type customInvalidUTF8Error struct{}
  80. func (customInvalidUTF8Error) Error() string { return "invalid UTF-8 detected" }
  81. func (customInvalidUTF8Error) InvalidUTF8() bool { return true }
  82. type customRequiredNotSetError struct{}
  83. func (customRequiredNotSetError) Error() string { return "required field not set" }
  84. func (customRequiredNotSetError) RequiredNotSet() bool { return true }