Skip to content

Commit 4d0daaa

Browse files
committed
fix: panic in spew when dealing with unexported fields
1 parent 3987752 commit 4d0daaa

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

assert/assertions_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -837,6 +837,39 @@ func TestEqualFormatting(t *testing.T) {
837837
}
838838
}
839839

840+
func TestEqualFormattingWithPanic(t *testing.T) {
841+
t.Parallel()
842+
843+
type structWithUnexportedMapWithArrayKey struct {
844+
m interface{}
845+
}
846+
847+
for _, c := range []struct {
848+
a interface{}
849+
b interface{}
850+
}{
851+
{
852+
// from the issue https://github.com/stretchr/testify/pull/1816
853+
a: structWithUnexportedMapWithArrayKey{
854+
map[[1]byte]*struct{}{
855+
{1}: nil,
856+
{2}: nil,
857+
},
858+
},
859+
b: structWithUnexportedMapWithArrayKey{},
860+
},
861+
} {
862+
863+
mockT := new(mockTestingT)
864+
NotPanics(t, func() {
865+
Equal(mockT, c.a, c.b)
866+
}, "should not panic")
867+
868+
True(t, mockT.Failed(), "should have failed")
869+
Contains(t, mockT.errorString(), "Not equal:", "error message should mention inequality")
870+
}
871+
}
872+
840873
func TestFormatUnequalValues(t *testing.T) {
841874
t.Parallel()
842875

internal/spew/common.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,12 @@ func valueSortLess(a, b reflect.Value) bool {
312312
for i := 0; i < l; i++ {
313313
av := a.Index(i)
314314
bv := b.Index(i)
315+
316+
if !av.CanInterface() || !bv.CanInterface() {
317+
// Unexported fields would panic on Interface() call.
318+
continue
319+
}
320+
315321
if av.Interface() == bv.Interface() {
316322
continue
317323
}

0 commit comments

Comments
 (0)