[start EDIT]
Yes, you can. See Michael Carman answer.
The initial question title "Is it possible to use a test like Test::More::cmp_ok but that accepts '~~' (smart match operator) with not a scalar at the 'expected' argument?"
was idiotic and with the help of Brian d Foy it has become the current one. You can skip the rest of the question and go for the answers that are also about comparing deep structures.
The origin of this question was my belief that ~~ does not work with array or hashes refs (like keys for hashes) as I was so get use to see ~~ never used with references and the docs always mention @ and %. I got so obfuscated with that, that I made the newbie error of passing an array to a function intending to be a single argument :-( cmp_ok($known_valu, '~~', @returned, 'testing method abc')
. My problem here was not cmp_ok but a better understanding of the smart match operator. The question is rubbish but you can learn good things from the answers.
[end EDIT]
I know that probably this is a 'XY question', so helping me to put the right question (or need) and the hint for the solution would also be appreciated.
The case:
I am testing the return of a function that produces an array. The return could be different depending of the environment but always it would have at least one constant value (the one that I want to test). I want to use a test like is
not the ok
in order to have better test info. As I am using Perl 5.12 and the smart match operator to find if the element is in the array, I can use:
ok($known_value ~~ @returned, 'testing method abc')
But I like the enhanced output of is
or like
with the found and expected part. So I tried the code that seemed more natural to me
cmp_ok($known_valu, '~~', @returned, 'testing method abc')
But it does not work because, seems that cmp_ok expects a scalar in both parts of the comparisons.
not ok 1 - testing method abc
# Failed test 'testing method abc'
# at abc.t line 53.
# 'stable_value'
# ~~
# '2'
The array in the expected slot is evaluated in scalar context and converted to '2'.
This makes sense because if it fails the 'expected' part can not be print
ed but should be print Dumper
and probably this is not in the logic of this method.
I can solve it with a hack using like
and stringifying the array, but having a test where you can use the smart match operator as a comparison method (like when
) would be nice. Does someone know if Test::More can do it? or any other Test package?
At the moment I am using:
ok($known_value ~~ @returned, 'testing method abc')
or diag (
"ERROR:\n".
"Found: ". Dumper @returned."\n".
"Expected at least one element equal to '$known_value'"
)
Is this the best that I can do?