Skip to content

Commit 5c61ef9

Browse files
mvrahdenboyan-soubachov
authored andcommitted
fix potential nil-pointer dereference
the fix gracefully fails the assertion instead of panicking unresolved.
1 parent e209ca8 commit 5c61ef9

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

assert/assertions.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -721,7 +721,11 @@ func NotEqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...inte
721721
func includeElement(list interface{}, element interface{}) (ok, found bool) {
722722

723723
listValue := reflect.ValueOf(list)
724-
listKind := reflect.TypeOf(list).Kind()
724+
listType := reflect.TypeOf(list)
725+
if listType == nil {
726+
return false, false
727+
}
728+
listKind := listType.Kind()
725729
defer func() {
726730
if e := recover(); e != nil {
727731
ok = false

assert/assertions_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -592,6 +592,7 @@ func TestContainsNotContains(t *testing.T) {
592592
{"j", "k"},
593593
}
594594
simpleMap := map[interface{}]interface{}{"Foo": "Bar"}
595+
var zeroMap map[interface{}]interface{}
595596

596597
cases := []struct {
597598
expected interface{}
@@ -606,6 +607,7 @@ func TestContainsNotContains(t *testing.T) {
606607
{complexList, &A{"g", "e"}, false},
607608
{simpleMap, "Foo", true},
608609
{simpleMap, "Bar", false},
610+
{zeroMap, "Bar", false},
609611
}
610612

611613
for _, c := range cases {
@@ -652,6 +654,22 @@ func TestContainsFailMessage(t *testing.T) {
652654
}
653655
}
654656

657+
func TestContainsNotContainsOnNilValue(t *testing.T) {
658+
mockT := new(mockTestingT)
659+
660+
Contains(mockT, nil, "key")
661+
expectedFail := "<nil> could not be applied builtin len()"
662+
actualFail := mockT.errorString()
663+
if !strings.Contains(actualFail, expectedFail) {
664+
t.Errorf("Contains failure should include %q but was %q", expectedFail, actualFail)
665+
}
666+
667+
NotContains(mockT, nil, "key")
668+
if !strings.Contains(actualFail, expectedFail) {
669+
t.Errorf("Contains failure should include %q but was %q", expectedFail, actualFail)
670+
}
671+
}
672+
655673
func TestSubsetNotSubset(t *testing.T) {
656674

657675
// MTestCase adds a custom message to the case

0 commit comments

Comments
 (0)