<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">package Test::Builder;

use 5.006;
use strict;
use warnings;

our $VERSION = '0.98';
$VERSION = eval $VERSION;    ## no critic (BuiltinFunctions::ProhibitStringyEval)

BEGIN {
    if( $] &lt; 5.008 ) {
        require Test::Builder::IO::Scalar;
    }
}


# Make Test::Builder thread-safe for ithreads.
BEGIN {
    use Config;
    # Load threads::shared when threads are turned on.
    # 5.8.0's threads are so busted we no longer support them.
    if( $] &gt;= 5.008001 &amp;&amp; $Config{useithreads} &amp;&amp; $INC{'threads.pm'} ) {
        require threads::shared;

        # Hack around YET ANOTHER threads::shared bug.  It would
        # occasionally forget the contents of the variable when sharing it.
        # So we first copy the data, then share, then put our copy back.
        *share = sub (\[$@%]) {
            my $type = ref $_[0];
            my $data;

            if( $type eq 'HASH' ) {
                %$data = %{ $_[0] };
            }
            elsif( $type eq 'ARRAY' ) {
                @$data = @{ $_[0] };
            }
            elsif( $type eq 'SCALAR' ) {
                $$data = ${ $_[0] };
            }
            else {
                die( "Unknown type: " . $type );
            }

            $_[0] = &amp;threads::shared::share( $_[0] );

            if( $type eq 'HASH' ) {
                %{ $_[0] } = %$data;
            }
            elsif( $type eq 'ARRAY' ) {
                @{ $_[0] } = @$data;
            }
            elsif( $type eq 'SCALAR' ) {
                ${ $_[0] } = $$data;
            }
            else {
                die( "Unknown type: " . $type );
            }

            return $_[0];
        };
    }
    # 5.8.0's threads::shared is busted when threads are off
    # and earlier Perls just don't have that module at all.
    else {
        *share = sub { return $_[0] };
        *lock  = sub { 0 };
    }
}

=head1 NAME

Test::Builder - Backend for building test libraries

=head1 SYNOPSIS

  package My::Test::Module;
  use base 'Test::Builder::Module';

  my $CLASS = __PACKAGE__;

  sub ok {
      my($test, $name) = @_;
      my $tb = $CLASS-&gt;builder;

      $tb-&gt;ok($test, $name);
  }


=head1 DESCRIPTION

Test::Simple and Test::More have proven to be popular testing modules,
but they're not always flexible enough.  Test::Builder provides a
building block upon which to write your own test libraries I&lt;which can
work together&gt;.

=head2 Construction

=over 4

=item B&lt;new&gt;

  my $Test = Test::Builder-&gt;new;

Returns a Test::Builder object representing the current state of the
test.

Since you only run one test per program C&lt;new&gt; always returns the same
Test::Builder object.  No matter how many times you call C&lt;new()&gt;, you're
getting the same object.  This is called a singleton.  This is done so that
multiple modules share such global information as the test counter and
where test output is going.

If you want a completely new Test::Builder object different from the
singleton, use C&lt;create&gt;.

=cut

our $Test = Test::Builder-&gt;new;

sub new {
    my($class) = shift;
    $Test ||= $class-&gt;create;
    return $Test;
}

=item B&lt;create&gt;

  my $Test = Test::Builder-&gt;create;

Ok, so there can be more than one Test::Builder object and this is how
you get it.  You might use this instead of C&lt;new()&gt; if you're testing
a Test::Builder based module, but otherwise you probably want C&lt;new&gt;.

B&lt;NOTE&gt;: the implementation is not complete.  C&lt;level&gt;, for example, is
still shared amongst B&lt;all&gt; Test::Builder objects, even ones created using
this method.  Also, the method name may change in the future.

=cut

sub create {
    my $class = shift;

    my $self = bless {}, $class;
    $self-&gt;reset;

    return $self;
}

=item B&lt;child&gt;

  my $child = $builder-&gt;child($name_of_child);
  $child-&gt;plan( tests =&gt; 4 );
  $child-&gt;ok(some_code());
  ...
  $child-&gt;finalize;

Returns a new instance of C&lt;Test::Builder&gt;.  Any output from this child will
be indented four spaces more than the parent's indentation.  When done, the
C&lt;finalize&gt; method I&lt;must&gt; be called explicitly.

Trying to create a new child with a previous child still active (i.e.,
C&lt;finalize&gt; not called) will C&lt;croak&gt;.

Trying to run a test when you have an open child will also C&lt;croak&gt; and cause
the test suite to fail.

=cut

sub child {
    my( $self, $name ) = @_;

    if( $self-&gt;{Child_Name} ) {
        $self-&gt;croak("You already have a child named ($self-&gt;{Child_Name}) running");
    }

    my $parent_in_todo = $self-&gt;in_todo;

    # Clear $TODO for the child.
    my $orig_TODO = $self-&gt;find_TODO(undef, 1, undef);

    my $child = bless {}, ref $self;
    $child-&gt;reset;

    # Add to our indentation
    $child-&gt;_indent( $self-&gt;_indent . '    ' );
    
    $child-&gt;{$_} = $self-&gt;{$_} foreach qw{Out_FH Todo_FH Fail_FH};
    if ($parent_in_todo) {
        $child-&gt;{Fail_FH} = $self-&gt;{Todo_FH};
    }

    # This will be reset in finalize. We do this here lest one child failure
    # cause all children to fail.
    $child-&gt;{Child_Error} = $?;
    $?                    = 0;
    $child-&gt;{Parent}      = $self;
    $child-&gt;{Parent_TODO} = $orig_TODO;
    $child-&gt;{Name}        = $name || "Child of " . $self-&gt;name;
    $self-&gt;{Child_Name}   = $child-&gt;name;
    return $child;
}


=item B&lt;subtest&gt;

    $builder-&gt;subtest($name, \&amp;subtests);

See documentation of C&lt;subtest&gt; in Test::More.

=cut

sub subtest {
    my $self = shift;
    my($name, $subtests) = @_;

    if ('CODE' ne ref $subtests) {
        $self-&gt;croak("subtest()'s second argument must be a code ref");
    }

    # Turn the child into the parent so anyone who has stored a copy of
    # the Test::Builder singleton will get the child.
    my($error, $child, %parent);
    {
        # child() calls reset() which sets $Level to 1, so we localize
        # $Level first to limit the scope of the reset to the subtest.
        local $Test::Builder::Level = $Test::Builder::Level + 1;

        $child  = $self-&gt;child($name);
        %parent = %$self;
        %$self  = %$child;

        my $run_the_subtests = sub {
            $subtests-&gt;();
            $self-&gt;done_testing unless $self-&gt;_plan_handled;
            1;
        };

        if( !eval { $run_the_subtests-&gt;() } ) {
            $error = $@;
        }
    }

    # Restore the parent and the copied child.
    %$child = %$self;
    %$self = %parent;

    # Restore the parent's $TODO
    $self-&gt;find_TODO(undef, 1, $child-&gt;{Parent_TODO});

    # Die *after* we restore the parent.
    die $error if $error and !eval { $error-&gt;isa('Test::Builder::Exception') };

    local $Test::Builder::Level = $Test::Builder::Level + 1;
    return $child-&gt;finalize;
}

=begin _private

=item B&lt;_plan_handled&gt;

    if ( $Test-&gt;_plan_handled ) { ... }

Returns true if the developer has explicitly handled the plan via:

=over 4

=item * Explicitly setting the number of tests

=item * Setting 'no_plan'

=item * Set 'skip_all'.

=back

This is currently used in subtests when we implicitly call C&lt;&lt; $Test-&gt;done_testing &gt;&gt;
if the developer has not set a plan.

=end _private

=cut

sub _plan_handled {
    my $self = shift;
    return $self-&gt;{Have_Plan} || $self-&gt;{No_Plan} || $self-&gt;{Skip_All};
}


=item B&lt;finalize&gt;

  my $ok = $child-&gt;finalize;

When your child is done running tests, you must call C&lt;finalize&gt; to clean up
and tell the parent your pass/fail status.

Calling finalize on a child with open children will C&lt;croak&gt;.

If the child falls out of scope before C&lt;finalize&gt; is called, a failure
diagnostic will be issued and the child is considered to have failed.

No attempt to call methods on a child after C&lt;finalize&gt; is called is
guaranteed to succeed.

Calling this on the root builder is a no-op.

=cut

