testify icon indicating copy to clipboard operation
testify copied to clipboard

Nil slice and empty slices fail in .Equal()

Open mitar opened this issue 3 years ago • 5 comments

This is reasonable. But when one obtains slices from JSON you can quickly get nil slices or empty slices where it does not matter which one it is. It would be great if there were some way or some alternative Equal function which would see nil slices and empty slices as the same.

Current workaround I use is to marshal objects into JSON and then compare using JSONEq, but that works only for objects which as a whole are nicely serialized into JSON. But it can happen that objects I want to compare only partially came form JSON in the first place.

mitar avatar Jan 06 '22 10:01 mitar

I would say that it does matter which one it is when you are testing JSON, consider this failing test:

func TestTestify(t *testing.T) {
	json1, err := json.Marshal([]int{})
	require.NoError(t, err)
	json2, err := json.Marshal([]int(nil))
	require.NoError(t, err)
	require.JSONEq(t, string(json1), string(json2))
}

The JSON [] is not the same as the JSON null, and I think a test should be explicit about which of the two you are dealing with so that you don't inadvertently change your API in a subtle way which could break other consumers of your JSON.

brackendawson avatar Jan 06 '22 13:01 brackendawson

When the struct has omitempty on the field, then it does not matter. This is why the workaround works.

mitar avatar Jan 06 '22 14:01 mitar

Reviving this: if I put up a PR with an EqualOrEmpty(t *testing.T, expected, actual any) function, would that be considered?

fdegiuli avatar Mar 30 '23 23:03 fdegiuli

Reviving this again. Is it ok if I open this PR?

srdtrk avatar Jan 09 '24 10:01 srdtrk

Ah sorry, I dropped the ball on this, I don't get notifications for the thumbs up. Go for it, I'm happy to review

fdegiuli avatar Jan 09 '24 19:01 fdegiuli