Test::Builder(3pm)
β¨ NAME β¨
Bestie, welcome to Test::Builder(3pm) from the Perl Programmers Reference Guide β the backend for building test libraries, and honestly it's giving βinfrastructure queenβ energy. π
Test::Builder β Backend for building test libraries
π§ͺ SYNOPSIS π§ͺ
package My::Test::Module;
use base 'Test::Builder::Module';
my $CLASS = __PACKAGE__;
sub ok {
my($test, $name) = @_;
my $tb = $CLASS->builder;
$tb->ok($test, $name);
}
π DESCRIPTION π
So Test::Simple and Test::More are iconic and popular testing modules, but they're not always flexible enough. Test::Builder gives you a building block for writing your own test libraries that can work together β lowkey powerful, fr fr.
ποΈ Construction ποΈ
β¨ new β¨
my $Test = Test::Builder->new;
Returns a Test::Builder object representing the current state of the test.
Okay so 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.
If you want a completely new Test::Builder object different from the singleton, use create.
β¨ create β¨
my $Test = Test::Builder->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 new() if you're testing a Test::Builder based module, but otherwise you probably want new.
NOTE: the implementation is not complete.level, for example, is still shared by allTest::Builderobjects, even ones created using this method. Also, the method name may change in the future. π
β¨ subtest β¨
$builder->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.
β¨ name β¨
diag $builder->name;
Returns the name of the current builder. Top level builders default to $0 (the name of the executable). Child builders are named via the child method. If no name is supplied, will be named Child of $parent->name.
β¨ reset β¨
$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.
π― 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.
β¨ 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. π«Ά
β¨ expected_tests β¨
my $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.
β¨ no_plan β¨
$Test->no_plan;
Declares that this test will run an indeterminate number of tests.
β¨ done_testing β¨
$Test->done_testing();
$Test->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 "no_plan" was declared, this will override.
If done_testing() is called twice, the second call will issue a failing test.
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);
β¨ has_plan β¨
$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).
β¨ skip_all β¨
$Test->skip_all;
$Test->skip_all($reason);
Skips all the tests, using the given $reason. Exits immediately with 0.
β¨ exported_to β¨
my $pack = $Test->exported_to;
$Test->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.
π 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.
$name is always optional.
β¨ ok β¨
$Test->ok($test, $name);
Your basic test. Pass if $test is true, fail if $test is false. Just like Test::Simple's ok().
β¨ is_eq β¨
$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".
β¨ is_num β¨
$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".
β¨ isnt_eq β¨
$Test->isnt_eq($got, $dont_expect, $name);
Like Test::More's isnt(). Checks if "$got ne $dont_expect". This is the string version.
β¨ isnt_num β¨
$Test->isnt_num($got, $dont_expect, $name);
Like Test::More's isnt(). Checks if "$got ne $dont_expect". This is the numeric version.
β¨ like β¨
$Test->like($thing, qr/$regex/, $name);
$Test->like($thing, '/$regex/', $name);
Like Test::More's like(). Checks if $thing matches the given $regex.
β¨ unlike β¨
$Test->unlike($thing, qr/$regex/, $name);
$Test->unlike($thing, '/$regex/', $name);
Like Test::More's unlike(). Checks if $thing does not match the given $regex.
β¨ cmp_ok β¨
$Test->cmp_ok($thing, $type, $that, $name);
Works just like Test::More's cmp_ok().
$Test->cmp_ok($big_num, '!=', $other_big_num);
π©Ή Other Testing Methods π©Ή
These are methods which are used in the course of writing a test but are not themselves tests.
β¨ BAIL_OUT β¨
$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. π¨
β¨ skip β¨
$Test->skip;
$Test->skip($why);
Skips the current test, reporting $why.
β¨ todo_skip β¨
$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 building utility methods π§°
These methods are useful when writing your own test methods.
β¨ maybe_regex β¨
$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 it's 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 recognized.
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);
}
β¨ is_fh β¨
my $is_fh = $Test->is_fh($thing);
Determines if the given $thing can be used as a filehandle.
π Test style π
β¨ level β¨
$Test->level($how_high);
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.
β¨ use_numbers β¨
$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.
β¨ no_diag β¨
$Test->no_diag($no_diag);
If set true no diagnostics will be printed. This includes calls to diag().
β¨ no_ending β¨
$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.
β¨ no_header β¨
$Test->no_header($no_header);
If set to true, no "1..N" header will be printed.
π€ 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.
β¨ diag β¨
$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. π
Okay so real talk: diag() returns false. Why? Because it's so often chained with a failing test ("ok() || diag()") that it just "passes through" the failure, like a bestie holding the door open for you. π«Ά
return ok(...) || diag(...);
π¬ note
$Test->note(@msgs);
Same energy as diag(), but it prints to the output() handle instead β so normally the user won't see it at all unless you're in verbose mode. It's giving "notes app at 2am, only for you." π
π explain
my @dump = $Test->explain(@msgs);
This one dumps the contents of any references in a format a human can actually read. So handy for stuff likeβ¦
is_deeply($have, $want) || diag explain $have;
or
is_deeply($have, $want) || note explain $have;
π€ output / failure_output / todo_output
my $filehandle = $Test->output;
$Test->output($filehandle);
$Test->output($filename);
$Test->output(\$scalar);
These three control where Test::Builder prints its output. They take either an open $filehandle, a $filename to open and write to, or a $scalar reference to append to. And it will always return a $filehandle. Always. β¨
output is where the normal "ok/not ok" test output goes.
Defaults to STDOUT.
failure_output is where the diagnostic output on test failures and diag() goes. It's normally not read by Test::Harness β it gets displayed to the user instead.
Defaults to STDERR.
"todo_output" is used instead of failure_output() for the diagnostics of a failing TODO test. Those bad boys will not be seen by the user.
Defaults to STDOUT.
π reset_outputs
$tb->reset_outputs;
Resets all the output filehandles back to their defaults. Clean slate, fresh start, main character energy. π¦
π€ carp
$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"). Sneaky but useful. iykyk.
π croak
$tb->croak(@message);
Dies with @message, but again the message will appear to come from the point where the original test function was called ("$tb->caller"). Same trick, higher stakes. π
π Test Status and Info
π« no_log_results
This turns off result long-term storage. Fair warning: calling this method will make "details" and "summary" useless. You might want this if you're running enough tests to fill up all available memory.
Test::Builder->new->no_log_results();
There is no way to turn it back on. Not one. It's gone. π
π’ current_test
my $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, ngl.
If you set it forward, the details of the missing tests get filled in as 'unknown'. If you set it backward, the details of the intervening tests get deleted. So yeah, you can erase history if you really want to. π
β is_passing
my $ok = $builder->is_passing;
Tells you if the test suite is currently passing.
More formally: it'll be false if anything has happened that makes it impossible for the test suite to pass. True otherwise.
For example, if no tests have run, is_passing() will be true β because even though a suite with no tests is a failure, you can still add a passing test to it and start passing. Slay.
Don't think about it too much. π§
π summary
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 count as passes. π
Of course, test #1 is $tests[0], etc...
π¬ details
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' reflects 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' tells you if it was a special test. Normal tests have a type of ''. Type can be one of these:
skip see skip()
todo see todo()
todo_skip see todo_skip()
unknown see below
Sometimes the Test::Builder test counter gets incremented without it printing any test output β for example, when current_test() is changed. In those cases Test::Builder doesn't know the result of the test, so its type is 'unknown'. The details for these tests get filled in. They're considered ok, but name and actual_ok are 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'
};
Donut-based test failures, iconic. π
π todo
my $todo_reason = $Test->todo;
my $todo_reason = $Test->todo($pack);
If the current tests are considered "TODO" it returns the reason, if there is one. That reason can come from a $TODO variable or from the last call to todo_start().
Since a TODO test doesn't need a reason, this function can return an empty string even when you're inside a TODO block. Use "$Test->in_todo" to figure out if you're currently inside a TODO block.
todo() is all about finding the right package to look for $TODO in. It's pretty good at guessing the right package β it first looks for the caller based on "$Level + 1", since todo() is usually called inside a test function. As a last resort it'll use exported_to().
Sometimes there's some confusion about where todo() should be looking for the $TODO variable. If you want to be sure, just tell it explicitly what $pack to use. Communication is key bestie. π«Ά
π find_TODO
my $todo_reason = $Test->find_TODO();
my $todo_reason = $Test->find_TODO($pack);
Like todo() but it only returns the value of $TODO, ignoring todo_start(). Strictly old-school.
It can also be used to set $TODO to a new value while returning the old value:
my $old_reason = $Test->find_TODO($pack, 1, $new_reason);
π in_todo
my $in_todo = $Test->in_todo;
Returns true if the test is currently inside a TODO block. Simple as that. β¨
π¬ todo_start
$Test->todo_start();
$Test->todo_start($message);
This method lets you declare all subsequent tests as TODO tests, right up until the "todo_end" method has been called.
The "TODO:" and $TODO syntax is generally pretty good at figuring out whether or not we're in a TODO test. But sometimes we find that this is just not possible to determine β like when we want to use $TODO but the tests are being executed in other packages that can't be inferred beforehand. Annoying, I know.
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 don't judge. π
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. Don't mix, fr fr. π
π todo_end
$Test->todo_end;
Stops running tests as "TODO" tests.
This method is fatal if called without a preceding "todo_start" method call. Like, it will absolutely end you. π
π caller
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().
$height gets added to the level().
If caller() winds up off the top of the stack, it reports the highest context. It's doing its best. π
πͺ EXIT CODES
If all your tests passed, Test::Builder will exit with zero (which is, like, 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) get counted as failures. If no tests were ever run, Test::Builder will throw a warning and exit with 255. And 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'll be reported as 254. So like, yeah, there's a cap. π₯
π§΅ THREADS
In perl 5.8.1 and later, Test::Builder is thread-safe. The test number is shared by all threads β which means if one thread sets the test number using current_test(), they will all be affected. One for all, all for one, periodt.
While versions earlier than 5.8.1 had threads, they contain too many bugs to support. We don't stan. π
Test::Builder is only thread-aware if threads.pm is loaded before Test::Builder. Order matters bestie!
You can directly disable thread support with one of the following:
$ENV{T2_NO_IPC} = 1
or
no Test2::IPC;
or
Test2::API::test2_ipc_disable()
π§ MEMORY
An informative hash, accessible via details(), is stored for each test you perform. So memory usage will scale linearly with each test run. For most test suites this is not a problem, but it can become an issue if you do large (hundred thousands to million) combinatorics tests in the same run. π
In such cases, you're 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. Until then, we cope. π
π EXAMPLES
CPAN can provide the best examples. Test::Simple, Test::More, Test::Exception and Test::Differences all use Test::Builder. Go look at them, they ate. π
π SEE ALSO
π§© INTERNALS
Test2, Test2::API
π°οΈ LEGACY
Test::Simple, Test::More
π EXTERNAL
Test::Harness
π AUTHORS
Okay so the lore: the original code was written by chromatic, and it's been maintained by Michael G Schwern <schwern@pobox.com>. Like, actual legends. Respect the elders bestie π«Ά
πΈ MAINTAINERS
These days the person holding it down is Chad Granum <exodist@cpan.org>. Say thank you. He's carrying the whole testing-industrial complex on his back fr fr π
π COPYRIGHT
The copyright situation, spelled out exactly:
- Copyright 2002-2008 by chromatic
<chromatic@wgz.org>and Michael G Schwern<schwern@pobox.com>.
And the license tea β:
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Hit up the link for the full legal moment: <https://dev.perl.org/licenses/> β that's where the license lives, go read it, it's giving required reading π
and that's the whole page, bestie πβ¨
You just read Test::Builder(3pm) from perl v5.42.3, dated 2026-11-03 β yes, that date is a whole mood, no I will not be explaining it π
Go write some tests. Slay. π
π¦ where this page comes from
- alpine 3.24: perl-doc 5.42.3-r0 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms