Today's handy testing trick

petdance on 2004-04-09T20:50:50

Say you have a test that wants to compare two big multi-line text strings, like web pages. You can do this:

is( $wanted, $actual, "Pages match" );

but if they don't match, then you have mile-long "expected X, got Y" output. That's no fun.

So do this:

is_deeply( [split /\n/, $wanted], [split /\n/, $actual], "Pages match" );

Now, it'll show what the first different line is. Much easier to debug, because the output is like this: not ok 13 - Pages match # Failed test (t/cached.t at line 54) # Structures begin differing at: # $got->[48] = '15:46:02
' # $expected->[48] = '15:45:58
'

In fact, I think I may have to submit a is_multiline function to Test::More that is a wrapper around it. sub is_multiline { my $got = shift; my $expected = shift; my $msg = shift;

return is_deeply( [split /\n/, $got], [split /\n/, $expected], $msg ); }
Schwern, whaddya think?


Sweet!

ajtaylor on 2004-04-10T01:21:25

I had run into that problem myself when testing the contents of dynamically generated PDF files (before I turned on compression thus removing the plain text from the file). The failed is() spaghetti is even worse w/ PDF content. Ask me how I know. :-)

Test::Differences?

Adrian on 2004-04-10T01:23:00

Would be what I'd use :-)