github.com/hasnat/dolt/go@v0.0.0-20210628190320-9eb5d843fbb7/libraries/utils/pantoerr/panic_utils_test.go (about) 1 // Copyright 2019 Dolthub, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package pantoerr 16 17 import ( 18 "errors" 19 "testing" 20 ) 21 22 func TestPanicToError(t *testing.T) { 23 errMsg := "error message" 24 panicMsg := "panic message" 25 err := PanicToError(errMsg, func() error { 26 panic(panicMsg) 27 }) 28 29 if err == nil { 30 t.Fatal("Should have an error from the panic") 31 } else if actualErrMsg := err.Error(); actualErrMsg != errMsg { 32 t.Error("Unexpected error message:", actualErrMsg, "does not match expected", errMsg) 33 } else if IsRecoveredPanic(err) { 34 if GetRecoveredPanicCause(err) != panicMsg { 35 t.Error("Unexpected Panic Cause") 36 } 37 } else { 38 t.Error("Recovered panic not of the correct type.") 39 } 40 41 errMsg2 := "other error message" 42 err = PanicToError(errMsg, func() error { 43 return errors.New(errMsg2) 44 }) 45 46 if err == nil { 47 t.Fatal("Should have the error that was returned.") 48 } else if err.Error() != errMsg2 { 49 t.Error("Unexpected error message") 50 } 51 } 52 53 func TestPanicToErrorNil(t *testing.T) { 54 errMsg := "error message" 55 panicMsg := "panic message" 56 err := PanicToErrorNil(errMsg, func() { 57 panic(panicMsg) 58 }) 59 60 if err == nil { 61 t.Fatal("Should have an error from the panic") 62 } else if actualErrMsg := err.Error(); actualErrMsg != errMsg { 63 t.Error("Unexpected error message:", actualErrMsg, "does not match expected", errMsg) 64 } else if IsRecoveredPanic(err) { 65 if GetRecoveredPanicCause(err) != panicMsg { 66 t.Error("Unexpected Panic Cause") 67 } 68 } else { 69 t.Error("Recovered panic not of the correct type.") 70 } 71 72 err = PanicToErrorNil(errMsg, func() { 73 var i int = 0 74 i++ 75 }) 76 77 if err != nil { 78 t.Error("Unexpected error message") 79 } 80 } 81 82 func TestPanicToErrorInstance(t *testing.T) { 83 expected := errors.New("err instance") 84 actual := PanicToErrorInstance(expected, func() error { 85 panic("panic to err instance") 86 }) 87 88 if actual != expected { 89 t.Fatal("Did not receive expected instance") 90 } 91 }