Using Test::* modules outside of a TAP context
Jul 19, 2010 / By Yanick Champoux
I totally blame Tim Bunce for this one.
You see, I was happily minding my business today, until I got sight of Tim’s tweet bemoaning the fact that Test::Difference tests can’t easily be used outside of a test harness. Darn him, that’s exactly the kind of happy little puzzle I can’t resist.
So I began to think about it. Of course, the Right Solution is probably to add alternative non-TAP-tied functions to the test modules themselves. But what if you just want to quickly leverage the module’s functionality without having to re-arrange its innards? Well, most test modules use
Test::Builder, so there’s surely ways to twist that to our advantage. After a hour or two of hacking, I think I got one.
My little experience is named
Test::Wrapper, and as usual can be found on github. In a nutshell,
Test::Wrapper takes the tests that you want to use and gleefully bastardize the underlaying
Test::Builder mechanisms such that nothing is output. Instead, the tests return an object that contains it all.
For example, if we want to use
Test::Differences, we can do
use 5.10.0; use Test::Differences; use Test::Wrapper qw/ eq_or_diff /; my $test = eq_or_diff "foo" => "bar"; say $test->is_success ? 'pass' : 'fail'; # yes! prints the whole diff table say "output: ", $test->diag; # also come with overloading voodoo say $test ? 'pass' : 'fail'; say "output: $test";
As mentioned above, this comes with the price of totally messing up with
Test::Builder, so using it intermixed with “real” tests is not an option. And it has doubtlessly a thousand gotchas I didn’t think about. But, still, I must say that I like it despite (or because) its devious hijacking nature. I might even push it to CPAN it if proves to be useful to anyone (myself included).
One Response to “Using Test::* modules outside of a TAP context”
Leave a Reply