Thursday, January 14, 2010

TAP That!

TAP (Test Anything Protcol) is Perl's simple test output format for reporting (amongst other things) success & failure of test assertions. This output is what you see printed to screen

ok 1 - Hello
not ok 2 - Nothing right

One thing I wanted to do was to build an object which can be run in two modes
  • As a normal test script (using Test::More)
  • As an object which can assert all tests are good (and confess if anything goes wrong)
So how can I do this? Thankfully Test::More delegates to Test::Builder::new (which is a singleton instance) for its assertion code. The builder has an output method which when passed a scalar reference Test::Builder will write the TAP output to that scalar. Couple this with TAP::Parser we can scan the TAP output and confess accordingly like so.

use Test::Builder;
use Test::More;
use Carp;

my $tap;
my $t = Test::Builder->new->output(\$tap);
ok(1, 'Hello');
fail('FAIL');
done_testing();

my $tap_parser = TAP::Parser->new({
tap => $tap
});

while ( my $result = $tap_parser->next() ) {
if(!$result->is_ok()) {
confess('Error during tests: '.$result->as_string());
}
print $result->as_string(), "\n";
}

Bingo! Now I'm sure there's a module somewhere which already does this but I like how easy this is.

No comments: