Calling All Test:: Authors

Ovid on 2009-06-30T14:16:11

The latest developer release of Test::More allows subtests. Subtests are great in that they solve a lot of problems in advanced Perl testing, but they have required a change in Test::Builder. Previously you could do stuff like this:

package Test::StringReverse;

use base 'Test::Builder::Module';
our @EXPORT = qw(is_reversed);

my $BUILDER = Test::Builder->new;

sub is_reversed ($$;$) {
    my ( $have, $want, $name ) = @_;

    my $passed = $want eq scalar reverse $name;

    $BUILDER->ok($passed, $name);
    $BUILDER->diag(<<"    END_DIAG") if not $passed;
    have: $have
    want: $want
    END_DIAG

    return $passed;
}

1;

And you've have a simple (untested ;) test for whether or not strings are reversed.

The reason that worked is that Test::Builder->new used to return a singleton. This is no longer true. If someone uses your test library in a subtest, the above code would break. Instead, you want to do this:

sub is_reversed ($$;$) {
    my ( $have, $want, $name ) = @_;

    my $passed  = $want eq scalar reverse $name;
    my $builder = __PACKAGE__->builder;

    $builder->ok($passed, $name);
    $builder->diag(<<"    END_DIAG") if not $passed;
    have: $have
    want: $want
    END_DIAG

    return $passed;
}

It's a minor change, it's completely backwards-compatible and it supports subtests. There's a work-around being planned, but it's not out there yet.


List of dists with this bug

dagolden on 2009-06-30T15:24:13

Running visitcpan against my mini CPAN repo and searching for "Test::Builder->new" in a perl file in the lib directory revealed 182 hits. (Some are certainly false-positives, like Test-Simple itself.)

List is online here.

-- dagolden

Re:List of dists with this bug

Ovid on 2009-06-30T15:37:35

That looks sweet!

Could you post the exact incantation you used with visitcpan? I'd like to steal some ideas.

Re:List of dists with this bug

dagolden on 2009-06-30T15:48:36

It doesn't ignore Test::Bulder->new within subroutines -- this is an ack search so you get anything that uses that code at all. You'd need PPI for something more sophisticated.

I ran:

visitcpan -q -a dist ~/git/sandbox/visitcpan/scan-test-builder-new | tee t-b-new

See also scan-test-builder-new for the actual script run in each distribution directory

Re:List of dists with this bug

chorny on 2009-07-01T07:44:33

Test::Warn is not in the list, because dist has no lib directory, only Warn.pm.