github.com/packtpublishing/learning-functional-programming-in-go@v0.0.0-20230130084745-8b849f6d58c4/Chapter06/04_onion/src/utils/utils_test/utils_test.go (about)

     1  package utils_test
     2  
     3  import (
     4  	"testing"
     5  	"utils"
     6  	"github.com/pkg/errors"
     7  	"os"
     8  )
     9  
    10  func TestPanic(t *testing.T) {
    11  	defer func() {
    12  		if r := recover(); r == nil {
    13  			t.Errorf("Expected to see a panic")
    14  		}
    15  	}()
    16  	filePanicFcn()
    17  }
    18  
    19  func TestPanic2(t *testing.T) {
    20  	assertPanic(t, filePanicFcn)
    21  }
    22  
    23  func TestPanic3(t *testing.T) {
    24  	assertPanic(t, zeroPanicFcn)
    25  }
    26  
    27  
    28  // -------------
    29  //    Helpers
    30  // -------------
    31  
    32  func assertPanic(t *testing.T, f func()) {
    33  	defer func() {
    34  		if r := recover(); r == nil {
    35  			t.Errorf("Expected to see a panic")
    36  		}
    37  	}()
    38  	f()
    39  }
    40  
    41  func filePanicFcn() {
    42  	_, err := os.Open("doesnot-exist.txt")
    43  	if err != nil {
    44  		utils.HandlePanic(errors.Wrap(err, "unable to read file"))
    45  	}
    46  }
    47  
    48  func divFcn(d int) error {
    49  	if d == 0 {
    50  		return errors.New("divide by 0 attempted")
    51  	}
    52  	return nil
    53  }
    54  
    55  func zeroPanicFcn() {
    56  	err := divFcn(0)
    57  	if err != nil {
    58  		utils.HandlePanic(err)
    59  	}
    60  }