The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Test::Builder - Backend for building test libraries

NOTE ON DEPRECATIONS

With version 1.301001 many old methods and practices have been deprecated. What we mean when we say "deprecated" is that the practices or methods are not to be used in any new code. Old code that uses them will still continue to work, possibly forever, but new code should use the newer and better alternatives.

In the future, if enough (read: pretty much everything) is updated and few if any modules still use these old items, they will be removed completely. This is not super likely to happen just because of the sheer number of modules that use Test::Builder.

SYNOPSIS

In general you probably do not want to use this module directly, but instead want to use Test::Builder::Provider which will help you roll out a testing library.

    package My::Test::Module;
    use Test::Builder::Provider;

    # Export a test tool from an anonymous sub
    provide ok => sub {
        my ($test, $name) = @_;
        builder()->ok($test, $name);
    };

    # Export tools that are package subs
    provides qw/is is_deeply/;
    sub is { ... }
    sub is_deeply { ... }

See Test::Builder::Provider for more details.

Note: You MUST use 'provide', or 'provides' to export testing tools, this allows you to use the builder()->trace_test tools to determine what file/line a failed test came from.

LOW-LEVEL

    use Test::Builder;
    my $tb = Test::Builder->create(modern => 1, shared_stream => 1);
    $tb->ok(1);
    ....

DEPRECATED

    use Test::Builder;
    my $tb = Test::Builder->new;
    $tb->ok(1);
    ...

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 which can work together.

TEST COMPONENT MAP

  [Test Script] > [Test Tool] > [Test::Builder] > [Test::Bulder::Stream] > [Event Formatter]
                                      ^
                                 You are here

A test script uses a test tool such as Test::More, which uses Test::Builder to produce events. The events are sent to Test::Builder::Stream which then forwards them on to one or more formatters. The default formatter is Test::Builder::Fromatter::TAP which produces TAP output.

METHODS

CONSTRUCTION

$Test = Test::Builder->create(%params)

Create a completely independant Test::Builder object.

    my $Test = Test::Builder->create;

Create a Test::Builder object that sends events to the shared output stream (usually what you want).

    my $Test = Test::Builder->create(shared_stream => 1);

Create a Test::Builder object that does not include any legacy cruft.

    my $Test = Test::Builder->create(modern => 1);
$Test = Test::Builder->new ***DEPRECATED***
    my $Test = Test::Builder->new;

This usage is DEPRECATED!

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

Since you only run one test per program new always returns the same Test::Builder object. No matter how many times you call new(), 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. No longer necessary

If you want a completely new Test::Builder object different from the singleton, use create.

SIMPLE ACCESSORS AND SHORTCUTS

READ/WRITE ATTRIBUTES

$parent = $Test->parent

Returns the parent Test::Builder instance, if any. Only used with child builders for nested TAP.

$Test->name

Defaults to $0, but subtests and child tests will set this.

$Test->modern

Defaults to $ENV{TB_MODERN}, or 0. True when the builder object was constructed with modern practices instead of deprecated ones.

$Test->depth

Get/Set the depth. This is usually set for Child tests.

$Test->default_name

Get/Set the default name for tests where no name was provided. Typically this should be set to undef, there are very few real-world use cases for this. Note: This functionality was added specifically for Test::Exception, which has one of the few real-world use cases.

DELEGATES TO STREAM

Each of these is a shortcut to $Test->stream->NAME

See the Test::Builder::Stream documentation for details.

$Test->is_passing(...)
$Test->listen(...)
$Test->munge(...)
$Test->tap
$Test->lresults
$Test->use_fork
$Test->no_fork

CHILDREN AND SUBTESTS

$Test->subtest($name, \&subtests, @args)

See documentation of subtest in Test::More.

subtest also, and optionally, accepts arguments which will be passed to the subtests reference.

$child = $Test->child($name)
  my $child = $builder->child($name_of_child);
  $child->plan( tests => 4 );
  $child->ok(some_code());
  ...
  $child->finalize;

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

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

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

$ok = $Child->finalize

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

Calling finalize on a child with open children will croak.

If the child falls out of scope before finalize 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 finalize is called is guaranteed to succeed.

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

STREAM MANAGEMENT

$stream = $Test->stream
$Test->stream($stream)
$Test->stream(undef)

Get/Set the stream. When no stream is set, or is undef it will return the shared stream.

Note: Do not set this to the shared stream yourself, set it to undef. This is because the shared stream is actually a stack, and this always returns the top of the stack.

$events = $Test->intercept(\&code)

Any tests run inside the codeblock will be intercepted and not sent to the normal stream. Instead they will be added to $events which is an array of Test::Builder::Event objects.

Note: This will also intercept BAIL_OUT and skipall.

Note: This will only intercept events generated with the Test::Builder object on which intercept() was called. Other builders will still send to the normal places.

