github.com/aristanetworks/goarista@v0.0.0-20240514173732-cca2755bbd44/test/panic.go (about)

     1  // Copyright (c) 2015 Arista Networks, Inc.
     2  // Use of this source code is governed by the Apache License 2.0
     3  // that can be found in the COPYING file.
     4  
     5  package test
     6  
     7  import (
     8  	"fmt"
     9  	"runtime"
    10  	"testing"
    11  )
    12  
    13  // ShouldPanic will test is a function is panicking
    14  func ShouldPanic(t *testing.T, fn func()) {
    15  	t.Helper()
    16  	defer func() {
    17  		t.Helper()
    18  		if r := recover(); r == nil {
    19  			t.Errorf("%sThe function %p should have panicked",
    20  				getCallerInfo(), fn)
    21  		}
    22  	}()
    23  
    24  	fn()
    25  }
    26  
    27  // ShouldPanicWith will test is a function is panicking with a specific message
    28  func ShouldPanicWith(t *testing.T, msg interface{}, fn func()) {
    29  	t.Helper()
    30  	defer func() {
    31  		t.Helper()
    32  		if r := recover(); r == nil {
    33  			t.Errorf("%sThe function %p should have panicked with %#v",
    34  				getCallerInfo(), fn, msg)
    35  		} else if d := Diff(msg, r); len(d) != 0 {
    36  			t.Errorf("%sThe function %p panicked with the wrong message.\n"+
    37  				"Expected: %#v\nReceived: %#v\nDiff:%s",
    38  				getCallerInfo(), fn, msg, r, d)
    39  		}
    40  	}()
    41  
    42  	fn()
    43  }
    44  
    45  // ShouldPanicWithStr a function panics with a specific string.
    46  // If the function panics with an error, the error's message is compared to the string.
    47  func ShouldPanicWithStr(t *testing.T, msg string, fn func()) {
    48  	t.Helper()
    49  	defer func() {
    50  		t.Helper()
    51  		r := recover()
    52  		if r == nil {
    53  			t.Errorf("%sThe function %p should have panicked with %#v",
    54  				getCallerInfo(), fn, msg)
    55  			return
    56  		}
    57  		gotStr, ok := r.(string)
    58  		if !ok {
    59  			gotErr, ok := r.(error)
    60  			if !ok {
    61  				t.Errorf("%sThe function paniced with not string/error: %#v", getCallerInfo(), r)
    62  			}
    63  			gotStr = gotErr.Error()
    64  		}
    65  		if d := Diff(msg, gotStr); len(d) != 0 {
    66  			t.Errorf("%sThe function %p panicked with the wrong message.\n"+
    67  				"Expected: %#v\nReceived: %#v\nDiff:%s",
    68  				getCallerInfo(), fn, msg, gotStr, d)
    69  		}
    70  	}()
    71  	fn()
    72  }
    73  
    74  func getCallerInfo() string {
    75  	_, file, line, ok := runtime.Caller(4)
    76  	if !ok {
    77  		return ""
    78  	}
    79  	return fmt.Sprintf("%s:%d\n", file, line)
    80  }