github.com/mitranim/sqlb@v0.7.2/t_err_test.go (about) 1 package sqlb 2 3 import ( 4 "fmt" 5 "io" 6 "testing" 7 ) 8 9 type FakeTracedErr string 10 11 func (self FakeTracedErr) Error() string { return string(self) } 12 13 func (self FakeTracedErr) Format(out fmt.State, _ rune) { 14 try1(io.WriteString(out, self.Error())) 15 16 if out.Flag('+') { 17 if self != `` { 18 try1(io.WriteString(out, `; `)) 19 } 20 try1(io.WriteString(out, `fake stack trace`)) 21 return 22 } 23 } 24 25 func Benchmark_errf(b *testing.B) { 26 for ind := 0; ind < b.N; ind++ { 27 errf(`error %v`, `message`) 28 } 29 } 30 31 func Benchmark_fmt_Errorf(b *testing.B) { 32 for ind := 0; ind < b.N; ind++ { 33 fmt.Errorf(`error %v`, `message`) 34 } 35 } 36 37 func TestErr_formatting(t *testing.T) { 38 test := func(src Err, expBase, expPlus string) { 39 eq(t, expBase, src.Error()) 40 eq(t, expBase, fmt.Sprintf(`%v`, src)) 41 eq(t, expPlus, fmt.Sprintf(`%+v`, src)) 42 } 43 44 test(Err{}, ``, ``) 45 46 test( 47 Err{While: `doing some operation`}, 48 `[sqlb] error while doing some operation`, 49 `[sqlb] error while doing some operation`, 50 ) 51 52 test( 53 Err{Cause: ErrStr(`some cause`)}, 54 `[sqlb] error: some cause`, 55 `[sqlb] error: some cause`, 56 ) 57 58 test( 59 Err{ 60 While: `doing some operation`, 61 Cause: ErrStr(`some cause`), 62 }, 63 `[sqlb] error while doing some operation: some cause`, 64 `[sqlb] error while doing some operation: some cause`, 65 ) 66 67 test( 68 Err{ 69 While: `doing some operation`, 70 Cause: FakeTracedErr(`some cause`), 71 }, 72 `[sqlb] error while doing some operation: some cause`, 73 `[sqlb] error while doing some operation: some cause; fake stack trace`, 74 ) 75 }