See Test::Tester2 for a method of capturing events sent to the global stream.

TRACING THE TEST/PROVIDER BOUNDRY

When a test fails it will report the filename and line where the failure occured. In order to do this it needs to look at the stack and figure out where your tests stop, and the tools you are using begin. These methods help you find the desired caller frame.

See the Test::Builder::Trace module for more details.

$trace = $Test->trace_test()

Returns an Test::Builder::Trace object.

$reason = $Test->find_TODO
$reason = $Test->find_TODO($pack)
$old_reason = $Test->find_TODO($pack, 1, $new_reason);

Like todo() but only returns the value of $TODO ignoring todo_start().

Can also be used to set $TODO to a new value while returning the old value.

TEST PLAN

$Test->plan('no_plan');
$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.

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

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

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

$Test->skip_all
$Test->skip_all($reason)

Skips all the tests, using the given $reason. Exits immediately with 0.

$Test->done_testing
$Test->done_testing($count)

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 event will be run to reflect the planning mistake. If no_plan was declared, this will override.

If done_testing() is called twice, the second call will issue a failing event.

If $num_tests is omitted, the number of tests run will be used, like no_plan.

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

    $Test->ok($a == $b);
    $Test->done_testing();

Or to plan a variable number of tests:

    for my $test (@tests) {
        $Test->ok($test);
    }
    $Test->done_testing(scalar @tests);

SIMPLE EVENT PRODUCERS

Each of these produces 1 or more Test::Builder::Event objects which are fed into the event stream.

$Test->ok($test)
$Test->ok($test, $name)
$Test->ok($test, $name, @diag)

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

You may also specify diagnostics messages in the form of simple strings, or complete <Test::Builder::Event> objects. Typically you would only do this in a failure, but you are allowed to add diags to passes as well.

$Test->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.

$Test->skip
$Test->skip($why)

Skips the current test, reporting $why.

$Test->todo_skip
$Test->todo_skip($why)

Like skip(), only it will declare the test as failing and TODO. Similar to

    print "not ok $tnum # TODO $why\n";
$Test->diag(@msgs)

Prints out the given @msgs. Like print, arguments are simply appended together.

Normally, it uses the failure_output() handle, but if this is for a TODO test, the todo_output() 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 diag() is often used in conjunction with a failing test (ok() || diag()) it "passes through" the failure.

    return ok(...) || diag(...);
$Test->note(@msgs)

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

ADVANCED EVENT PRODUCERS

$Test->is_eq($got, $expected, $name)

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

undef only ever matches another undef.

$Test->is_num($got, $expected, $name)

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

undef only ever matches another undef.

$Test->isnt_eq($got, $dont_expect, $name)

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

$Test->isnt_num($got, $dont_expect, $name)

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

$Test->like($thing, qr/$regex/, $name)
$Test->like($thing, '/$regex/', $name)

Like Test::More's like(). Checks if $thing matches the given $regex.

$Test->unlike($thing, qr/$regex/, $name)
$Test->unlike($thing, '/$regex/', $name)

Like Test::More's unlike(). Checks if $thing $Test->does not match the given $regex.

$Test->cmp_ok($thing, $type, $that, $name)

Works just like Test::More's cmp_ok().

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

PUBLIC HELPERS

@dump = $Test->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;
$tb->carp(@message)

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

$tb->croak(@message)

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

$plan = $Test->has_plan

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

$Test->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.

%context = $Test->context

Returns a hash of contextual info.

    (
        depth  => DEPTH,
        source => NAME,
        trace  => TRACE,
    )

TODO MANAGEMENT

$todo_reason = $Test->todo
$todo_reason = $Test->todo($pack)

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

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

todo() is about finding the right package to look for $TODO in. It's pretty good at guessing the right package to look at. It considers the stack trace, $Level, and metadata associated with various packages.

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

$in_todo = $Test->in_todo

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

$Test->todo_start()
$Test->todo_start($message)

This method allows you declare all subsequent tests as TODO tests, up until the todo_end method has been called.

The TODO: and $TODO 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 $TODO 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->todo_start('working on this');
 # lots of code
 $Test->todo_start('working on that');
 # more code
 $Test->todo_end;
 $Test->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->todo_start('working on this');
     # lots of code
     $Test->todo_start('working on that');
     # more code
     $Test->todo_end;
     $Test->todo_end;
 }

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

$Test->todo_end

Stops running tests as "TODO" tests. This method is fatal if called without a preceding todo_start method call.

DEPRECATED/LEGACY

All of these will issue warnings if called on a modern Test::Builder object. That is any Test::Builder instance that was created with the 'modern' flag.

$self->no_ending

Deprecated: Moved to the Test::Builder::Stream object.

    $Test->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.

$self->summary