sub finalize {
    my $self = shift;

    return unless $self-&gt;parent;
    if( $self-&gt;{Child_Name} ) {
        $self-&gt;croak("Can't call finalize() with child ($self-&gt;{Child_Name}) active");
    }

    local $? = 0;     # don't fail if $subtests happened to set $? nonzero
    $self-&gt;_ending;

    # XXX This will only be necessary for TAP envelopes (we think)
    #$self-&gt;_print( $self-&gt;is_passing ? "PASS\n" : "FAIL\n" );

    local $Test::Builder::Level = $Test::Builder::Level + 1;
    my $ok = 1;
    $self-&gt;parent-&gt;{Child_Name} = undef;
    if ( $self-&gt;{Skip_All} ) {
        $self-&gt;parent-&gt;skip($self-&gt;{Skip_All});
    }
    elsif ( not @{ $self-&gt;{Test_Results} } ) {
        $self-&gt;parent-&gt;ok( 0, sprintf q[No tests run for subtest "%s"], $self-&gt;name );
    }
    else {
        $self-&gt;parent-&gt;ok( $self-&gt;is_passing, $self-&gt;name );
    }
    $? = $self-&gt;{Child_Error};
    delete $self-&gt;{Parent};

    return $self-&gt;is_passing;
}

sub _indent      {
    my $self = shift;

    if( @_ ) {
        $self-&gt;{Indent} = shift;
    }

    return $self-&gt;{Indent};
}

=item B&lt;parent&gt;

 if ( my $parent = $builder-&gt;parent ) {
     ...
 }

Returns the parent C&lt;Test::Builder&gt; instance, if any.  Only used with child
builders for nested TAP.

=cut

sub parent { shift-&gt;{Parent} }

=item B&lt;name&gt;

 diag $builder-&gt;name;

Returns the name of the current builder.  Top level builders default to C&lt;$0&gt;
(the name of the executable).  Child builders are named via the C&lt;child&gt;
method.  If no name is supplied, will be named "Child of $parent-&gt;name".

=cut

sub name { shift-&gt;{Name} }

sub DESTROY {
    my $self = shift;
    if ( $self-&gt;parent and $$ == $self-&gt;{Original_Pid} ) {
        my $name = $self-&gt;name;
        $self-&gt;diag(&lt;&lt;"FAIL");
Child ($name) exited without calling finalize()
FAIL
        $self-&gt;parent-&gt;{In_Destroy} = 1;
        $self-&gt;parent-&gt;ok(0, $name);
    }
}

=item B&lt;reset&gt;

  $Test-&gt;reset;

Reinitializes the Test::Builder singleton to its original state.
Mostly useful for tests run in persistent environments where the same
test might be run multiple times in the same process.

=cut

our $Level;

sub reset {    ## no critic (Subroutines::ProhibitBuiltinHomonyms)
    my($self) = @_;

    # We leave this a global because it has to be localized and localizing
    # hash keys is just asking for pain.  Also, it was documented.
    $Level = 1;

    $self-&gt;{Name}         = $0;
    $self-&gt;is_passing(1);
    $self-&gt;{Ending}       = 0;
    $self-&gt;{Have_Plan}    = 0;
    $self-&gt;{No_Plan}      = 0;
    $self-&gt;{Have_Output_Plan} = 0;
    $self-&gt;{Done_Testing} = 0;

    $self-&gt;{Original_Pid} = $$;
    $self-&gt;{Child_Name}   = undef;
    $self-&gt;{Indent}     ||= '';

    share( $self-&gt;{Curr_Test} );
    $self-&gt;{Curr_Test} = 0;
    $self-&gt;{Test_Results} = &amp;share( [] );

    $self-&gt;{Exported_To}    = undef;
    $self-&gt;{Expected_Tests} = 0;

    $self-&gt;{Skip_All} = 0;

    $self-&gt;{Use_Nums} = 1;

    $self-&gt;{No_Header} = 0;
    $self-&gt;{No_Ending} = 0;

    $self-&gt;{Todo}       = undef;
    $self-&gt;{Todo_Stack} = [];
    $self-&gt;{Start_Todo} = 0;
    $self-&gt;{Opened_Testhandles} = 0;

    $self-&gt;_dup_stdhandles;

    return;
}

=back

=head2 Setting up tests

These methods are for setting up tests and declaring how many there
are.  You usually only want to call one of these methods.

=over 4

