views:

90

answers:

2

I have a Perl test script written using Test::More. Right before exiting, and if all tests passed, I'd like to perform some cleanup actions. If any tests failed, I want to leave everything in place for troubleshooting.

Is there a flag within Test::More, or some other best practice within a single test script, to tell if "all is well" once the tests themselves are complete?

+10  A: 

You can access the current status of the tests with Test::Builder, available via Test::More->builder:

use strict;
use warnings;
use Test::More tests => 1;

ok(int rand 2, 'this test randomly passes or fails');

if (Test::More->builder->is_passing)
{
    print "hooray!\n";
}
else
{
    print "aw... :(\n";
}

Alternatively, you can just do your cleanup at the end of the script, but exit early if things go awry, with Test::More's BAIL_OUT("reason why you are bailing");.

There's lots of other data and statistics you can gather about the state of your tests; see the documentation for Test::Builder.

Ether
I've got Can't locate object method "is_passing" via package "Test::Builder" at ./put.pl line 9.with Perl v5.8.4 with 31 registered patches (on Solaris 10) :o(
philippe
I got this too with Test::More version 0.8, but had better luck with Test::More version 0.93 .
mobrule
Test::Builder->is_passing() was added in version 0.89_01, see the CHANGES file: http://cpansearch.perl.org/src/MSCHWERN/Test-Simple-0.94/Changes
Ether
A: 

Here is what I came up to in order to avoid the "Can't locate object method" error shown at the bottom of this answer :

#! /usr/bin/perl 

use strict;
use warnings;
use Test::More tests => 1;

ok(int rand 2, 'this test randomly passes or fails');

my $FAILcount = 0;
foreach my $detail (Test::Builder->details()) {
    if (${%$detail}{ok}==0) { $FAILcount++; }
}

if ($FAILcount == 0) {
    print "hooray!\n";
} else {
    print "aw... :(\n";
}

On Solaris 10, with Perl v5.8.4 (with 31 registered patches), I got the following

Can't locate object method "is_passing" via package "Test::Builder"
philippe
You need to upgrade your Test::Simple distribution - see the notes in the other answer.
Ether
I know you're under Solaris, but on ActivePerl upgrading Test::Simple is the way. Test::Builder doesn't have its own PPM entry in my Win32 5.10 installation. It took me a few minutes to track down so maybe this note will save someone else the time.
aczarnowski