http://www.perlmonks.org?node_id=1135609


in reply to Re: Diagnostic messages in Test::Deep
in thread Diagnostic messages in Test::Deep

yes, the array can be populated in random order :-).

The data set is slightly different than your example. The keys for each hash within the test run are the same. They differ between runs/tests.

Test 1 sample.

$got = [ { key_1 => "A", key_2 => "CC"} , { key_1 => "B", key_2 => "CC"} ] $expected = [ { key_1 => "B", key_2 => "CC"} , { key_1 => "A", key_2 => "CC"} ]

I want these to evaluate as equal, and they do with code like this (similar to yours):

return is deeply ( $got ? [ sort {$a->{key_1} cmp $b->{key_1}} $got ] : [] , $expected ? [ sort {$a->{key_1} cmp $b->{key_1}} $expected ] : [] , "Test array of hashes"

(the ternary operator is there because "no data returned" is also a valid/possible response).

The problem arises with Test 2 which has the following data:

$got = [ { key_3 => "A", key_2 => "CC"} , { key_3 => "B", key_2 => "CC"} ] $expected = [ { key_3 => "B", key_2 => "CC"} , { key_3 => "A", key_2 => "CC"} ]

The problem is the sorting key name has changed from 'key_1' to 'key_3' so my sort:

sort {$a->{key_1} cmp $b->{key_1}}

fails on the second data set. I could pass in the key names as variables, but was hoping to avoid that, especially since Test::Deep->bag() does exactly what I want.

The working Test::Deep code looks like this:

return = cmp_deeply ( $got ? [ $got ] : [] , bag ( $expected ? $expected : () ) );

(different brackets on bag due to return type, I need to double check that...)

So Test::Deep->bag() works for me because it does magic I don't have to when deciding how to sort the second array.

Robert Kuropkat