go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/assert/it_panics.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package assert
     9  
    10  import "testing"
    11  
    12  // ItPanics is an assertion helper.
    13  //
    14  // It will test that a given function panics using a recovery.
    15  func ItPanics(t *testing.T, fn func(), message ...any) {
    16  	t.Helper()
    17  	var r any
    18  	func() {
    19  		defer func() {
    20  			r = recover()
    21  		}()
    22  		fn()
    23  	}()
    24  	if r == nil {
    25  		Fatalf(t, "expected function to panic", nil, message)
    26  	}
    27  }
    28  
    29  // ItNotPanics is an assertion helper.
    30  //
    31  // It will test that a given function panics using a recovery.
    32  func ItNotPanics[T any](t *testing.T, fn func() T, message ...any) (out T) {
    33  	t.Helper()
    34  	var r any
    35  	func() {
    36  		defer func() {
    37  			r = recover()
    38  		}()
    39  		out = fn()
    40  	}()
    41  	if r != nil {
    42  		Fatalf(t, "expected function not to panic, got %v", []any{r}, message)
    43  	}
    44  	return
    45  }