github.com/haraldrudell/parl@v0.4.176/perrors/whynotpanic/why-not-panic_test.go (about) 1 /* 2 © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package whynotpanic 7 8 import ( 9 "errors" 10 "strings" 11 "testing" 12 13 "github.com/haraldrudell/parl/internal/cyclebreaker" 14 "github.com/haraldrudell/parl/perrors/errorglue" 15 "github.com/haraldrudell/parl/pruntime" 16 ) 17 18 func TestWhyNotPanic(t *testing.T) { 19 var errorNilExp = "error-nil: true" 20 var errorNoStackExp = "stacks: 0" 21 var errorStackNoPanicExp = "stacks: 1" 22 23 var s string 24 var errorNil error 25 var errorNoStack = errors.New("errorNoStack") 26 var errorStackNoPanic = errorglue.NewErrorStack(errors.New("errorStackNoPanic"), pruntime.NewStack(0)) 27 var _, isErrorCallStacker = errorStackNoPanic.(errorglue.ErrorCallStacker) 28 var errorIsPanic = recoverPanic1() 29 var errorPanicWithStack = recoverPanic2() 30 31 t.Logf("errorStackNoPanic chain: %d[%s] ErrorCallStacker: %t", 32 len(errorglue.ErrorChainSlice(errorStackNoPanic)), 33 errorglue.DumpChain(errorStackNoPanic), 34 isErrorCallStacker, 35 ) 36 37 // error nil should return error-nil: true 38 s = WhyNotPanic(errorNil) 39 if !strings.Contains(s, errorNilExp) { 40 t.Errorf("nil error not detected: %s", s) 41 } 42 43 // error without stack should return stacks: 0 44 s = WhyNotPanic(errorNoStack) 45 if !strings.Contains(s, errorNoStackExp) { 46 t.Errorf("errorNoStackExp has stacks: %s", s) 47 } 48 49 // error with stack should return stacks: 1 50 s = WhyNotPanic(errorStackNoPanic) 51 if !strings.Contains(s, errorStackNoPanicExp) { 52 t.Errorf("errorNoStackExp has stacks: %s", s) 53 } 54 55 // a recovered panic should return empty string 56 s = WhyNotPanic(errorIsPanic) 57 if s != "" { 58 t.Errorf("errorIsPanic no panic detected: %s", s) 59 } 60 61 // a recovered panic with an error already having a stack 62 // should return empty string 63 s = WhyNotPanic(errorPanicWithStack) 64 if s != "" { 65 t.Errorf("errorPanicWithStack no panic detected: %s", s) 66 } 67 } 68 69 func recoverPanic1() (err error) { 70 defer cyclebreaker.RecoverErr(func() cyclebreaker.DA { return cyclebreaker.A() }, &err) 71 72 panic(1) 73 } 74 75 func recoverPanic2() (err error) { 76 defer cyclebreaker.RecoverErr(func() cyclebreaker.DA { return cyclebreaker.A() }, &err) 77 78 var errorWithStack = errorglue.NewErrorStack(errors.New("errorStackNoPanic"), pruntime.NewStack(0)) 79 panic(errorWithStack) 80 }