=item B&lt;plan&gt;

  $Test-&gt;plan('no_plan');
  $Test-&gt;plan( skip_all =&gt; $reason );
  $Test-&gt;plan( tests =&gt; $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 C&lt;plan()&gt;, don't call any of the other methods below.

If a child calls "skip_all" in the plan, a C&lt;Test::Builder::Exception&gt; is
thrown.  Trap this error, call C&lt;finalize()&gt; and don't run any more tests on
the child.

 my $child = $Test-&gt;child('some child');
 eval { $child-&gt;plan( $condition ? ( skip_all =&gt; $reason ) : ( tests =&gt; 3 )  ) };
 if ( eval { $@-&gt;isa('Test::Builder::Exception') } ) {
    $child-&gt;finalize;
    return;
 }
 # run your tests

=cut

my %plan_cmds = (
    no_plan     =&gt; \&amp;no_plan,
    skip_all    =&gt; \&amp;skip_all,
    tests       =&gt; \&amp;_plan_tests,
);

sub plan {
    my( $self, $cmd, $arg ) = @_;

    return unless $cmd;

    local $Level = $Level + 1;

    $self-&gt;croak("You tried to plan twice") if $self-&gt;{Have_Plan};

    if( my $method = $plan_cmds{$cmd} ) {
        local $Level = $Level + 1;
        $self-&gt;$method($arg);
    }
    else {
        my @args = grep { defined } ( $cmd, $arg );
        $self-&gt;croak("plan() doesn't understand @args");
    }

    return 1;
}


sub _plan_tests {
    my($self, $arg) = @_;

    if($arg) {
        local $Level = $Level + 1;
        return $self-&gt;expected_tests($arg);
    }
    elsif( !defined $arg ) {
        $self-&gt;croak("Got an undefined number of tests");
    }
    else {
        $self-&gt;croak("You said to run 0 tests");
    }

    return;
}

=item B&lt;expected_tests&gt;

    my $max = $Test-&gt;expected_tests;
    $Test-&gt;expected_tests($max);

Gets/sets the number of tests we expect this test to run and prints out
the appropriate headers.

=cut

sub expected_tests {
    my $self = shift;
    my($max) = @_;

    if(@_) {
        $self-&gt;croak("Number of tests must be a positive integer.  You gave it '$max'")
          unless $max =~ /^\+?\d+$/;

        $self-&gt;{Expected_Tests} = $max;
        $self-&gt;{Have_Plan}      = 1;

        $self-&gt;_output_plan($max) unless $self-&gt;no_header;
    }
    return $self-&gt;{Expected_Tests};
}

=item B&lt;no_plan&gt;

  $Test-&gt;no_plan;

Declares that this test will run an indeterminate number of tests.

=cut

sub no_plan {
    my($self, $arg) = @_;

    $self-&gt;carp("no_plan takes no arguments") if $arg;

    $self-&gt;{No_Plan}   = 1;
    $self-&gt;{Have_Plan} = 1;

    return 1;
}

=begin private

=item B&lt;_output_plan&gt;

  $tb-&gt;_output_plan($max);
  $tb-&gt;_output_plan($max, $directive);
  $tb-&gt;_output_plan($max, $directive =&gt; $reason);

Handles displaying the test plan.

If a C&lt;$directive&gt; and/or C&lt;$reason&gt; are given they will be output with the
plan.  So here's what skipping all tests looks like:

    $tb-&gt;_output_plan(0, "SKIP", "Because I said so");

It sets C&lt;&lt; $tb-&gt;{Have_Output_Plan} &gt;&gt; and will croak if the plan was already
output.

=end private

=cut

sub _output_plan {
    my($self, $max, $directive, $reason) = @_;

    $self-&gt;carp("The plan was already output") if $self-&gt;{Have_Output_Plan};

    my $plan = "1..$max";
    $plan .= " # $directive" if defined $directive;
    $plan .= " $reason"      if defined $reason;

    $self-&gt;_print("$plan\n");

    $self-&gt;{Have_Output_Plan} = 1;

    return;
}


=item B&lt;done_testing&gt;

  $Test-&gt;done_testing();
  $Test-&gt;done_testing($num_tests);

Declares that you are done testing, no more tests will be run after this point.

If a plan has not yet been output, it will do so.

$num_tests is the number of tests you planned to run.  If a numbered
plan was already declared, and if this contradicts, a failing test
will be run to reflect the planning mistake.  If C&lt;no_plan&gt; was declared,
this will override.

If C&lt;done_testing()&gt; is called twice, the second call will issue a
failing test.

If C&lt;$num_tests&gt; is omitted, the number of tests run will be used, like
no_plan.

C&lt;done_testing()&gt; is, in effect, used when you'd want to use C&lt;no_plan&gt;, but
safer. You'd use it like so:

    $Test-&gt;ok($a == $b);
    $Test-&gt;done_testing();

Or to plan a variable number of tests:

    for my $test (@tests) {
        $Test-&gt;ok($test);
    }
    $Test-&gt;done_testing(@tests);

=cut

sub done_testing {
    my($self, $num_tests) = @_;

    # If done_testing() specified the number of tests, shut off no_plan.
    if( defined $num_tests ) {
        $self-&gt;{No_Plan} = 0;
    }
    else {
        $num_tests = $self-&gt;current_test;
    }

    if( $self-&gt;{Done_Testing} ) {
        my($file, $line) = @{$self-&gt;{Done_Testing}}[1,2];
        $self-&gt;ok(0, "done_testing() was already called at $file line $line");
        return;
    }

    $self-&gt;{Done_Testing} = [caller];

    if( $self-&gt;expected_tests &amp;&amp; $num_tests != $self-&gt;expected_tests ) {
        $self-&gt;ok(0, "planned to run @{[ $self-&gt;expected_tests ]} ".
                     "but done_testing() expects $num_tests");
    }
    else {
        $self-&gt;{Expected_Tests} = $num_tests;
    }

    $self-&gt;_output_plan($num_tests) unless $self-&gt;{Have_Output_Plan};

    $self-&gt;{Have_Plan} = 1;

    # The wrong number of tests were run
    $self-&gt;is_passing(0) if $self-&gt;{Expected_Tests} != $self-&gt;{Curr_Test};

    # No tests were run
    $self-&gt;is_passing(0) if $self-&gt;{Curr_Test} == 0;

    return 1;
}


=item B&lt;has_plan&gt;

  $plan = $Test-&gt;has_plan

Find out whether a plan has been defined. C&lt;$plan&gt; is either C&lt;undef&gt; (no plan
has been set), C&lt;no_plan&gt; (indeterminate # of tests) or an integer (the number
of expected tests).

=cut

sub has_plan {
    my $self = shift;

    return( $self-&gt;{Expected_Tests} ) if $self-&gt;{Expected_Tests};
    return('no_plan') if $self-&gt;{No_Plan};
    return(undef);
}

=item B&lt;skip_all&gt;

  $Test-&gt;skip_all;
  $Test-&gt;skip_all($reason);

Skips all the tests, using the given C&lt;$reason&gt;.  Exits immediately with 0.

=cut

sub skip_all {
    my( $self, $reason ) = @_;

    $self-&gt;{Skip_All} = $self-&gt;parent ? $reason : 1;

    $self-&gt;_output_plan(0, "SKIP", $reason) unless $self-&gt;no_header;
    if ( $self-&gt;parent ) {
        die bless {} =&gt; 'Test::Builder::Exception';
    }
    exit(0);
}

=item B&lt;exported_to&gt;

  my $pack = $Test-&gt;exported_to;
  $Test-&gt;exported_to($pack);

Tells Test::Builder what package you exported your functions to.

This method isn't terribly useful since modules which share the same
Test::Builder object might get exported to different packages and only
the last one will be honored.

=cut

sub exported_to {
    my( $self, $pack ) = @_;

    if( defined $pack ) {
        $self-&gt;{Exported_To} = $pack;
    }
    return $self-&gt;{Exported_To};
}

=back

=head2 Running tests

These actually run the tests, analogous to the functions in Test::More.

They all return true if the test passed, false if the test failed.

C&lt;$name&gt; is always optional.

=over 4

=item B&lt;ok&gt;

  $Test-&gt;ok($test, $name);

Your basic test.  Pass if C&lt;$test&gt; is true, fail if $test is false.  Just
like Test::Simple's C&lt;ok()&gt;.

=cut

sub ok {
    my( $self, $test, $name ) = @_;

    if ( $self-&gt;{Child_Name} and not $self-&gt;{In_Destroy} ) {
        $name = 'unnamed test' unless defined $name;
        $self-&gt;is_passing(0);
        $self-&gt;croak("Cannot run test ($name) with active children");
    }
    # $test might contain an object which we don't want to accidentally
    # store, so we turn it into a boolean.
    $test = $test ? 1 : 0;

    lock $self-&gt;{Curr_Test};
    $self-&gt;{Curr_Test}++;

    # In case $name is a string overloaded object, force it to stringify.
    $self-&gt;_unoverload_str( \$name );

    $self-&gt;diag(&lt;&lt;"ERR") if defined $name and $name =~ /^[\d\s]+$/;
    You named your test '$name'.  You shouldn't use numbers for your test names.
    Very confusing.
ERR

    # Capture the value of $TODO for the rest of this ok() call
    # so it can more easily be found by other routines.
    my $todo    = $self-&gt;todo();
    my $in_todo = $self-&gt;in_todo;
    local $self-&gt;{Todo} = $todo if $in_todo;

    $self-&gt;_unoverload_str( \$todo );

    my $out;
    my $result = &amp;share( {} );

    unless($test) {
        $out .= "not ";
        @$result{ 'ok', 'actual_ok' } = ( ( $self-&gt;in_todo ? 1 : 0 ), 0 );
    }
    else {
        @$result{ 'ok', 'actual_ok' } = ( 1, $test );
    }

    $out .= "ok";
    $out .= " $self-&gt;{Curr_Test}" if $self-&gt;use_numbers;

    if( defined $name ) {
        $name =~ s|#|\\#|g;    # # in a name can confuse Test::Harness.
        $out .= " - $name";
        $result-&gt;{name} = $name;
    }
    else {
        $result-&gt;{name} = '';
    }

    if( $self-&gt;in_todo ) {
        $out .= " # TODO $todo";
        $result-&gt;{reason} = $todo;
        $result-&gt;{type}   = 'todo';
    }
    else {
        $result-&gt;{reason} = '';
        $result-&gt;{type}   = '';
    }

    $self-&gt;{Test_Results}[ $self-&gt;{Curr_Test} - 1 ] = $result;
    $out .= "\n";

    $self-&gt;_print($out);

    unless($test) {
        my $msg = $self-&gt;in_todo ? "Failed (TODO)" : "Failed";
        $self-&gt;_print_to_fh( $self-&gt;_diag_fh, "\n" ) if $ENV{HARNESS_ACTIVE};

        my( undef, $file, $line ) = $self-&gt;caller;
        if( defined $name ) {
            $self-&gt;diag(qq[  $msg test '$name'\n]);
            $self-&gt;diag(qq[  at $file line $line.\n]);
        }
        else {
            $self-&gt;diag(qq[  $msg test at $file line $line.\n]);
        }
    }

    $self-&gt;is_passing(0) unless $test || $self-&gt;in_todo;

    # Check that we haven't violated the plan
    $self-&gt;_check_is_passing_plan();

    return $test ? 1 : 0;
}


# Check that we haven't yet violated the plan and set
# is_passing() accordingly
sub _check_is_passing_plan {
    my $self = shift;

    my $plan = $self-&gt;has_plan;
    return unless defined $plan;        # no plan yet defined
    return unless $plan !~ /\D/;        # no numeric plan
    $self-&gt;is_passing(0) if $plan &lt; $self-&gt;{Curr_Test};
}


sub _unoverload {
    my $self = shift;
    my $type = shift;

    $self-&gt;_try(sub { require overload; }, die_on_fail =&gt; 1);

    foreach my $thing (@_) {
        if( $self-&gt;_is_object($$thing) ) {
            if( my $string_meth = overload::Method( $$thing, $type ) ) {
                $$thing = $$thing-&gt;$string_meth();
            }
        }
    }

    return;
}

sub _is_object {
    my( $self, $thing ) = @_;

    return $self-&gt;_try( sub { ref $thing &amp;&amp; $thing-&gt;isa('UNIVERSAL') } ) ? 1 : 0;
}

sub _unoverload_str {
    my $self = shift;

    return $self-&gt;_unoverload( q[""], @_ );
}

sub _unoverload_num {
    my $self = shift;

    $self-&gt;_unoverload( '0+', @_ );

    for my $val (@_) {
        next unless $self-&gt;_is_dualvar($$val);
        $$val = $$val + 0;
    }

    return;
}

# This is a hack to detect a dualvar such as $!
sub _is_dualvar {
    my( $self, $val ) = @_;

    # Objects are not dualvars.
    return 0 if ref $val;

    no warnings 'numeric';
    my $numval = $val + 0;
    return $numval != 0 and $numval ne $val ? 1 : 0;
}

=item B&lt;is_eq&gt;

  $Test-&gt;is_eq($got, $expected, $name);

Like Test::More's C&lt;is()&gt;.  Checks if C&lt;$got eq $expected&gt;.  This is the
string version.

C&lt;undef&gt; only ever matches another C&lt;undef&gt;.

=item B&lt;is_num&gt;

  $Test-&gt;is_num($got, $expected, $name);

Like Test::More's C&lt;is()&gt;.  Checks if C&lt;$got == $expected&gt;.  This is the
numeric version.

C&lt;undef&gt; only ever matches another C&lt;undef&gt;.

=cut

sub is_eq {
    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 &amp;&amp; !defined $expect;

        $self-&gt;ok( $test, $name );
        $self-&gt;_is_diag( $got, 'eq', $expect ) unless $test;
        return $test;
    }

    return $self-&gt;cmp_ok( $got, 'eq', $expect, $name );
}

