github.com/jxskiss/gopkg@v0.17.3/easy/recover_test.go (about)

     1  package easy
     2  
     3  import (
     4  	"errors"
     5  	"log"
     6  	"strings"
     7  	"sync"
     8  	"testing"
     9  
    10  	"github.com/stretchr/testify/assert"
    11  )
    12  
    13  var _ = log.Println
    14  
    15  var wantPanicLoc string
    16  
    17  func willPanic() {
    18  	wantPanicLoc = "gopkg/easy.willPanic:18"
    19  	panic("oops...")
    20  }
    21  
    22  func willPanicCaller() {
    23  	willPanic()
    24  }
    25  
    26  func TestIdentifyPanicLoc(t *testing.T) {
    27  	var panicLoc1 string
    28  	func() {
    29  		defer func() {
    30  			recover()
    31  			panicLoc1 = IdentifyPanic()
    32  		}()
    33  		willPanic()
    34  	}()
    35  	assert.True(t, strings.HasSuffix(panicLoc1, wantPanicLoc))
    36  
    37  	var panicLoc2 string
    38  	func() {
    39  		defer func() {
    40  			recover()
    41  			panicLoc2 = IdentifyPanic()
    42  		}()
    43  		willPanicCaller()
    44  	}()
    45  	assert.True(t, strings.HasSuffix(panicLoc2, wantPanicLoc))
    46  }
    47  
    48  type syncLogger struct {
    49  	bufLogger
    50  	wg sync.WaitGroup
    51  }
    52  
    53  func (p *syncLogger) Errorf(format string, args ...interface{}) {
    54  	p.bufLogger.Errorf(format, args...)
    55  	p.wg.Done()
    56  }
    57  
    58  func TestGoroutineRecover(t *testing.T) {
    59  	var logger = &syncLogger{}
    60  	configTestLog(false, logger, nil)
    61  
    62  	logger.wg.Add(1)
    63  	Go(func() { willPanic() })
    64  	logger.wg.Wait()
    65  	logText := logger.buf.String()
    66  	assert.Contains(t, logText, "catch panic:")
    67  	assert.Contains(t, logText, "gopkg/easy.TestGoroutineRecover")
    68  
    69  	logger.buf.Reset()
    70  	logger.wg.Add(1)
    71  	Go1(func() error {
    72  		willPanicCaller()
    73  		return nil
    74  	})
    75  	logger.wg.Wait()
    76  	logText = logger.buf.String()
    77  	assert.Contains(t, logText, "catch panic:")
    78  	assert.Contains(t, logText, "gopkg/easy.TestGoroutineRecover")
    79  
    80  	logger.buf.Reset()
    81  	logger.wg.Add(1)
    82  	Go1(func() error {
    83  		return errors.New("dummy error")
    84  	})
    85  	logger.wg.Wait()
    86  	logText = logger.buf.String()
    87  	assert.Contains(t, logText, "catch error:")
    88  	assert.Contains(t, logText, "dummy error")
    89  }
    90  
    91  func TestPanicOnError(t *testing.T) {
    92  	panicErr := errors.New("dummy panic error")
    93  	willPanic := func() (int, error) {
    94  		return 123, panicErr
    95  	}
    96  
    97  	x, gotErr := willPanic()
    98  	assert.PanicsWithValue(t, panicErr, func() {
    99  		PanicOnError(x, gotErr)
   100  	})
   101  
   102  	assert.PanicsWithValue(t, panicErr, func() {
   103  		PanicOnError(willPanic())
   104  	})
   105  }