# $^C was only introduced in 5.005-ish. We do this to prevent
# use of uninitialized value warnings in older perls.
use vars
qw($VERSION $CLASS);
my $IsVMS = $^O eq 'VMS';
# Make Test::Builder thread-safe for ithreads.
if( $] >= 5.008 && $Config{useithreads} ) {
Test::Builder - Backend for building test libraries
package My::Test::Module;
my $Test = Test
::Builder
->new;
$Test->output('my_logfile');
$Test->exported_to($pack);
$self->export_to_level(1, $self, 'ok');
Test::Simple and Test::More have proven to be popular testing modules,
but they're not always flexible enough. Test::Builder provides the a
building block upon which to write your own test libraries I<which can
my $Test = Test::Builder->new;
Returns a Test::Builder object representing the current state of the
Since you only run one test per program, there is B<one and only one>
Test::Builder object. No matter how many times you call new(), you're
getting the same object. (This is called a singleton).
$Test ||= bless ['Move along, nothing to see here'], $class;
These methods are for setting up tests and declaring how many there
are. You usually only want to call one of these methods.
my $pack = $Test->exported_to;
$Test->exported_to($pack);
Tells Test::Builder what package you exported your functions to.
This is important for getting TODO tests right.
$Test->plan( skip_all => $reason );
$Test->plan( tests => $num_tests );
A convenient way to set up your tests. Call this and Test::Builder
will print the appropriate headers and take the appropriate actions.
If you call plan(), don't call any of the other methods below.
my($self, $cmd, $arg) = @_;
die sprintf "You tried to plan twice! Second plan at %s line %d\n",
if( $cmd eq 'no_plan' ) {
elsif( $cmd eq 'skip_all' ) {
return $self->skip_all($arg);
elsif( $cmd eq 'tests' ) {
return $self->expected_tests($arg);
die "Got an undefined number of tests. Looks like you tried to ".
"say how many tests you plan to run but made a mistake.\n";
die "You said to run 0 tests! You've got to run something.\n";
my @args = grep { defined } ($cmd, $arg);
Carp
::croak
("plan() doesn't understand @args");
my $max = $Test->expected_tests;
$Test->expected_tests($max);
Gets/sets the # of tests we expect this test to run and prints out
$self->_print("1..$max\n") unless $self->no_header;
Declares that this test will run an indeterminate # of tests.
$Test->skip_all($reason);
Skips all the tests, using the given $reason. Exits immediately with 0.
$out .= " # Skip $reason" if $reason;
$self->_print($out) unless $self->no_header;
These actually run the tests, analogous to the functions in
$name is always optional.
Your basic test. Pass if $test is true, fail if $test is false. Just
like Test::Simple's ok().
my($self, $test, $name) = @_;
Carp
::croak
("You tried to run a test without a plan! Gotta have a plan.");
$self->diag(<<ERR) if defined $name and $name =~ /^[\d\s]+$/;
You named your test '$name'. You shouldn't use numbers for your test names.
my($pack, $file, $line) = $self->caller;
my $todo = $self->todo($pack);
$Test_Results[$Curr_Test-1] = $todo ?
1 : 0;
$Test_Results[$Curr_Test-1] = 1;
$out .= " $Curr_Test" if $self->use_numbers;
$name =~ s
|#|\\#|g; # # in a name can confuse Test::Harness.
$out .= " # TODO $what_todo";
my $msg = $todo ?
"Failed (TODO)" : "Failed";
$self->diag(" $msg test ($file at line $line)\n");
$Test->is_eq($got, $expected, $name);
Like Test::More's is(). Checks if $got eq $expected. This is the
$Test->is_num($got, $expected, $name);
Like Test::More's is(). Checks if $got == $expected. This is the
my($self, $got, $expect, $name) = @_;
local $Level = $Level + 1;
if( !defined $got || !defined $expect ) {
# undef only matches undef and nothing else
my $test = !defined $got && !defined $expect;
$self->_is_diag($got, 'eq', $expect) unless $test;
return $self->cmp_ok($got, 'eq', $expect, $name);
my($self, $got, $expect, $name) = @_;
local $Level = $Level + 1;
if( !defined $got || !defined $expect ) {
# undef only matches undef and nothing else
my $test = !defined $got && !defined $expect;
$self->_is_diag($got, '==', $expect) unless $test;
return $self->cmp_ok($got, '==', $expect, $name);
my($self, $got, $type, $expect) = @_;
foreach my $val (\
$got, \
$expect) {
# quote and force string context
return $self->diag(sprintf <<DIAGNOSTIC, $got, $expect);
$Test->isnt_eq($got, $dont_expect, $name);
Like Test::More's isnt(). Checks if $got ne $dont_expect. This is
$Test->is_num($got, $dont_expect, $name);
Like Test::More's isnt(). Checks if $got ne $dont_expect. This is
my($self, $got, $dont_expect, $name) = @_;
local $Level = $Level + 1;
if( !defined $got || !defined $dont_expect ) {
# undef only matches undef and nothing else
my $test = defined $got || defined $dont_expect;
$self->_cmp_diag('ne', $got, $dont_expect) unless $test;
return $self->cmp_ok($got, 'ne', $dont_expect, $name);
my($self, $got, $dont_expect, $name) = @_;
local $Level = $Level + 1;
if( !defined $got || !defined $dont_expect ) {
# undef only matches undef and nothing else
my $test = defined $got || defined $dont_expect;
$self->_cmp_diag('!=', $got, $dont_expect) unless $test;
return $self->cmp_ok($got, '!=', $dont_expect, $name);
$Test->like($this, qr/$regex/, $name);
$Test->like($this, '/$regex/', $name);
Like Test::More's like(). Checks if $this matches the given $regex.
You'll want to avoid qr// if you want your tests to work before 5.005.
$Test->unlike($this, qr/$regex/, $name);
$Test->unlike($this, '/$regex/', $name);
Like Test::More's unlike(). Checks if $this B<does not match> the
my($self, $this, $regex, $name) = @_;
local $Level = $Level + 1;
$self->_regex_ok($this, $regex, '=~', $name);
my($self, $this, $regex, $name) = @_;
local $Level = $Level + 1;
$self->_regex_ok($this, $regex, '!~', $name);
$Test->maybe_regex(qr/$regex/);
$Test->maybe_regex('/$regex/');
Convenience method for building testing functions that take regular
expressions as arguments, but need to work before perl 5.005.
Takes a quoted regular expression produced by qr//, or a string
representing a regular expression.
Returns a Perl value which may be used instead of the corresponding
regular expression, or undef if it's argument is not recognised.
For example, a version of like(), sans the useful diagnostic messages,
my ($self, $this, $regex, $name) = @_;
my $usable_regex = $self->maybe_regex($regex);
die "expecting regex, found '$regex'\n"
$self->ok($this =~ m/$usable_regex/, $name);
my $usable_regex = undef;
if( ref $regex eq 'Regexp' ) {
# Check if it looks like '/foo/'
elsif( my($re, $opts) = $regex =~ m{^ /(.*)/ (\w*) $ }sx ) {
$usable_regex = length $opts ?
"(?$opts)$re" : $re;
my($self, $this, $regex, $cmp, $name) = @_;
local $Level = $Level + 1;
my $usable_regex = $self->maybe_regex($regex);
unless (defined $usable_regex) {
$ok = $self->ok( 0, $name );
$self->diag(" '$regex' doesn't look much like a regex to me.");
my $test = $this =~ /$usable_regex/ ?
1 : 0;
$test = !$test if $cmp eq '!~';
$ok = $self->ok( $test, $name );
$this = defined $this ?
"'$this'" : 'undef';
my $match = $cmp eq '=~' ?
"doesn't match" : "matches";
$self->diag(sprintf <<DIAGNOSTIC, $this, $match, $regex);
$Test->cmp_ok($this, $type, $that, $name);
Works just like Test::More's cmp_ok().
$Test->cmp_ok($big_num, '!=', $other_big_num);
my($self, $got, $type, $expect, $name) = @_;
local($@
,$!); # don't interfere with $@
# eval() sometimes resets $!
$test = eval "\$got $type \$expect";
local $Level = $Level + 1;
my $ok = $self->ok($test, $name);
if( $type =~ /^(eq|==)$/ ) {
$self->_is_diag($got, $type, $expect);
$self->_cmp_diag($got, $type, $expect);
my($self, $got, $type, $expect) = @_;
$got = defined $got ?
"'$got'" : 'undef';
$expect = defined $expect ?
"'$expect'" : 'undef';
return $self->diag(sprintf <<DIAGNOSTIC, $got, $type, $expect);
Indicates to the Test::Harness that things are going so badly all
testing should terminate. This includes running any additional test
$self->_print("Bail out! $reason");
Skips the current test, reporting $why.
Carp
::croak
("You tried to run tests without a plan! Gotta have a plan.");
$Test_Results[$Curr_Test-1] = 1;
$out .= " $Curr_Test" if $self->use_numbers;
$out .= " # skip $why\n";
Like skip(), only it will declare the test as failing and TODO. Similar
print "not ok $tnum # TODO $why\n";
Carp
::croak
("You tried to run tests without a plan! Gotta have a plan.");
$Test_Results[$Curr_Test-1] = 1;
$out .= " $Curr_Test" if $self->use_numbers;
$out .= " # TODO & SKIP $why\n";
$Test->skip_rest($reason);
Like skip(), only it skips all the rest of the tests you plan to run
If you're running under no_plan, it skips once and terminates the
How far up the call stack should $Test look when reporting where the
Setting $Test::Builder::Level overrides. This is typically useful
local $Test::Builder::Level = 2;
$Test->use_numbers($on_or_off);
Whether or not the test should output numbers. That is, this if true:
Most useful when you can't depend on the test output order, such as
when threads or forking is involved.
Test::Harness will accept either, but avoid mixing the two styles.
my($self, $use_nums) = @_;
if( defined $use_nums ) {
$Test->no_header($no_header);
If set to true, no "1..N" header will be printed.
$Test->no_ending($no_ending);
Normally, Test::Builder does some extra diagnostics when the test
ends. It also changes the exit code as described in Test::Simple.
If this is true, none of that will be done.
my($No_Header, $No_Ending) = (0,0);
my($self, $no_header) = @_;
if( defined $no_header ) {
my($self, $no_ending) = @_;
if( defined $no_ending ) {
Controlling where the test output goes.
It's ok for your test to change where STDOUT and STDERR point to,
Test::Builder's default output settings will not be affected.
Prints out the given $message. Normally, it uses the failure_output()
handle, but if this is for a TODO test, the todo_output() handle is
Output will be indented and marked with a # so as not to interfere
with test output. A newline will be put on the end if there isn't one
We encourage using this rather than calling print directly.
Returns false. Why? Because diag() is often used in conjunction with
a failing test (C<ok() || diag()>) it "passes through" the failure.
return ok(...) || diag(...);
Mark Fowler <mark@twoshortplanks.com>
# Prevent printing headers when compiling (i.e. -c)
# Escape each line with a #.
$_ = 'undef' unless defined;
push @msgs, "\n" unless $msgs[-1] =~ /\n\Z/;
local $Level = $Level + 1;
my $fh = $self->todo ?
$self->todo_output : $self->failure_output;
local($\
, $", $,) = (undef, ' ', '');
Prints to the output() filehandle.
# Prevent printing headers when only compiling. Mostly for when
# tests are deparsed with B::Deparse
local($\, $", $,) = (undef, ' ', '');
# Escape each line after the first with a # so we don't
push @msgs, "\n" unless $msgs[-1] =~ /\n\Z/;
Where normal "ok/not ok" test output should go.
$Test->failure_output($fh);
$Test->failure_output($file);
Where diagnostic output on test failures and diag() should go.
$Test->todo_output($file);
Where diagnostics about todo test failures and diag() should go.
my($Out_FH, $Fail_FH, $Todo_FH);
unless( UNIVERSAL
::isa
($file_or_fh, 'GLOB') ) {
open $fh, ">$file_or_fh" or
die "Can't open test output log $file_or_fh: $!";
# We dup STDOUT and STDERR so people can change them in their
# test suites while still getting normal test output.
open(TESTOUT
, ">&STDOUT") or die "Can't dup STDOUT: $!";
open(TESTERR
, ">&STDERR") or die "Can't dup STDERR: $!";
# Set everything to unbuffered else plain prints to STDOUT will
# come out in the wrong order from our own prints.
$CLASS->output(\
*TESTOUT
);
$CLASS->failure_output(\
*TESTERR
);
$CLASS->todo_output(\
*TESTOUT
);
=head2 Test Status and Info
my $curr_test = $Test->current_test;
$Test->current_test($num);
Gets/sets the current test # we're on.
You usually shouldn't have to set this.
Carp
::croak
("Can't change the current test number without a plan!");
if( $num > @Test_Results ) {
my $start = @Test_Results ?
$#Test_Results : 0;
my @tests = $Test->summary;
A simple summary of the tests so far. True for pass, false for fail.
This is a logical pass/fail, so todos are passes.
Of course, test #1 is $tests[0], etc...
=item B<details> I<UNIMPLEMENTED>
my @tests = $Test->details;
Like summary(), but with a lot more detail.
{ ok => is the test considered ok?
actual_ok => did it literally say 'ok'?
name => name of the test (if any)
type => 'skip' or 'todo' (if any)
reason => reason for the above (if any)
my $todo_reason = $Test->todo;
my $todo_reason = $Test->todo($pack);
todo() looks for a $TODO variable in your tests. If set, all tests
will be considered 'todo' (see Test::More and Test::Harness for
details). Returns the reason (ie. the value of $TODO) if running as
todo tests, false otherwise.
todo() is pretty part about finding the right package to look for
$TODO in. It uses the exported_to() package to find it. If that's
not set, it's pretty good at guessing the right package to look at.
Sometimes there is some confusion about where todo() should be looking
for the $TODO variable. If you want to be sure, tell it explicitly
$pack = $pack || $self->exported_to || $self->caller(1);
return defined ${$pack.'::TODO'} ?
${$pack.'::TODO'}
my $package = $Test->caller;
my($pack, $file, $line) = $Test->caller;
my($pack, $file, $line) = $Test->caller($height);
Like the normal caller(), except it reports according to your level().
my @caller = CORE
::caller($self->level + $height + 1);
return wantarray ?
@caller : $caller[0];
Runs a bunch of end of test sanity checks to make sure reality came
through ok. If anything is wrong it will die with a fairly friendly
_whoa
($Curr_Test < 0, 'Says here you ran a negative number of tests!');
_whoa
(!$Have_Plan and $Curr_Test,
'Somehow your tests ran without a plan!');
_whoa
($Curr_Test != @Test_Results,
'Somehow you got a different number of results than tests ran!');
_whoa($check, $description);
A sanity check, similar to assert(). If the $check is true, something
has gone horribly wrong. It will die with the given $description and
a note to contact the author.
This should never happen
! Please contact the author immediately
!
Perl seems to have some trouble with exiting inside an END block. 5.005_03
and 5.6.1 both seem to do odd things. Instead, this function edits $?
directly. It should ONLY be called from inside an END block. It
doesn't actually exit, that's your job.
# We don't want to muck with death in an eval, but $^S isn't
# totally reliable. 5.005_03 and 5.6.1 both do the wrong thing
# with it. Instead, we use caller. This also means it runs under
for( my $stack = 1; my $sub = (CORE
::caller($stack))[3]; $stack++ ) {
$in_eval = 1 if $sub =~ /^\(eval\)/;
$Test_Died = 1 unless $in_eval;
# Bailout if plan() was never called. This is so
# "require Test::Simple" doesn't puke.
do{ _my_exit
(0) && return } if !$Have_Plan;
# Figure out if we passed or failed and print helpful messages.
# The plan? We have no plan.
$self->_print("1..$Curr_Test\n") unless $self->no_header;
$Expected_Tests = $Curr_Test;
# 5.8.0 threads bug. Shared arrays will not be auto-extended
$Test_Results[$Expected_Tests-1] = undef
unless defined $Test_Results[$Expected_Tests-1];
my $num_failed = grep !$_, @Test_Results[0..$Expected_Tests-1];
$num_failed += abs($Expected_Tests - @Test_Results);
if( $Curr_Test < $Expected_Tests ) {
Looks like you planned $Expected_Tests tests but only ran $Curr_Test.
elsif( $Curr_Test > $Expected_Tests ) {
my $num_extra = $Curr_Test - $Expected_Tests;
Looks like you planned $Expected_Tests tests but ran $num_extra extra.
Looks like you failed $num_failed tests of $Expected_Tests.
Looks like your test died just after $Curr_Test.
_my_exit
( 255 ) && return;
_my_exit
( $num_failed <= 254 ?
$num_failed : 254 ) && return;
$self->diag("No tests run!\n");
_my_exit
( 255 ) && return;
$Test->_ending if defined $Test and !$Test->no_ending;
In perl 5.8.0 and later, Test::Builder is thread-safe. The test
number is shared amongst all threads. This means if one thread sets
the test number using current_test() they will all be effected.
CPAN can provide the best examples. Test::Simple, Test::More,
Test::Exception and Test::Differences all use Test::Builder.
Test::Simple, Test::More, Test::Harness
Original code by chromatic, maintained by Michael G Schwern
E<lt>schwern@pobox.comE<gt>
Copyright 2001 by chromatic E<lt>chromatic@wgz.orgE<gt>,
Michael G Schwern E<lt>schwern@pobox.comE<gt>.
This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
See F<http://www.perl.com/perl/misc/Artistic.html>