Skip to content

Commit 083ff1c

Browse files
RmbRTboyan-soubachov
authored andcommitted
Fixed didPanic to now detect panic(nil).
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.
1 parent 1e36bfe commit 083ff1c

File tree

2 files changed

+29
-21
lines changed

2 files changed

+29
-21
lines changed

assert/assertions.go

+11-17
Original file line numberDiff line numberDiff line change
@@ -1004,27 +1004,21 @@ func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool {
10041004
type PanicTestFunc func()
10051005

10061006
// didPanic returns true if the function passed to it panics. Otherwise, it returns false.
1007-
func didPanic(f PanicTestFunc) (bool, interface{}, string) {
1008-
1009-
didPanic := false
1010-
var message interface{}
1011-
var stack string
1012-
func() {
1013-
1014-
defer func() {
1015-
if message = recover(); message != nil {
1016-
didPanic = true
1017-
stack = string(debug.Stack())
1018-
}
1019-
}()
1020-
1021-
// call the target function
1022-
f()
1007+
func didPanic(f PanicTestFunc) (didPanic bool, message interface{}, stack string) {
1008+
didPanic = true
10231009

1010+
defer func() {
1011+
message = recover()
1012+
if didPanic {
1013+
stack = string(debug.Stack())
1014+
}
10241015
}()
10251016

1026-
return didPanic, message, stack
1017+
// call the target function
1018+
f()
1019+
didPanic = false
10271020

1021+
return
10281022
}
10291023

10301024
// Panics asserts that the code inside the specified PanicTestFunc panics.

assert/assertions_test.go

+18-4
Original file line numberDiff line numberDiff line change
@@ -923,10 +923,18 @@ func TestCondition(t *testing.T) {
923923

924924
func TestDidPanic(t *testing.T) {
925925

926-
if funcDidPanic, _, _ := didPanic(func() {
927-
panic("Panic!")
928-
}); !funcDidPanic {
929-
t.Error("didPanic should return true")
926+
const panicMsg = "Panic!"
927+
928+
if funcDidPanic, msg, _ := didPanic(func() {
929+
panic(panicMsg)
930+
}); !funcDidPanic || msg != panicMsg {
931+
t.Error("didPanic should return true, panicMsg")
932+
}
933+
934+
if funcDidPanic, msg, _ := didPanic(func() {
935+
panic(nil)
936+
}); !funcDidPanic || msg != nil {
937+
t.Error("didPanic should return true, nil")
930938
}
931939

932940
if funcDidPanic, _, _ := didPanic(func() {
@@ -963,6 +971,12 @@ func TestPanicsWithValue(t *testing.T) {
963971
t.Error("PanicsWithValue should return true")
964972
}
965973

974+
if !PanicsWithValue(mockT, nil, func() {
975+
panic(nil)
976+
}) {
977+
t.Error("PanicsWithValue should return true")
978+
}
979+
966980
if PanicsWithValue(mockT, "Panic!", func() {
967981
}) {
968982
t.Error("PanicsWithValue should return false")

0 commit comments

Comments
 (0)