testify
testify copied to clipboard
Nil slice and empty slices fail in .Equal()
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.
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.
When the struct has omitempty on the field, then it does not matter. This is why the workaround works.
Reviving this: if I put up a PR with an EqualOrEmpty(t *testing.T, expected, actual any) function, would that be considered?
Reviving this again. Is it ok if I open this PR?
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