testify icon indicating copy to clipboard operation
testify copied to clipboard

assert: add PanicsWithErrorIs

Open jannisbaudisch opened this issue 1 year ago • 5 comments

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
}

jannisbaudisch avatar Feb 27 '23 22:02 jannisbaudisch

Implemented in pull request #1353

jannisbaudisch avatar Feb 27 '23 23:02 jannisbaudisch

@brackendawson You voted this issue down. Do you have a comment?

dolmen avatar Jul 05 '23 15:07 dolmen

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.

brackendawson avatar Jul 10 '23 14:07 brackendawson

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.

jannisbaudisch avatar Jul 18 '23 18:07 jannisbaudisch

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",
		)
	})
}

mail2nnv avatar Oct 19 '23 14:10 mail2nnv