In Test::Most, I have an "explain" function. This functions just like &Test::More::diag, except it only triggers in verbose mode. Thus, if you run an individual test to see its full output, you see the "explain" dialogue. When you run a full test suite, you don't. It's very handy to keep from having "messy" test suite output.
Now I'm thinking about rewriting it as follows:
sub explain { return unless $ENV{TEST_VERBOSE}; if ( ref $_[0] ) { require Data::Dumper; local $Data::Dumper::Indent = 1; local $Data::Dumper::Sortkeys = 1; Test::More::diag(Data::Dumper::Dumper(@_)); } else { Test::More::diag(@_); } }
In other words, you can forget about using Data::Dumper in your test suites just to diagnose bugs. You can do this:
my $self = Some::Object->new($id); explain $self;
Since we rarely need to print a reference as a string, this seems right, but I wonder if I'm violating some principle of least surprise.
sub explain {
return unless $ENV{TEST_VERBOSE};
Test::More::diag(
map{
ref $_ ? do {
require Data::Dumper;
local $Data::Dumper::Indent = 1;
local $Data::Dumper::Sortkeys = 1;
Data::Dumper::Dumper($_);
} : $_
} @_
);
}
This would allow for nifty stuff like:
my $self = Some::Object->new($id);
explain 'I just created', $self;
Cheers, Sebastian
After something like ten years of Perl, I still expect diag to dumper for me, so you won't be surprising me at all.