github.com/hoop33/elvish@v0.0.0-20160801152013-6d25485beab4/util/exception_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 TestException(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  }