github.com/qioalice/ekago/v3@v3.3.2-0.20221202205325-5c262d586ee4/ekaerr/error_test.go (about) 1 // Copyright © 2020-2021. All rights reserved. 2 // Author: Ilya Stroy. 3 // Contacts: iyuryevich@pm.me, https://github.com/qioalice 4 // License: https://opensource.org/licenses/MIT 5 6 package ekaerr_test 7 8 import ( 9 "fmt" 10 "runtime" 11 "testing" 12 13 "github.com/qioalice/ekago/v3/ekaerr" 14 "github.com/qioalice/ekago/v3/ekalog" 15 16 "github.com/stretchr/testify/assert" 17 ) 18 19 type T struct{} 20 21 func (T) String() string { 22 return "stringer" 23 } 24 25 func foo() *ekaerr.Error { 26 return foo1().AddMessage("foo bad").WithObject("foo_arg", T{}).Throw() 27 } 28 29 func foo1() *ekaerr.Error { 30 return foo2().AddMessage("foo1 bad").WithInt("foo1_arg", 23).Throw() 31 } 32 33 func foo2() *ekaerr.Error { 34 return foo3().AddMessage("foo2 bad").WithString("foo2_arg?", "").Throw() 35 } 36 37 func foo3() *ekaerr.Error { 38 return ekaerr.IllegalState.New("what??", "arg1?", nil).Throw() 39 } 40 41 func TestError(t *testing.T) { 42 ekalog.Warne("", foo()) 43 } 44 45 func BenchmarkErrorCreation(b *testing.B) { 46 b.StopTimer() 47 b.ReportAllocs() 48 49 defer func() { 50 runtime.GC() 51 fmt.Printf("EKAERR: %+v\n", ekaerr.EPS()) 52 fmt.Println() 53 }() 54 55 b.StartTimer() 56 for i := 0; i < b.N; i++ { 57 _ = ekaerr.NotImplemented.New("An error") 58 } 59 } 60 61 func BenchmarkErrorCreationReusing(b *testing.B) { 62 b.StopTimer() 63 b.ReportAllocs() 64 65 defer func() { 66 runtime.GC() 67 fmt.Printf("EKAERR: %+v\n", ekaerr.EPS()) 68 fmt.Println() 69 }() 70 71 b.StartTimer() 72 for i := 0; i < b.N; i++ { 73 ekaerr.ReleaseError(ekaerr.NotImplemented.New("An error")) 74 } 75 } 76 77 func BenchmarkErrorCreateAndReleaser(b *testing.B) { 78 b.StopTimer() 79 b.ReportAllocs() 80 b.StartTimer() 81 for i := 0; i < b.N; i++ { 82 ekaerr.ReleaseError(foo()) 83 } 84 } 85 86 func TestError_IsAnyDeep(t *testing.T) { 87 cls := ekaerr.AlreadyExist.NewSubClass("Derived") 88 err := cls.New("Error") 89 90 assert.True(t, err.Is(cls)) 91 assert.False(t, err.Is(ekaerr.AlreadyExist)) 92 93 assert.True(t, err.IsAnyDeep(ekaerr.AlreadyExist)) 94 assert.False(t, err.IsAnyDeep(ekaerr.NotFound)) 95 }