github.com/Axway/agent-sdk@v1.1.101/pkg/util/exception/exeception_test.go (about) 1 package exception 2 3 import ( 4 "errors" 5 "strings" 6 "testing" 7 8 "github.com/stretchr/testify/assert" 9 ) 10 11 func TestExceptionNoBlock(t *testing.T) { 12 assert.Equal(t, 0, 0) 13 noopException := Block{}.Do 14 assert.NotPanics(t, noopException) 15 16 noCatchBlockException := Block{ 17 Try: func() { 18 Throw(errors.New("some_err")) 19 }, 20 }.Do 21 assert.Panics(t, noCatchBlockException) 22 } 23 24 func TestExceptionTryCatchBlock(t *testing.T) { 25 var catchErr error 26 tryCatchBlockException := Block{ 27 Try: func() { 28 Throw(errors.New("try_catch_err")) 29 }, 30 Catch: func(err error) { 31 catchErr = err 32 }, 33 }.Do 34 35 assert.NotPanics(t, tryCatchBlockException) 36 assert.NotNil(t, catchErr) 37 assert.Equal(t, "try_catch_err", catchErr.Error()) 38 } 39 40 func TestExceptionTryCatchFinallyBlock(t *testing.T) { 41 var catchErr error 42 var executionOrder string 43 tryCatchFinallyBlockException := Block{ 44 Try: func() { 45 executionOrder = "try" 46 Throw(errors.New("try_catch_finally_err")) 47 }, 48 Catch: func(err error) { 49 executionOrder = executionOrder + "catch" 50 catchErr = err 51 }, 52 Finally: func() { 53 executionOrder = executionOrder + "finally" 54 }, 55 }.Do 56 57 assert.NotPanics(t, tryCatchFinallyBlockException) 58 assert.NotNil(t, catchErr) 59 assert.Equal(t, "try_catch_finally_err", catchErr.Error()) 60 assert.Equal(t, "trycatchfinally", executionOrder) 61 } 62 63 func TestExceptionTryCatchBlockWithNPE(t *testing.T) { 64 var catchErr error 65 var executionOrder string 66 tryCatchFinallyBlockException := Block{ 67 Try: func() { 68 executionOrder = "try" 69 b := Block{} 70 b.Try() 71 }, 72 Catch: func(err error) { 73 executionOrder = executionOrder + "catch" 74 catchErr = err 75 }, 76 }.Do 77 78 assert.NotPanics(t, tryCatchFinallyBlockException) 79 assert.NotNil(t, catchErr) 80 assert.Equal(t, strings.Contains(catchErr.Error(), "runtime error: invalid memory address or nil pointer dereference"), true) 81 }