testify icon indicating copy to clipboard operation
testify copied to clipboard

Compare structs with unsorted slices

Open LawYard opened this issue 5 years ago • 9 comments

Hi! Are here any assert func to compare two struct contains same slices with the same elements but in differs order?

For example:

type Test struct {
    Names []string
}

c1 := Test{
    Names: []string{ "Joe", "Rick" }
}

c2 := Test{
    Names: []string{ "Rick", "Joe" }
}

I need some func that can compare that two structs ignoring slice elems order in it.

LawYard avatar Aug 20 '19 21:08 LawYard

It would also be amazing if we we could compare 2 json-strings this way - almost like JsonEq, but using ElementsMatch when comparing slices. We could name this new method JsonContentsMatch or something along these lines.

Example usage:


expectedEvent := `{
"participants": ["Joe", "Rick"], 
"event": "Birthday party"
}`

actualEvent := `{
"event": "Birthday party",
"participants": ["Rick", "Joe"]
}`

assert.JsonContentsMatch(t, expectedEvent, actualEvent)

galecore avatar Aug 21 '19 10:08 galecore

Is it in the raodmap?

dharmjit avatar Feb 07 '20 10:02 dharmjit

We can certainly add it. I'm going to spruce up the milestones this morning, I'll slot this in.

glesica avatar Feb 07 '20 15:02 glesica

Hey @glesica just checking if this got added to the milestones? It would be an incredibly useful feature

alexrudd avatar Mar 25 '20 17:03 alexrudd

I just ran into this with a slice nested down inside some structs. I'm using assert.EqualValues on the structs and the assertion starts to fail when the slice order differs, which gets annoying in my case that conditionally adds values to the slice in question.

i have the same problem。assert.EqualValues use reflect.DeepEqual , it's hard to do what i want

ShitaoFu avatar Nov 25 '22 10:11 ShitaoFu

This use case seems to be addressed by the assertions.ElementsMatch method.

image

https://pkg.go.dev/github.com/stretchr/testify/assert?utm_source=godoc#ElementsMatch

mchlp avatar Nov 28 '22 00:11 mchlp

@mchlp Yes and no...

It does solve it in the case the OP presented.


Now imagine you have struct, with 20+ fields. And one of those fields is a slice. You cannot write:

assert.Equal(t, expectedResponse, receivedResponse)

But you have write:

assert.Equal(t, expectedResponse.field1, receivedResponse.field1)
assert.Equal(t, expectedResponse.field2, receivedResponse.field2)
...
assert.ElementsMatch(t, expectedResponse.field20, receivedResponse.field20)

And this is only the simple case without any nesting....

If I have to write this all out by hand, why am I even using an assertion library?

lordzsolt avatar Jan 24 '23 10:01 lordzsolt

Potentially could be addressed by: https://github.com/stretchr/testify/issues/843#issuecomment-1952362012

brackendawson avatar Mar 03 '24 23:03 brackendawson