Skip to content

Commit

Permalink
fix: didPanic should detect panic(nil)
Browse files Browse the repository at this point in the history
This is cheery-picked from stretchr/testify#793.

Signed-off-by: tison <wander4096@gmail.com>
Co-authored-by: RmbRT <steffen.rattay@gmail.com>
  • Loading branch information
tisonkun and RmbRT committed Mar 23, 2022
1 parent 8ead291 commit c01eb93
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 18 deletions.
28 changes: 12 additions & 16 deletions assertions.go
Original file line number Diff line number Diff line change
Expand Up @@ -945,25 +945,21 @@ func (a *Assertions) Condition(comp Comparison, msgAndArgs ...any) bool {
type PanicTestFunc func()

// didPanic returns true if the function passed to it panics. Otherwise, it returns false.
func didPanic(f PanicTestFunc) (bool, any, string) {
didPanic := false
var message any
var stack string
func() {

defer func() {
if message = recover(); message != nil {
didPanic = true
stack = string(debug.Stack())
}
}()

// call the target function
f()
func didPanic(f PanicTestFunc) (didPanic bool, message any, stack string) {
didPanic = true

defer func() {
message = recover()
if didPanic {
stack = string(debug.Stack())
}
}()

return didPanic, message, stack
// call the target function
f()
didPanic = false

return
}

// Panics asserts that the code inside the specified PanicTestFunc panics.
Expand Down
16 changes: 14 additions & 2 deletions assertions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -912,9 +912,15 @@ func TestCondition(t *testing.T) {
}

func TestDidPanic(t *testing.T) {
if funcDidPanic, _, _ := didPanic(func() {
if funcDidPanic, msg, _ := didPanic(func() {
panic(nil)
}); !funcDidPanic || msg != nil {
t.Error("didPanic should return true")
}

if funcDidPanic, msg, _ := didPanic(func() {
panic("Panic!")
}); !funcDidPanic {
}); !funcDidPanic || msg != "Panic!" {
t.Error("didPanic should return true")
}

Expand Down Expand Up @@ -943,6 +949,12 @@ func TestPanics(t *testing.T) {
func TestPanicsWithValue(t *testing.T) {
mockAssertion := NewWithOnFailureNoop(new(testing.T))

if !mockAssertion.PanicsWithValue(nil, func() {
panic(nil)
}) {
t.Error("PanicsWithValue should return true")
}

if !mockAssertion.PanicsWithValue("Panic!", func() {
panic("Panic!")
}) {
Expand Down

0 comments on commit c01eb93

Please sign in to comment.