github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+incompatible/cmds/core/elvish/util/throw_test.go (about) 1 package util 2 3 import ( 4 "errors" 5 "testing" 6 ) 7 8 func recoverPanic(f func()) (recovered interface{}) { 9 defer func() { 10 recovered = recover() 11 }() 12 f() 13 return nil 14 } 15 16 func TestThrowAndCatch(t *testing.T) { 17 tothrow := errors.New("an error to throw") 18 // Throw should cause a panic 19 f := func() { 20 Throw(tothrow) 21 } 22 if recoverPanic(f) == nil { 23 t.Errorf("Throw did not cause a panic") 24 } 25 26 // Catch should catch what was thrown 27 caught := func() (err error) { 28 defer Catch(&err) 29 Throw(tothrow) 30 return nil 31 }() 32 if caught != tothrow { 33 t.Errorf("thrown %v, but caught %v", tothrow, caught) 34 } 35 36 // Catch should not recover panics not caused by Throw 37 var err error 38 f = func() { 39 defer Catch(&err) 40 panic(errors.New("233")) 41 } 42 _ = recoverPanic(f) 43 if err != nil { 44 t.Errorf("Catch recovered panic not caused via Throw") 45 } 46 47 // Catch should do nothing when there is no panic 48 err = nil 49 f = func() { 50 defer Catch(&err) 51 } 52 f() 53 if err != nil { 54 t.Errorf("Catch recovered something when there is no panic") 55 } 56 } 57 58 // errToThrow is the error to throw in test cases. 59 var errToThrow = errors.New("error to throw") 60 61 func TestPCall(t *testing.T) { 62 // PCall catches throws 63 if PCall(func() { Throw(errToThrow) }) != errToThrow { 64 t.Errorf("PCall does not catch throws") 65 } 66 // PCall returns nil when nothing has been thrown 67 if PCall(func() {}) != nil { 68 t.Errorf("PCall returns non-nil when nothing has been thrown") 69 } 70 // PCall returns nil when nil has been thrown 71 if PCall(func() { Throw(nil) }) != nil { 72 t.Errorf("PCall returns non-nil when nil has been thrown") 73 } 74 } 75 76 func TestThrows(t *testing.T) { 77 if Throws(func() { Throw(errToThrow) }, errToThrow) != true { 78 t.Errorf("Throws returns false when function throws wanted error") 79 } 80 if Throws(func() { Throw(errToThrow) }, errors.New("")) != false { 81 t.Errorf("Throws returns true when function throws unwanted error") 82 } 83 if Throws(func() {}, errToThrow) != false { 84 t.Errorf("Throws returns true when function does not throw") 85 } 86 } 87 88 func TestThrowsAny(t *testing.T) { 89 if ThrowsAny(func() { Throw(errToThrow) }) != true { 90 t.Errorf("ThrowsAny returns false when function throws non-nil") 91 } 92 if ThrowsAny(func() {}) != false { 93 t.Errorf("ThrowsAny returns true when function does not throw") 94 } 95 } 96 97 func TestDoesnotThrow(t *testing.T) { 98 if DoesntThrow(func() { Throw(errToThrow) }) != false { 99 t.Errorf("DoesntThrow returns true when function throws") 100 } 101 if DoesntThrow(func() {}) != true { 102 t.Errorf("DoesntThrow returns false when function doesn't throw") 103 } 104 }