codeberg.org/gruf/go-errors/v2@v2.3.1/errors_test.go (about) 1 package errors_test 2 3 import ( 4 "fmt" 5 "runtime" 6 "sync" 7 "testing" 8 _ "unsafe" 9 10 "codeberg.org/gruf/go-errors/v2" 11 ) 12 13 var msgTests = []string{ 14 "hello world", 15 "oh no!", 16 "aw shit", 17 } 18 19 var formatTests = []struct { 20 fmt string 21 arg []interface{} 22 exp string 23 }{ 24 { 25 fmt: "wrap: %v", 26 arg: []interface{}{errors.New("error")}, 27 exp: fmt.Sprintf("wrap: %v", errors.New("error")), 28 }, 29 { 30 fmt: "%d %d %d", 31 arg: []interface{}{0, 1, 2}, 32 exp: fmt.Sprintf("%d %d %d", 0, 1, 2), 33 }, 34 { 35 fmt: "%#v %#v", 36 arg: []interface{}{sync.Mutex{}, map[string]string{"hello": "world"}}, 37 exp: fmt.Sprintf("%#v %#v", sync.Mutex{}, map[string]string{"hello": "world"}), 38 }, 39 } 40 41 func TestNew(t *testing.T) { 42 for _, msg := range msgTests { 43 exp := msg 44 err := errors.New(msg) 45 46 if errors.IncludesCaller { 47 exp = "v2_test.TestNew " + exp 48 } 49 50 if str := err.Error(); str != exp { 51 t.Errorf("unexpected error string: expect=%q actual=%q", exp, str) 52 } 53 } 54 } 55 56 func TestNewf(t *testing.T) { 57 for _, test := range formatTests { 58 exp := test.exp 59 err := errors.Newf(test.fmt, test.arg...) 60 61 if errors.IncludesCaller { 62 exp = "v2_test.TestNewf " + exp 63 } 64 65 if str := err.Error(); str != exp { 66 t.Errorf("unexpected error string: expect=%q actual=%q", exp, str) 67 } 68 } 69 } 70 71 func TestWrap(t *testing.T) { 72 base := errors.New("base error") 73 74 for _, msg := range msgTests { 75 exp := msg + ": " + base.Error() 76 err := errors.Wrap(base, msg) 77 78 if errors.IncludesCaller { 79 exp = "v2_test.TestWrap " + exp 80 } 81 82 if str := err.Error(); str != exp { 83 t.Errorf("unexpected error string: expect=%q actual=%q", exp, str) 84 } 85 86 if !errors.Is(err, base) { 87 t.Errorf("wrapped error did not identify as base") 88 } 89 } 90 } 91 92 func TestWrapf(t *testing.T) { 93 base := errors.New("base error") 94 95 for _, test := range formatTests { 96 exp := test.exp + ": " + base.Error() 97 err := errors.Wrapf(base, test.fmt, test.arg...) 98 99 if errors.IncludesCaller { 100 exp = "v2_test.TestWrapf " + exp 101 } 102 103 if str := err.Error(); str != exp { 104 t.Errorf("unexpected error string: expect=%q actual=%q", exp, str) 105 } 106 107 if !errors.Is(err, base) { 108 t.Errorf("wrapped error did not identify as base") 109 } 110 } 111 } 112 113 //go:linkname funcName codeberg.org/gruf/go-errors/v2.funcName 114 func funcName(fn *runtime.Func) string 115 116 type baseerror struct{} 117 118 func (baseerror) Error() string { return "base error" }