sub is_num {
    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 &amp;&amp; !defined $expect;

        $self-&gt;ok( $test, $name );
        $self-&gt;_is_diag( $got, '==', $expect ) unless $test;
        return $test;
    }

    return $self-&gt;cmp_ok( $got, '==', $expect, $name );
}

sub _diag_fmt {
    my( $self, $type, $val ) = @_;

    if( defined $$val ) {
        if( $type eq 'eq' or $type eq 'ne' ) {
            # quote and force string context
            $$val = "'$$val'";
        }
        else {
            # force numeric context
            $self-&gt;_unoverload_num($val);
        }
    }
    else {
        $$val = 'undef';
    }

    return;
}

sub _is_diag {
    my( $self, $got, $type, $expect ) = @_;

    $self-&gt;_diag_fmt( $type, $_ ) for \$got, \$expect;

    local $Level = $Level + 1;
    return $self-&gt;diag(&lt;&lt;"DIAGNOSTIC");
         got: $got
    expected: $expect
DIAGNOSTIC

}

sub _isnt_diag {
    my( $self, $got, $type ) = @_;

    $self-&gt;_diag_fmt( $type, \$got );

    local $Level = $Level + 1;
    return $self-&gt;diag(&lt;&lt;"DIAGNOSTIC");
         got: $got
    expected: anything else
DIAGNOSTIC
}

=item B&lt;isnt_eq&gt;

  $Test-&gt;isnt_eq($got, $dont_expect, $name);

Like Test::More's C&lt;isnt()&gt;.  Checks if C&lt;$got ne $dont_expect&gt;.  This is
the string version.

=item B&lt;isnt_num&gt;

  $Test-&gt;isnt_num($got, $dont_expect, $name);

Like Test::More's C&lt;isnt()&gt;.  Checks if C&lt;$got ne $dont_expect&gt;.  This is
the numeric version.

=cut

sub isnt_eq {
    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-&gt;ok( $test, $name );
        $self-&gt;_isnt_diag( $got, 'ne' ) unless $test;
        return $test;
    }

    return $self-&gt;cmp_ok( $got, 'ne', $dont_expect, $name );
}

sub isnt_num {
    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-&gt;ok( $test, $name );
        $self-&gt;_isnt_diag( $got, '!=' ) unless $test;
        return $test;
    }

    return $self-&gt;cmp_ok( $got, '!=', $dont_expect, $name );
}

=item B&lt;like&gt;

  $Test-&gt;like($this, qr/$regex/, $name);
  $Test-&gt;like($this, '/$regex/', $name);

Like Test::More's C&lt;like()&gt;.  Checks if $this matches the given C&lt;$regex&gt;.

=item B&lt;unlike&gt;

  $Test-&gt;unlike($this, qr/$regex/, $name);
  $Test-&gt;unlike($this, '/$regex/', $name);

Like Test::More's C&lt;unlike()&gt;.  Checks if $this B&lt;does not match&gt; the
given C&lt;$regex&gt;.

=cut

sub like {
    my( $self, $this, $regex, $name ) = @_;

    local $Level = $Level + 1;
    return $self-&gt;_regex_ok( $this, $regex, '=~', $name );
}

sub unlike {
    my( $self, $this, $regex, $name ) = @_;

    local $Level = $Level + 1;
    return $self-&gt;_regex_ok( $this, $regex, '!~', $name );
}

=item B&lt;cmp_ok&gt;

  $Test-&gt;cmp_ok($this, $type, $that, $name);

Works just like Test::More's C&lt;cmp_ok()&gt;.

    $Test-&gt;cmp_ok($big_num, '!=', $other_big_num);

=cut

my %numeric_cmps = map { ( $_, 1 ) } ( "&lt;", "&lt;=", "&gt;", "&gt;=", "==", "!=", "&lt;=&gt;" );

sub cmp_ok {
    my( $self, $got, $type, $expect, $name ) = @_;

    my $test;
    my $error;
    {
        ## no critic (BuiltinFunctions::ProhibitStringyEval)

        local( $@, $!, $SIG{__DIE__} );    # isolate eval

        my($pack, $file, $line) = $self-&gt;caller();

        # This is so that warnings come out at the caller's level
        $test = eval qq[
#line $line "(eval in cmp_ok) $file"
\$got $type \$expect;
];
        $error = $@;
    }
    local $Level = $Level + 1;
    my $ok = $self-&gt;ok( $test, $name );

    # Treat overloaded objects as numbers if we're asked to do a
    # numeric comparison.
    my $unoverload
      = $numeric_cmps{$type}
      ? '_unoverload_num'
      : '_unoverload_str';

    $self-&gt;diag(&lt;&lt;"END") if $error;
An error occurred while using $type:
------------------------------------
$error
------------------------------------
END

    unless($ok) {
        $self-&gt;$unoverload( \$got, \$expect );

        if( $type =~ /^(eq|==)$/ ) {
            $self-&gt;_is_diag( $got, $type, $expect );
        }
        elsif( $type =~ /^(ne|!=)$/ ) {
            $self-&gt;_isnt_diag( $got, $type );
        }
        else {
            $self-&gt;_cmp_diag( $got, $type, $expect );
        }
    }
    return $ok;
}

sub _cmp_diag {
    my( $self, $got, $type, $expect ) = @_;

    $got    = defined $got    ? "'$got'"    : 'undef';
    $expect = defined $expect ? "'$expect'" : 'undef';

    local $Level = $Level + 1;
    return $self-&gt;diag(&lt;&lt;"DIAGNOSTIC");
    $got
        $type
    $expect
DIAGNOSTIC
}

sub _caller_context {
    my $self = shift;

    my( $pack, $file, $line ) = $self-&gt;caller(1);

    my $code = '';
    $code .= "#line $line $file\n" if defined $file and defined $line;

    return $code;
}

=back


=head2 Other Testing Methods

These are methods which are used in the course of writing a test but are not themselves tests.

=over 4

=item B&lt;BAIL_OUT&gt;

    $Test-&gt;BAIL_OUT($reason);

Indicates to the Test::Harness that things are going so badly all
testing should terminate.  This includes running any additional test
scripts.

It will exit with 255.

=cut

sub BAIL_OUT {
    my( $self, $reason ) = @_;

    $self-&gt;{Bailed_Out} = 1;
    $self-&gt;_print("Bail out!  $reason");
    exit 255;
}

=for deprecated
BAIL_OUT() used to be BAILOUT()

=cut

{
    no warnings 'once';
    *BAILOUT = \&amp;BAIL_OUT;
}

=item B&lt;skip&gt;

    $Test-&gt;skip;
    $Test-&gt;skip($why);

Skips the current test, reporting C&lt;$why&gt;.

=cut

sub skip {
    my( $self, $why ) = @_;
    $why ||= '';
    $self-&gt;_unoverload_str( \$why );

    lock( $self-&gt;{Curr_Test} );
    $self-&gt;{Curr_Test}++;

    $self-&gt;{Test_Results}[ $self-&gt;{Curr_Test} - 1 ] = &amp;share(
        {
            'ok'      =&gt; 1,
            actual_ok =&gt; 1,
            name      =&gt; '',
            type      =&gt; 'skip',
            reason    =&gt; $why,
        }
    );

    my $out = "ok";
    $out .= " $self-&gt;{Curr_Test}" if $self-&gt;use_numbers;
    $out .= " # skip";
    $out .= " $why"               if length $why;
    $out .= "\n";

    $self-&gt;_print($out);

    return 1;
}

=item B&lt;todo_skip&gt;

  $Test-&gt;todo_skip;
  $Test-&gt;todo_skip($why);

Like C&lt;skip()&gt;, only it will declare the test as failing and TODO.  Similar
to

    print "not ok $tnum # TODO $why\n";

=cut

