go.undefinedlabs.com/scopeagent@v0.4.2/reflection/panic_handler_test.go (about)

     1  package reflection_test
     2  
     3  import (
     4  	"sync"
     5  	"sync/atomic"
     6  	"testing"
     7  
     8  	_ "go.undefinedlabs.com/scopeagent/autoinstrument"
     9  	"go.undefinedlabs.com/scopeagent/reflection"
    10  )
    11  
    12  func TestPanicHandler(t *testing.T) {
    13  	var panicHandlerVisit int32
    14  
    15  	reflection.AddPanicHandler(func(e interface{}) {
    16  		t.Log("PANIC HANDLER FOR:", e)
    17  		atomic.AddInt32(&panicHandlerVisit, 1)
    18  	})
    19  
    20  	t.Run("OnPanic", func(t2 *testing.T) {
    21  		var wg = new(sync.WaitGroup)
    22  		wg.Add(1)
    23  
    24  		go func() {
    25  			defer func() {
    26  				if r := recover(); r != nil {
    27  					t.Log("PANIC RECOVERED")
    28  				}
    29  				wg.Done()
    30  			}()
    31  
    32  			t.Log("PANICKING!")
    33  			panic("Panic error")
    34  
    35  		}()
    36  
    37  		wg.Wait()
    38  	})
    39  
    40  	if atomic.LoadInt32(&panicHandlerVisit) != 1 {
    41  		t.Fatalf("panic handler should be executed once.")
    42  	}
    43  }