Skip to content

Commit

Permalink
Fixed didPanic to now detect panic(nil).
Browse files Browse the repository at this point in the history
Previously, the function would not detect panic(nil) calls.
In didPanic, removed the anonymous function call, instead,
added named return values. Added extra test cases for the
panic(nil) call.
  • Loading branch information
RmbRT committed Jul 26, 2019
1 parent 221dbe5 commit a6f8d2c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 21 deletions.
24 changes: 7 additions & 17 deletions assert/assertions.go
Original file line number Diff line number Diff line change
Expand Up @@ -901,25 +901,15 @@ func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool {
type PanicTestFunc func()

// didPanic returns true if the function passed to it panics. Otherwise, it returns false.
func didPanic(f PanicTestFunc) (bool, interface{}) {
func didPanic(f PanicTestFunc) (didPanic bool, message interface{}) {
didPanic = true

didPanic := false
var message interface{}
func() {

defer func() {
if message = recover(); message != nil {
didPanic = true
}
}()

// call the target function
f()

}()

return didPanic, message
defer func() { message = recover() }()
// call the target function
f()
didPanic = false

return
}

// Panics asserts that the code inside the specified PanicTestFunc panics.
Expand Down
22 changes: 18 additions & 4 deletions assert/assertions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -730,10 +730,18 @@ func TestCondition(t *testing.T) {

func TestDidPanic(t *testing.T) {

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

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

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

if funcDidPanic, _ := didPanic(func() {
Expand Down Expand Up @@ -770,6 +778,12 @@ func TestPanicsWithValue(t *testing.T) {
t.Error("PanicsWithValue should return true")
}

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

if PanicsWithValue(mockT, "Panic!", func() {
}) {
t.Error("PanicsWithValue should return false")
Expand Down

0 comments on commit a6f8d2c

Please sign in to comment.