testify icon indicating copy to clipboard operation
testify copied to clipboard

EqualExportedValues panic when struct contains array

Open olitez opened this issue 3 years ago • 1 comments

Hi

package main

import (
	"github.com/stretchr/testify/assert"
)

type Foo struct {
	Array [2]int
}

func main() {
	a := Foo{[2]int{1, 2}}
	b := Foo{[2]int{2, 1}}
	assert.EqualExportedValues(nil, a, b)
}

Will panic with "panic: reflect.MakeSlice of non-slice type"

Reason is there in assertion.go:113 :

case reflect.Array, reflect.Slice:
	result := reflect.MakeSlice(expectedType, expectedValue.Len(), expectedValue.Len())

reflect.MakeSlice only work with slice, not with Array. Fix could be follow:

case reflect.Array, reflect.Slice:
	result := reflect.New(expectedType).Elem()
	if expectedKind == reflect.Slice {
		result = reflect.MakeSlice(expectedType, expectedValue.Len(), expectedValue.Len())
	}

Or even carry reflect.Array to different switch case

olitez avatar Jun 21 '23 12:06 olitez

Confirmed. https://go.dev/play/p/0ZWBaOHwqjZ

Simpler: https://go.dev/play/p/Rxk9Z1Cvsx9

dolmen avatar Jul 05 '23 13:07 dolmen