testify
testify copied to clipboard
assert: add PanicsWithErrorIs
I have some code that wraps a database error with fmt.Errorf() and panics it. Now I want to assert that this error is paniced.
The current method PanicsWithError only compares the error message, but does not use a error chain comparison.
Example:
func foo(source err) {
panic(fmt.Errorf("Wrapping error %w", source))
}
func Test(t *testing.T) {
expectedError := errors.New("some error")
require.PanicsWithErrorIs(t, expectedError, func() { foo(expectedError) }) // This functionality is missing
}
Implemented in pull request #1353
@brackendawson You voted this issue down. Do you have a comment?
Just in my opinion; assertions dealing with a specific type of any
may be too much of a reach for the testify API. If any builtin function or standard library panics an error
then I'd be more receptive.
The assertion function ErrorIs is already implemented. So i guess if there was ever a discussion. Someone decided to implement it.
Ad hoc there is no standard library that panics with an error that comes in mind. But at least panicking as well es ErrorIs as well as error wrapping is all part of the standard libraries.
I'll add my five cents. Besides the specified PanicsWithErrorIs
method, I lack the PanicsWithErrorContains()
.
https://go.dev/play/p/-ePsCuCxyW1
import (
"errors"
"fmt"
"testing"
"github.com/stretchr/testify/require"
)
var ErrGoCrazy = errors.New("go crazy")
var GoCrazy = func() { panic(fmt.Errorf("🔫: %w", ErrGoCrazy)) }
func Test_SomePanicWithError(t *testing.T) {
require := require.New(t)
t.Run("must be ok to test panics wrapped errors", func(t *testing.T) {
require.PanicsWithErrorIs( // <— error here ⛔
func() { GoCrazy() },
ErrGoCrazy,
)
})
t.Run("must be ok to test panics error contains string", func(t *testing.T) {
require.PanicsWithErrorContains( // <— error here ⛔
func() { GoCrazy() },
"crazy",
)
})
}