Deprecated: Moved to the Test::Builder::Stream object.

The style of result recording used here is deprecated. The functionality was moved to its own object to contain the legacy code.

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

$self->details

Deprecated: Moved to the Test::Builder::Formatter::LegacyEvents object.

The style of result recording used here is deprecated. The functionality was moved to its own object to contain the legacy code.

    my @tests = $Test->details;

Like summary(), but with a lot more detail.

    $tests[$test_num - 1] =
            { 'ok'       => is the test considered a pass?
              actual_ok  => did it literally say 'ok'?
              name       => name of the test (if any)
              type       => type of test (if any, see below).
              reason     => 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 current_test() 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 undef.

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        => 1,   # logically, the test passed since its todo
        actual_ok => 0,   # in absolute terms, it failed
        name      => 'hole count',
        type      => 'todo',
        reason    => 'insufficient donuts'
      };
$self->no_header

Deprecated: moved to the Test::Builder::Formatter::TAP object.

    $Test->no_header($no_header);

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

$self->no_diag

Deprecated: moved to the Test::Builder::Formatter::TAP object.

If set true no diagnostics will be printed. This includes calls to diag().

$self->output
$self->failure_output
$self->todo_output

Deprecated: moved to the Test::Builder::Formatter::TAP object.

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

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

output is where normal "ok/not ok" test output goes.

Defaults to STDOUT.

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

Defaults to STDERR.

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

Defaults to STDOUT.

$self->reset_outputs

Deprecated: moved to the Test::Builder::Formatter::TAP object.

    $tb->reset_outputs;

Resets all the output filehandles back to their defaults.

$self->use_numbers

Deprecated: moved to the Test::Builder::Formatter::TAP object.

    $Test->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.

$pack = $Test->exported_to
$Test->exported_to($pack)

Deprecated: Use Test::Builder::Trace->anoint($package) and $Test->trace_anointed instead.

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.

$is_fh = $Test->is_fh($thing);

Determines if the given $thing can be used as a filehandle.

$curr_test = $Test->current_test;
$Test->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.

$Test->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.

$max = $Test->expected_tests
$Test->expected_tests($max)

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

$package = $Test->caller
($pack, $file, $line) = $Test->caller
($pack, $file, $line) = $Test->caller($height)

Like the normal caller(), except it reports according to your level().

$height will be added to the level().

If caller() winds up off the top of the stack it report the highest context.

$Test->level($how_high)

DEPRECATED See deprecation notes at the top. The use of level() is deprecated.

How far up the call stack should $Test look when reporting where the test failed.

Defaults to 1.

Setting $Test::Builder::Level overrides. This is typically useful localized:

    sub my_ok {
        my $test = shift;

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

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

$Test->maybe_regex(qr/$regex/)
$Test->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 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 its argument is not recognised.

For example, a version of like(), sans the useful diagnostic messages, could be written as:

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

PACKAGE VARIABLES

NOTE: These are tied to the package, not the instance. Basically that means touching these can affect more things than you expect. Using these can lead to unexpected interactions at a distance.

$Level

Originally this was the only way to tell Test::Builder where in the stack errors should be reported. Now the preferred method of finding where errors should be reported is using the Test::Builder::Trace and Test::Builder::Provider modules.

$Level should be considered deprecated when possible, that said it will not be removed any time soon. There is too much legacy code that depends on $Level. There are also a couple situations in which $Level is necessary:

Backwards compatibility

If code simply cannot depend on a recent version of Test::Builder, then $Level must be used as there is no alternative. See Test::Builder::Compat for tools to help make test tools that work in old and new versions.

Stack Management

Using Test::Builder::Provider is not practical for situations like in Test::Exception where one needs to munge the call stack to hide frames.

$BLevel

Used internally by the Test::Builder::Trace, do not modify or rely on this in your own code. Documented for completeness.

$Test

The singleton returned by new(), which is deprecated in favor of create().

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.

Note: The magic that accomplishes this has been moved to Test::Builder::ExitMagic

THREADS

In perl 5.8.1 and later, Test::Builder is thread-safe. The test number is shared amongst all threads.

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 before Test::Builder.

MEMORY

Note: This only applies if you turn lresults on.

    $Test->stream->no_lresults;

An informative hash, accessible via details(), 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.

EXAMPLES

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

SEE ALSO

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

AUTHORS

Original code by chromatic, maintained by Michael G Schwern <schwern@pobox.com> until 2014. Currently maintained by Chad Granum <exodist7@gmail.com>.

MAINTAINERS

Chad Granum <exodist@cpan.org>

COPYRIGHT

Copyright 2002-2014 by chromatic <chromatic@wgz.org> and Michael G Schwern <schwern@pobox.com> and Chad Granum <exodist7@gmail.com>

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

See http://www.perl.com/perl/misc/Artistic.html