sub todo_skip {
    my( $self, $why ) = @_;
    $why ||= '';

    lock( $self-&gt;{Curr_Test} );
    $self-&gt;{Curr_Test}++;

    $self-&gt;{Test_Results}[ $self-&gt;{Curr_Test} - 1 ] = &amp;share(
        {
            'ok'      =&gt; 1,
            actual_ok =&gt; 0,
            name      =&gt; '',
            type      =&gt; 'todo_skip',
            reason    =&gt; $why,
        }
    );

    my $out = "not ok";
    $out .= " $self-&gt;{Curr_Test}" if $self-&gt;use_numbers;
    $out .= " # TODO &amp; SKIP $why\n";

    $self-&gt;_print($out);

    return 1;
}

=begin _unimplemented

=item B&lt;skip_rest&gt;

  $Test-&gt;skip_rest;
  $Test-&gt;skip_rest($reason);

Like C&lt;skip()&gt;, only it skips all the rest of the tests you plan to run
and terminates the test.

If you're running under C&lt;no_plan&gt;, it skips once and terminates the
test.

=end _unimplemented

=back


=head2 Test building utility methods

These methods are useful when writing your own test methods.

=over 4

=item B&lt;maybe_regex&gt;

  $Test-&gt;maybe_regex(qr/$regex/);
  $Test-&gt;maybe_regex('/$regex/');

This method used to be useful back when Test::Builder worked on Perls
before 5.6 which didn't have qr//.  Now its pretty useless.

Convenience method for building testing functions that take regular
expressions as arguments.

Takes a quoted regular expression produced by C&lt;qr//&gt;, or a string
representing a regular expression.

Returns a Perl value which may be used instead of the corresponding
regular expression, or C&lt;undef&gt; if its argument is not recognised.

For example, a version of C&lt;like()&gt;, sans the useful diagnostic messages,
could be written as:

  sub laconic_like {
      my ($self, $this, $regex, $name) = @_;
      my $usable_regex = $self-&gt;maybe_regex($regex);
      die "expecting regex, found '$regex'\n"
          unless $usable_regex;
      $self-&gt;ok($this =~ m/$usable_regex/, $name);
  }

=cut

sub maybe_regex {
    my( $self, $regex ) = @_;
    my $usable_regex = undef;

    return $usable_regex unless defined $regex;

    my( $re, $opts );

    # Check for qr/foo/
    if( _is_qr($regex) ) {
        $usable_regex = $regex;
    }
    # Check for '/foo/' or 'm,foo,'
    elsif(( $re, $opts )        = $regex =~ m{^ /(.*)/ (\w*) $ }sx              or
          ( undef, $re, $opts ) = $regex =~ m,^ m([^\w\s]) (.+) \1 (\w*) $,sx
    )
    {
        $usable_regex = length $opts ? "(?$opts)$re" : $re;
    }

    return $usable_regex;
}

sub _is_qr {
    my $regex = shift;

    # is_regexp() checks for regexes in a robust manner, say if they're
    # blessed.
    return re::is_regexp($regex) if defined &amp;re::is_regexp;
    return ref $regex eq 'Regexp';
}

sub _regex_ok {
    my( $self, $this, $regex, $cmp, $name ) = @_;

    my $ok           = 0;
    my $usable_regex = $self-&gt;maybe_regex($regex);
    unless( defined $usable_regex ) {
        local $Level = $Level + 1;
        $ok = $self-&gt;ok( 0, $name );
        $self-&gt;diag("    '$regex' doesn't look much like a regex to me.");
        return $ok;
    }

    {
        ## no critic (BuiltinFunctions::ProhibitStringyEval)

        my $test;
        my $context = $self-&gt;_caller_context;

        local( $@, $!, $SIG{__DIE__} );    # isolate eval

        $test = eval $context . q{$test = $this =~ /$usable_regex/ ? 1 : 0};

        $test = !$test if $cmp eq '!~';

        local $Level = $Level + 1;
        $ok = $self-&gt;ok( $test, $name );
    }

    unless($ok) {
        $this = defined $this ? "'$this'" : 'undef';
        my $match = $cmp eq '=~' ? "doesn't match" : "matches";

        local $Level = $Level + 1;
        $self-&gt;diag( sprintf &lt;&lt;'DIAGNOSTIC', $this, $match, $regex );
                  %s
    %13s '%s'
DIAGNOSTIC

    }

    return $ok;
}

# I'm not ready to publish this.  It doesn't deal with array return
# values from the code or context.

=begin private

=item B&lt;_try&gt;

    my $return_from_code          = $Test-&gt;try(sub { code });
    my($return_from_code, $error) = $Test-&gt;try(sub { code });

Works like eval BLOCK except it ensures it has no effect on the rest
of the test (ie. C&lt;$@&gt; is not set) nor is effected by outside
interference (ie. C&lt;$SIG{__DIE__}&gt;) and works around some quirks in older
Perls.

C&lt;$error&gt; is what would normally be in C&lt;$@&gt;.

It is suggested you use this in place of eval BLOCK.

=cut

sub _try {
    my( $self, $code, %opts ) = @_;

    my $error;
    my $return;
    {
        local $!;               # eval can mess up $!
        local $@;               # don't set $@ in the test
        local $SIG{__DIE__};    # don't trip an outside DIE handler.
        $return = eval { $code-&gt;() };
        $error = $@;
    }

    die $error if $error and $opts{die_on_fail};

    return wantarray ? ( $return, $error ) : $return;
}

=end private


=item B&lt;is_fh&gt;

    my $is_fh = $Test-&gt;is_fh($thing);

Determines if the given C&lt;$thing&gt; can be used as a filehandle.

=cut

sub is_fh {
    my $self     = shift;
    my $maybe_fh = shift;
    return 0 unless defined $maybe_fh;

    return 1 if ref $maybe_fh  eq 'GLOB';    # its a glob ref
    return 1 if ref \$maybe_fh eq 'GLOB';    # its a glob

    return eval { $maybe_fh-&gt;isa("IO::Handle") } ||
           eval { tied($maybe_fh)-&gt;can('TIEHANDLE') };
}

=back


=head2 Test style


=over 4

=item B&lt;level&gt;

    $Test-&gt;level($how_high);

How far up the call stack should C&lt;$Test&gt; look when reporting where the
test failed.

Defaults to 1.

Setting L&lt;$Test::Builder::Level&gt; overrides.  This is typically useful
localized:

    sub my_ok {
        my $test = shift;

        local $Test::Builder::Level = $Test::Builder::Level + 1;
        $TB-&gt;ok($test);
    }

To be polite to other functions wrapping your own you usually want to increment C&lt;$Level&gt; rather than set it to a constant.

=cut

sub level {
    my( $self, $level ) = @_;

    if( defined $level ) {
        $Level = $level;
    }
    return $Level;
}

=item B&lt;use_numbers&gt;

    $Test-&gt;use_numbers($on_or_off);

Whether or not the test should output numbers.  That is, this if true:

  ok 1
  ok 2
  ok 3

or this if false

  ok
  ok
  ok

Most useful when you can't depend on the test output order, such as
when threads or forking is involved.

Defaults to on.

=cut

sub use_numbers {
    my( $self, $use_nums ) = @_;

    if( defined $use_nums ) {
        $self-&gt;{Use_Nums} = $use_nums;
    }
    return $self-&gt;{Use_Nums};
}

=item B&lt;no_diag&gt;

    $Test-&gt;no_diag($no_diag);

If set true no diagnostics will be printed.  This includes calls to
C&lt;diag()&gt;.

=item B&lt;no_ending&gt;

    $Test-&gt;no_ending($no_ending);

Normally, Test::Builder does some extra diagnostics when the test
ends.  It also changes the exit code as described below.

If this is true, none of that will be done.

=item B&lt;no_header&gt;

    $Test-&gt;no_header($no_header);

If set to true, no "1..N" header will be printed.

=cut

foreach my $attribute (qw(No_Header No_Ending No_Diag)) {
    my $method = lc $attribute;

    my $code = sub {
        my( $self, $no ) = @_;

        if( defined $no ) {
            $self-&gt;{$attribute} = $no;
        }
        return $self-&gt;{$attribute};
    };

    no strict 'refs';    ## no critic
    *{ __PACKAGE__ . '::' . $method } = $code;
}

=back

=head2 Output

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.

=over 4

=item B&lt;diag&gt;

    $Test-&gt;diag(@msgs);

Prints out the given C&lt;@msgs&gt;.  Like C&lt;print&gt;, arguments are simply
appended together.

Normally, it uses the C&lt;failure_output()&gt; handle, but if this is for a
TODO test, the C&lt;todo_output()&gt; handle is used.

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
already.

We encourage using this rather than calling print directly.

Returns false.  Why?  Because C&lt;diag()&gt; is often used in conjunction with
a failing test (C&lt;ok() || diag()&gt;) it "passes through" the failure.

    return ok(...) || diag(...);

=for blame transfer
Mark Fowler &lt;mark@twoshortplanks.com&gt;

=cut

sub diag {
    my $self = shift;

    $self-&gt;_print_comment( $self-&gt;_diag_fh, @_ );
}

=item B&lt;note&gt;

    $Test-&gt;note(@msgs);

Like C&lt;diag()&gt;, but it prints to the C&lt;output()&gt; handle so it will not
normally be seen by the user except in verbose mode.

=cut

sub note {
    my $self = shift;

    $self-&gt;_print_comment( $self-&gt;output, @_ );
}

sub _diag_fh {
    my $self = shift;

    local $Level = $Level + 1;
    return $self-&gt;in_todo ? $self-&gt;todo_output : $self-&gt;failure_output;
}

sub _print_comment {
    my( $self, $fh, @msgs ) = @_;

    return if $self-&gt;no_diag;
    return unless @msgs;

    # Prevent printing headers when compiling (i.e. -c)
    return if $^C;

    # Smash args together like print does.
    # Convert undef to 'undef' so its readable.
    my $msg = join '', map { defined($_) ? $_ : 'undef' } @msgs;

    # Escape the beginning, _print will take care of the rest.
    $msg =~ s/^/# /;

    local $Level = $Level + 1;
    $self-&gt;_print_to_fh( $fh, $msg );

    return 0;
}

=item B&lt;explain&gt;

    my @dump = $Test-&gt;explain(@msgs);

Will dump the contents of any references in a human readable format.
Handy for things like...

    is_deeply($have, $want) || diag explain $have;

or

    is_deeply($have, $want) || note explain $have;

=cut

sub explain {
    my $self = shift;

    return map {
        ref $_
          ? do {
            $self-&gt;_try(sub { require Data::Dumper }, die_on_fail =&gt; 1);

            my $dumper = Data::Dumper-&gt;new( [$_] );
            $dumper-&gt;Indent(1)-&gt;Terse(1);
            $dumper-&gt;Sortkeys(1) if $dumper-&gt;can("Sortkeys");
            $dumper-&gt;Dump;
          }
          : $_
    } @_;
}

=begin _private

=item B&lt;_print&gt;

    $Test-&gt;_print(@msgs);

Prints to the C&lt;output()&gt; filehandle.

=end _private

=cut

sub _print {
    my $self = shift;
    return $self-&gt;_print_to_fh( $self-&gt;output, @_ );
}

sub _print_to_fh {
    my( $self, $fh, @msgs ) = @_;

    # Prevent printing headers when only compiling.  Mostly for when
    # tests are deparsed with B::Deparse
    return if $^C;

    my $msg = join '', @msgs;
    my $indent = $self-&gt;_indent;

    local( $\, $", $, ) = ( undef, ' ', '' );

    # Escape each line after the first with a # so we don't
    # confuse Test::Harness.
    $msg =~ s{\n(?!\z)}{\n$indent# }sg;

    # Stick a newline on the end if it needs it.
    $msg .= "\n" unless $msg =~ /\n\z/;

    return print $fh $indent, $msg;
}

=item B&lt;output&gt;

=item B&lt;failure_output&gt;

=item B&lt;todo_output&gt;

    my $filehandle = $Test-&gt;output;
    $Test-&gt;output($filehandle);
    $Test-&gt;output($filename);
    $Test-&gt;output(\$scalar);

These methods control where Test::Builder will print its output.
They take either an open C&lt;$filehandle&gt;, a C&lt;$filename&gt; to open and write to
or a C&lt;$scalar&gt; reference to append to.  It will always return a C&lt;$filehandle&gt;.

B&lt;output&gt; is where normal "ok/not ok" test output goes.

Defaults to STDOUT.

B&lt;failure_output&gt; is where diagnostic output on test failures and
C&lt;diag()&gt; goes.  It is normally not read by Test::Harness and instead is
displayed to the user.

Defaults to STDERR.

C&lt;todo_output&gt; is used instead of C&lt;failure_output()&gt; for the
diagnostics of a failing TODO test.  These will not be seen by the
user.

Defaults to STDOUT.

=cut

sub output {
    my( $self, $fh ) = @_;

    if( defined $fh ) {
        $self-&gt;{Out_FH} = $self-&gt;_new_fh($fh);
    }
    return $self-&gt;{Out_FH};
}

sub failure_output {
    my( $self, $fh ) = @_;

    if( defined $fh ) {
        $self-&gt;{Fail_FH} = $self-&gt;_new_fh($fh);
    }
    return $self-&gt;{Fail_FH};
}

sub todo_output {
    my( $self, $fh ) = @_;

    if( defined $fh ) {
        $self-&gt;{Todo_FH} = $self-&gt;_new_fh($fh);
    }
    return $self-&gt;{Todo_FH};
}

sub _new_fh {
    my $self = shift;
    my($file_or_fh) = shift;

    my $fh;
    if( $self-&gt;is_fh($file_or_fh) ) {
        $fh = $file_or_fh;
    }
    elsif( ref $file_or_fh eq 'SCALAR' ) {
        # Scalar refs as filehandles was added in 5.8.
        if( $] &gt;= 5.008 ) {
            open $fh, "&gt;&gt;", $file_or_fh
              or $self-&gt;croak("Can't open scalar ref $file_or_fh: $!");
        }
        # Emulate scalar ref filehandles with a tie.
        else {
            $fh = Test::Builder::IO::Scalar-&gt;new($file_or_fh)
              or $self-&gt;croak("Can't tie scalar ref $file_or_fh");
        }
    }
    else {
        open $fh, "&gt;", $file_or_fh
          or $self-&gt;croak("Can't open test output log $file_or_fh: $!");
        _autoflush($fh);
    }

    return $fh;
}

sub _autoflush {
    my($fh) = shift;
    my $old_fh = select $fh;
    $| = 1;
    select $old_fh;

    return;
}

my( $Testout, $Testerr );

sub _dup_stdhandles {
    my $self = shift;

    $self-&gt;_open_testhandles;

    # Set everything to unbuffered else plain prints to STDOUT will
    # come out in the wrong order from our own prints.
    _autoflush($Testout);
    _autoflush( \*STDOUT );
    _autoflush($Testerr);
    _autoflush( \*STDERR );

    $self-&gt;reset_outputs;

    return;
}

sub _open_testhandles {
    my $self = shift;

    return if $self-&gt;{Opened_Testhandles};

    # We dup STDOUT and STDERR so people can change them in their
    # test suites while still getting normal test output.
    open( $Testout, "&gt;&amp;STDOUT" ) or die "Can't dup STDOUT:  $!";
    open( $Testerr, "&gt;&amp;STDERR" ) or die "Can't dup STDERR:  $!";

    $self-&gt;_copy_io_layers( \*STDOUT, $Testout );
    $self-&gt;_copy_io_layers( \*STDERR, $Testerr );

    $self-&gt;{Opened_Testhandles} = 1;

    return;
}

sub _copy_io_layers {
    my( $self, $src, $dst ) = @_;

    $self-&gt;_try(
        sub {
            require PerlIO;
            my @src_layers = PerlIO::get_layers($src);

            _apply_layers($dst, @src_layers) if @src_layers;
        }
    );

    return;
}

sub _apply_layers {
    my ($fh, @layers) = @_;
    my %seen;
    my @unique = grep { $_ ne 'unix' and !$seen{$_}++ } @layers;
    binmode($fh, join(":", "", "raw", @unique));
}


=item reset_outputs

  $tb-&gt;reset_outputs;

Resets all the output filehandles back to their defaults.

=cut

sub reset_outputs {
    my $self = shift;

    $self-&gt;output        ($Testout);
    $self-&gt;failure_output($Testerr);
    $self-&gt;todo_output   ($Testout);

    return;
}

=item carp

  $tb-&gt;carp(@message);

Warns with C&lt;@message&gt; but the message will appear to come from the
point where the original test function was called (C&lt;&lt; $tb-&gt;caller &gt;&gt;).

=item croak

  $tb-&gt;croak(@message);

Dies with C&lt;@message&gt; but the message will appear to come from the
point where the original test function was called (C&lt;&lt; $tb-&gt;caller &gt;&gt;).

=cut

sub _message_at_caller {
    my $self = shift;

    local $Level = $Level + 1;
    my( $pack, $file, $line ) = $self-&gt;caller;
    return join( "", @_ ) . " at $file line $line.\n";
}

sub carp {
    my $self = shift;
    return warn $self-&gt;_message_at_caller(@_);
}

sub croak {
    my $self = shift;
    return die $self-&gt;_message_at_caller(@_);
}


=back


=head2 Test Status and Info

=over 4

=item B&lt;current_test&gt;

    my $curr_test = $Test-&gt;current_test;
    $Test-&gt;current_test($num);

Gets/sets the current test number we're on.  You usually shouldn't
have to set this.

If set forward, the details of the missing tests are filled in as 'unknown'.
if set backward, the details of the intervening tests are deleted.  You
can erase history if you really want to.

=cut

sub current_test {
    my( $self, $num ) = @_;

    lock( $self-&gt;{Curr_Test} );
    if( defined $num ) {
        $self-&gt;{Curr_Test} = $num;

        # If the test counter is being pushed forward fill in the details.
        my $test_results = $self-&gt;{Test_Results};
        if( $num &gt; @$test_results ) {
            my $start = @$test_results ? @$test_results : 0;
            for( $start .. $num - 1 ) {
                $test_results-&gt;[$_] = &amp;share(
                    {
                        'ok'      =&gt; 1,
                        actual_ok =&gt; undef,
                        reason    =&gt; 'incrementing test number',
                        type      =&gt; 'unknown',
                        name      =&gt; undef
                    }
                );
            }
        }
        # If backward, wipe history.  Its their funeral.
        elsif( $num &lt; @$test_results ) {
            $#{$test_results} = $num - 1;
        }
    }
    return $self-&gt;{Curr_Test};
}

=item B&lt;is_passing&gt;

   my $ok = $builder-&gt;is_passing;

Indicates if the test suite is currently passing.

More formally, it will be false if anything has happened which makes
it impossible for the test suite to pass.  True otherwise.

For example, if no tests have run C&lt;is_passing()&gt; will be true because
even though a suite with no tests is a failure you can add a passing
test to it and start passing.

Don't think about it too much.

=cut

sub is_passing {
    my $self = shift;

    if( @_ ) {
        $self-&gt;{Is_Passing} = shift;
    }

    return $self-&gt;{Is_Passing};
}


=item B&lt;summary&gt;

    my @tests = $Test-&gt;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...

=cut

sub summary {
    my($self) = shift;

    return map { $_-&gt;{'ok'} } @{ $self-&gt;{Test_Results} };
}

=item B&lt;details&gt;

    my @tests = $Test-&gt;details;

Like C&lt;summary()&gt;, but with a lot more detail.

    $tests[$test_num - 1] = 
            { 'ok'       =&gt; is the test considered a pass?
              actual_ok  =&gt; did it literally say 'ok'?
              name       =&gt; name of the test (if any)
              type       =&gt; type of test (if any, see below).
              reason     =&gt; reason for the above (if any)
            };

'ok' is true if Test::Harness will consider the test to be a pass.

'actual_ok' is a reflection of whether or not the test literally
printed 'ok' or 'not ok'.  This is for examining the result of 'todo'
tests.

'name' is the name of the test.

'type' indicates if it was a special test.  Normal tests have a type
of ''.  Type can be one of the following:

    skip        see skip()
    todo        see todo()
    todo_skip   see todo_skip()
    unknown     see below

Sometimes the Test::Builder test counter is incremented without it
printing any test output, for example, when C&lt;current_test()&gt; is changed.
In these cases, Test::Builder doesn't know the result of the test, so
its type is 'unknown'.  These details for these tests are filled in.
They are considered ok, but the name and actual_ok is left C&lt;undef&gt;.

For example "not ok 23 - hole count # TODO insufficient donuts" would
result in this structure:

    $tests[22] =    # 23 - 1, since arrays start from 0.
      { ok        =&gt; 1,   # logically, the test passed since its todo
        actual_ok =&gt; 0,   # in absolute terms, it failed
        name      =&gt; 'hole count',
        type      =&gt; 'todo',
        reason    =&gt; 'insufficient donuts'
      };

=cut

sub details {
    my $self = shift;
    return @{ $self-&gt;{Test_Results} };
}

=item B&lt;todo&gt;

    my $todo_reason = $Test-&gt;todo;
    my $todo_reason = $Test-&gt;todo($pack);

If the current tests are considered "TODO" it will return the reason,
if any.  This reason can come from a C&lt;$TODO&gt; variable or the last call
to C&lt;todo_start()&gt;.

Since a TODO test does not need a reason, this function can return an
empty string even when inside a TODO block.  Use C&lt;&lt; $Test-&gt;in_todo &gt;&gt;
to determine if you are currently inside a TODO block.

C&lt;todo()&gt; is about finding the right package to look for C&lt;$TODO&gt; in.  It's
pretty good at guessing the right package to look at.  It first looks for
the caller based on C&lt;$Level + 1&gt;, since C&lt;todo()&gt; is usually called inside
a test function.  As a last resort it will use C&lt;exported_to()&gt;.

Sometimes there is some confusion about where todo() should be looking
for the C&lt;$TODO&gt; variable.  If you want to be sure, tell it explicitly
what $pack to use.

=cut

sub todo {
    my( $self, $pack ) = @_;

    return $self-&gt;{Todo} if defined $self-&gt;{Todo};

    local $Level = $Level + 1;
    my $todo = $self-&gt;find_TODO($pack);
    return $todo if defined $todo;

    return '';
}

=item B&lt;find_TODO&gt;

    my $todo_reason = $Test-&gt;find_TODO();
    my $todo_reason = $Test-&gt;find_TODO($pack);

Like C&lt;todo()&gt; but only returns the value of C&lt;$TODO&gt; ignoring
C&lt;todo_start()&gt;.

Can also be used to set C&lt;$TODO&gt; to a new value while returning the
old value:

    my $old_reason = $Test-&gt;find_TODO($pack, 1, $new_reason);

=cut

sub find_TODO {
    my( $self, $pack, $set, $new_value ) = @_;

    $pack = $pack || $self-&gt;caller(1) || $self-&gt;exported_to;
    return unless $pack;

    no strict 'refs';    ## no critic
    my $old_value = ${ $pack . '::TODO' };
    $set and ${ $pack . '::TODO' } = $new_value;
    return $old_value;
}

=item B&lt;in_todo&gt;

    my $in_todo = $Test-&gt;in_todo;

Returns true if the test is currently inside a TODO block.

=cut

sub in_todo {
    my $self = shift;

    local $Level = $Level + 1;
    return( defined $self-&gt;{Todo} || $self-&gt;find_TODO ) ? 1 : 0;
}

=item B&lt;todo_start&gt;

    $Test-&gt;todo_start();
    $Test-&gt;todo_start($message);

This method allows you declare all subsequent tests as TODO tests, up until
the C&lt;todo_end&gt; method has been called.

The C&lt;TODO:&gt; and C&lt;$TODO&gt; syntax is generally pretty good about figuring out
whether or not we're in a TODO test.  However, often we find that this is not
possible to determine (such as when we want to use C&lt;$TODO&gt; but
the tests are being executed in other packages which can't be inferred
beforehand).

Note that you can use this to nest "todo" tests

 $Test-&gt;todo_start('working on this');
 # lots of code
 $Test-&gt;todo_start('working on that');
 # more code
 $Test-&gt;todo_end;
 $Test-&gt;todo_end;

This is generally not recommended, but large testing systems often have weird
internal needs.

We've tried to make this also work with the TODO: syntax, but it's not
guaranteed and its use is also discouraged:

 TODO: {
     local $TODO = 'We have work to do!';
     $Test-&gt;todo_start('working on this');
     # lots of code
     $Test-&gt;todo_start('working on that');
     # more code
     $Test-&gt;todo_end;
     $Test-&gt;todo_end;
 }

Pick one style or another of "TODO" to be on the safe side.

=cut

sub todo_start {
    my $self = shift;
    my $message = @_ ? shift : '';

    $self-&gt;{Start_Todo}++;
    if( $self-&gt;in_todo ) {
        push @{ $self-&gt;{Todo_Stack} } =&gt; $self-&gt;todo;
    }
    $self-&gt;{Todo} = $message;

    return;
}

=item C&lt;todo_end&gt;

 $Test-&gt;todo_end;

Stops running tests as "TODO" tests.  This method is fatal if called without a
preceding C&lt;todo_start&gt; method call.

=cut

sub todo_end {
    my $self = shift;

    if( !$self-&gt;{Start_Todo} ) {
        $self-&gt;croak('todo_end() called without todo_start()');
    }

    $self-&gt;{Start_Todo}--;

    if( $self-&gt;{Start_Todo} &amp;&amp; @{ $self-&gt;{Todo_Stack} } ) {
        $self-&gt;{Todo} = pop @{ $self-&gt;{Todo_Stack} };
    }
    else {
        delete $self-&gt;{Todo};
    }

    return;
}

=item B&lt;caller&gt;

    my $package = $Test-&gt;caller;
    my($pack, $file, $line) = $Test-&gt;caller;
    my($pack, $file, $line) = $Test-&gt;caller($height);

Like the normal C&lt;caller()&gt;, except it reports according to your C&lt;level()&gt;.

C&lt;$height&gt; will be added to the C&lt;level()&gt;.

If C&lt;caller()&gt; winds up off the top of the stack it report the highest context.

=cut

sub caller {    ## no critic (Subroutines::ProhibitBuiltinHomonyms)
    my( $self, $height ) = @_;
    $height ||= 0;

    my $level = $self-&gt;level + $height + 1;
    my @caller;
    do {
        @caller = CORE::caller( $level );
        $level--;
    } until @caller;
    return wantarray ? @caller : $caller[0];
}

=back

=cut

=begin _private

=over 4

=item B&lt;_sanity_check&gt;

  $self-&gt;_sanity_check();

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
error message.

=cut

#'#
sub _sanity_check {
    my $self = shift;

    $self-&gt;_whoa( $self-&gt;{Curr_Test} &lt; 0, 'Says here you ran a negative number of tests!' );
    $self-&gt;_whoa( $self-&gt;{Curr_Test} != @{ $self-&gt;{Test_Results} },
        'Somehow you got a different number of results than tests ran!' );

    return;
}

=item B&lt;_whoa&gt;

  $self-&gt;_whoa($check, $description);

A sanity check, similar to C&lt;assert()&gt;.  If the C&lt;$check&gt; is true, something
has gone horribly wrong.  It will die with the given C&lt;$description&gt; and
a note to contact the author.

=cut

sub _whoa {
    my( $self, $check, $desc ) = @_;
    if($check) {
        local $Level = $Level + 1;
        $self-&gt;croak(&lt;&lt;"WHOA");
WHOA!  $desc
This should never happen!  Please contact the author immediately!
WHOA
    }

    return;
}

=item B&lt;_my_exit&gt;

  _my_exit($exit_num);

Perl seems to have some trouble with exiting inside an C&lt;END&gt; block.
5.6.1 does some odd things.  Instead, this function edits C&lt;$?&gt;
directly.  It should B&lt;only&gt; be called from inside an C&lt;END&gt; block.
It doesn't actually exit, that's your job.

=cut

sub _my_exit {
    $? = $_[0];    ## no critic (Variables::RequireLocalizedPunctuationVars)

    return 1;
}

=back

=end _private

=cut

sub _ending {
    my $self = shift;
    return if $self-&gt;no_ending;
    return if $self-&gt;{Ending}++;

    my $real_exit_code = $?;

    # Don't bother with an ending if this is a forked copy.  Only the parent
    # should do the ending.
    if( $self-&gt;{Original_Pid} != $$ ) {
        return;
    }

    # Ran tests but never declared a plan or hit done_testing
    if( !$self-&gt;{Have_Plan} and $self-&gt;{Curr_Test} ) {
        $self-&gt;is_passing(0);
        $self-&gt;diag("Tests were run but no plan was declared and done_testing() was not seen.");
    }

    # Exit if plan() was never called.  This is so "require Test::Simple"
    # doesn't puke.
    if( !$self-&gt;{Have_Plan} ) {
        return;
    }

    # Don't do an ending if we bailed out.
    if( $self-&gt;{Bailed_Out} ) {
        $self-&gt;is_passing(0);
        return;
    }
    # Figure out if we passed or failed and print helpful messages.
    my $test_results = $self-&gt;{Test_Results};
    if(@$test_results) {
        # The plan?  We have no plan.
        if( $self-&gt;{No_Plan} ) {
            $self-&gt;_output_plan($self-&gt;{Curr_Test}) unless $self-&gt;no_header;
            $self-&gt;{Expected_Tests} = $self-&gt;{Curr_Test};
        }

        # Auto-extended arrays and elements which aren't explicitly
        # filled in with a shared reference will puke under 5.8.0
        # ithreads.  So we have to fill them in by hand. :(
        my $empty_result = &amp;share( {} );
        for my $idx ( 0 .. $self-&gt;{Expected_Tests} - 1 ) {
            $test_results-&gt;[$idx] = $empty_result
              unless defined $test_results-&gt;[$idx];
        }

        my $num_failed = grep !$_-&gt;{'ok'}, @{$test_results}[ 0 .. $self-&gt;{Curr_Test} - 1 ];

        my $num_extra = $self-&gt;{Curr_Test} - $self-&gt;{Expected_Tests};

        if( $num_extra != 0 ) {
            my $s = $self-&gt;{Expected_Tests} == 1 ? '' : 's';
            $self-&gt;diag(&lt;&lt;"FAIL");
Looks like you planned $self-&gt;{Expected_Tests} test$s but ran $self-&gt;{Curr_Test}.
FAIL
            $self-&gt;is_passing(0);
        }

        if($num_failed) {
            my $num_tests = $self-&gt;{Curr_Test};
            my $s = $num_failed == 1 ? '' : 's';

            my $qualifier = $num_extra == 0 ? '' : ' run';

            $self-&gt;diag(&lt;&lt;"FAIL");
Looks like you failed $num_failed test$s of $num_tests$qualifier.
FAIL
            $self-&gt;is_passing(0);
        }

        if($real_exit_code) {
            $self-&gt;diag(&lt;&lt;"FAIL");
Looks like your test exited with $real_exit_code just after $self-&gt;{Curr_Test}.
FAIL
            $self-&gt;is_passing(0);
            _my_exit($real_exit_code) &amp;&amp; return;
        }

        my $exit_code;
        if($num_failed) {
            $exit_code = $num_failed &lt;= 254 ? $num_failed : 254;
        }
        elsif( $num_extra != 0 ) {
            $exit_code = 255;
        }
        else {
            $exit_code = 0;
        }

        _my_exit($exit_code) &amp;&amp; return;
    }
    elsif( $self-&gt;{Skip_All} ) {
        _my_exit(0) &amp;&amp; return;
    }
    elsif($real_exit_code) {
        $self-&gt;diag(&lt;&lt;"FAIL");
Looks like your test exited with $real_exit_code before it could output anything.
FAIL
        $self-&gt;is_passing(0);
        _my_exit($real_exit_code) &amp;&amp; return;
    }
    else {
        $self-&gt;diag("No tests run!\n");
        $self-&gt;is_passing(0);
        _my_exit(255) &amp;&amp; return;
    }

    $self-&gt;is_passing(0);
    $self-&gt;_whoa( 1, "We fell off the end of _ending()" );
}

END {
    $Test-&gt;_ending if defined $Test;
}

=head1 EXIT CODES

If all your tests passed, Test::Builder will exit with zero (which is
normal).  If anything failed it will exit with how many failed.  If
you run less (or more) tests than you planned, the missing (or extras)
will be considered failures.  If no tests were ever run Test::Builder
will throw a warning and exit with 255.  If the test died, even after
having successfully completed all its tests, it will still be
considered a failure and will exit with 255.

So the exit codes are...

    0                   all tests successful
    255                 test died or all passed but wrong # of tests run
    any other number    how many failed (including missing or extras)

If you fail more than 254 tests, it will be reported as 254.

=head1 THREADS

In perl 5.8.1 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 C&lt;current_test()&gt; they will all be effected.

While versions earlier than 5.8.1 had threads they contain too many
bugs to support.

Test::Builder is only thread-aware if threads.pm is loaded I&lt;before&gt;
Test::Builder.

=head1 MEMORY

An informative hash, accessible via C&lt;&lt;details()&gt;&gt;, is stored for each
test you perform.  So memory usage will scale linearly with each test
run. Although this is not a problem for most test suites, it can
become an issue if you do large (hundred thousands to million)
combinatorics tests in the same run.

In such cases, you are advised to either split the test file into smaller
ones, or use a reverse approach, doing "normal" (code) compares and
triggering fail() should anything go unexpected.

Future versions of Test::Builder will have a way to turn history off.


=head1 EXAMPLES

CPAN can provide the best examples.  Test::Simple, Test::More,
Test::Exception and Test::Differences all use Test::Builder.

=head1 SEE ALSO

Test::Simple, Test::More, Test::Harness

=head1 AUTHORS

Original code by chromatic, maintained by Michael G Schwern
E&lt;lt&gt;schwern@pobox.comE&lt;gt&gt;

=head1 COPYRIGHT

Copyright 2002-2008 by chromatic E&lt;lt&gt;chromatic@wgz.orgE&lt;gt&gt; and
                       Michael G Schwern E&lt;lt&gt;schwern@pobox.comE&lt;gt&gt;.

This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.

See F&lt;http://www.perl.com/perl/misc/Artistic.html&gt;

=cut

1;

</pre></body></html>