Test::Builder(3perl)
π Test::Builder π
okay bestie, so this is the manual page for Test::Builder from the Perl Programmers Reference Guide (that's the third section of the perl manpages, iykyk), and honestly? she's the backstage queen of the whole Perl testing world. let's get into it π«Ά
β¨ NAME β¨
Test::Builder β the backend for building test libraries π
like, she's not the one on stage. she's the one running the lights, the sound, the whole production. no cap.
πΈ 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);
}
see how chill that is? that's literally all it takes to start growing your own test module. iconic.
π¦ DESCRIPTION π¦
so Test::Simple and Test::More are absolute legends, right? everybody loves them. but bestie⦠they're not always flexible enough. and that's where our girl comes in.
Test::Builder gives you a building block π§± so you can write your own test libraries β and the best part? they can all work together. no fighting. no drama. just vibes.
π Construction
new
my $Test = Test::Builder->new;
hands you back a Test::Builder object that represents the current state of the test. that's it, that's the whole job. π
here's the tea tho: since you only ever run one test per program, new always returns the same Test::Builder object. doesn't matter how many times you call new(). same object every single time. that's called a singleton, and she's committed fr. the reason is so that multiple modules can share all that global info β the test counter, where test output is going, all of it. one queen, one kingdom. π
if you want a completely newTest::Builderobject that's different from the singleton, usecreateinstead.
create
my $Test = Test::Builder->create;
ok so yes, there can be more than one Test::Builder object, and this is how you get one. you might reach for 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 the ones created using this method. also, the method name may change in the future. so likeβ¦ tread carefully bestie π«£
subtest
$builder->subtest($name, \&subtests, @args);
go read the documentation of subtest in Test::More β that's where the real explanation lives.
bonus tho: subtest also, and optionally, accepts arguments which will be passed to the subtests reference. cute. π
name
diag $builder->name;
returns the name of the current builder. top level builders default to $0 (that's the name of the executable, bestie). child builders get named via the child method. and if no name is supplied at all? she'll be called "Child of $parent->name". adorable. π₯Ή
reset
$Test->reset;
reinitializes the Test::Builder singleton back to its original state. mostly useful for tests running in persistent environments, where the same test might get run multiple times in the same process. she's basically a factory reset button. π
π Setting up tests
these methods are all about setting up your tests and declaring how many there are. and like β you usually only want to call one of them. not all of them. one. pick your fighter. β¨
plan
$Test->plan('no_plan');
$Test->plan( skip_all => $reason );
$Test->plan( tests => $num_tests );
the convenient lil way to set up your tests. call this and Test::Builder will print the appropriate headers and take the appropriate actions. easy peasy. πΈ
if you call plan(), don't call any of the other methods below. seriously. don't.
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 while she's at it. π
no_plan
$Test->no_plan;
declares that this test will run an indeterminate number of tests. chaotic, but valid. π¦
done_testing
$Test->done_testing();
$Test->done_testing($num_tests);
declares that you are done testing β no more tests will run after this point. periodt.
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 this contradicts it, a failing test will be run to reflect the planning mistake. oops. π and if no_plan was declared, this will override.
if done_testing() is called twice, the second call will issue a failing test. so like⦠don't do that.
if $num_tests is omitted, the number of tests run will be used, like no_plan.
done_testing() is, in effect, what you'd use when you'd want no_plan β but safer. you'd use it like so:
$Test->ok($a == $b);
$Test->done_testing();
or, if you're planning 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- an integer β the number of expected tests
skip_all
$Test->skip_all;
$Test->skip_all($reason);
skips all the tests, using the given $reason. then exits immediately with 0. bye bestie π
exported_to
my $pack = $Test->exported_to;
$Test->exported_to($pack);
tells Test::Builder what package you exported your functions to.
ngl, this method isn't terribly useful β because 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 are the ones that actually run the tests, analogous to the functions in Test::More.
they all return true if the test passed, false if the test failed.
and $name? always optional, always. π
ok
$Test->ok($test, $name);
your basic test. pass if $test is true, fail if $test is false. just like Test::Simple's ok(). the classic. the blueprint. β¨
is_eq
$Test->is_eq($got, $expected, $name);
like Test::More's is(). checks if "$got eq $expected". this is the string version.
and heads up: "undef" only ever matches another "undef". no exceptions. π
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" here too. π«Ά
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. the hater check. π
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 used in the course of writing a test β but they are not themselves tests. side characters with main character energy, honestly. π
BAIL_OUT
$Test->BAIL_OUT($reason);
indicates to the Test::Harness that things are going SO badly that all testing should terminate. and yes, that includes running any additional test scripts. it's giving emergency evacuation π¨
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. so like, if you're building the tester, not the test. π
maybe_regex
$Test->maybe_regex(qr/$regex/);
$Test->maybe_regex('/$regex/');
okay so 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. RIP to a real one. π
but for the record: it's a 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. yes or no, that's it. π
β 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);
}
and to be polite to other functions wrapping your own, you usually want to increment $Level rather than set it to a constant. be a good neighbor bestie π
use_numbers
$Test->use_numbers($on_or_off);
whether or not the test should output numbers. so like, 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 β like when threads or forking is involved. chaos energy fr π
defaults to on.
no_diag
$Test->no_diag($no_diag);
if set true, no diagnostics will be printed. and yes, that 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. she justβ¦ stops. π«
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.
good news: it's ok for your test to change where STDOUT and STDERR point to β Test::Builder's default output settings will not be affected. she has her own spotify queue and she's not switching it for anybody. π§
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. and a newline will be put on the end if there isn't one already.
we encourage using this rather than calling print directly. seriously. use it. π«Ά
Returns false. Why tho? π Because diag() is almost always bestie-coded right next to a failing test (ok() || diag()), so it passes through the failure β it doesn't eat it, it just hands it back to you.
return ok(...) || diag(...);
β¨ note β¨
$Test->note(@msgs);
Basically diag()'s sibling but with a whole different vibe check: it prints to the output() handle instead. Which means the user normally never sees it unless they've got verbose mode on. It's giving "note to self, but public if you ask nicely" π
β¨ explain β¨
my @dump = $Test->explain(@msgs);
This one dumps the contents of any references in a human readable format. So handy for stuff like...
is_deeply($have, $want) || diag explain $have;
or
is_deeply($have, $want) || note explain $have;
no cap, that's the whole bit π¦
β¨ output / failure_output / todo_output β¨
my $filehandle = $Test->output;
$Test->output($filehandle);
$Test->output($filename);
$Test->output(\$scalar);
These three are the ones in charge of where Test::Builder actually prints its stuff. What do they take? Any of:
- an already-open
$filehandleπ«Ά - a
$filenameto open and write to - a
$scalarreference to append to
And it will always return a $filehandle. Periodt.
output β this is where normal "ok/not ok" test output goes. Defaults to STDOUT.
failure_output β this is where the diagnostic output on test failures, plus diag(), goes. It is normally not read by Test::Harness, and instead gets displayed straight to the user. Defaults to STDERR.
"todo_output" β this one 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.
β¨ reset_outputs β¨
$tb->reset_outputs;
Resets all the output filehandles back to their defaults. Clean slate 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 little misdirection, we love her.
β¨ croak β¨
$tb->croak(@message);
Same deal as carp, except it dies with @message β and again, the message will appear to come from the point where the original test function was called ($tb->caller). π
π Test Status and Info π
no_log_results
This turns off result long-term storage. Calling this method will make "details" and "summary" useless. You might want it if you're running enough tests to fill up all available memory.
Test::Builder->new->no_log_results();
β οΈ Bestie. There is no way to turn it back on. It's one-way. π¨
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, fr fr.
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. (Main character move, honestly.)
is_passing
my $ok = $builder->is_passing;
Indicates if the test suite is currently passing.
More formally: it'll 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, is_passing() 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. π
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 are 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' 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'
};
todo
my $todo_reason = $Test->todo;
my $todo_reason = $Test->todo($pack);
If the current tests are considered "TODO" it will return the reason, if any. That reason can come from a $TODO variable or 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 to look at. It first looks for the caller based on "$Level + 1", since todo() is usually called inside a test function. As a last resort it will use exported_to().
Sometimes there's 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. π
find_TODO
my $todo_reason = $Test->find_TODO();
my $todo_reason = $Test->find_TODO($pack);
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:
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. That's it, that's the whole method. π
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 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. Don't mix, bestie, it's giving chaos. π¦
"todo_end"
$Test->todo_end;
Stops running tests as "TODO" tests. This method is fatal if called without a preceding "todo_start" method call. π
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 will be added to the level().
If caller() winds up off the top of the stack it reports the highest context. π
π EXIT CODES π
If all your tests passed, Test::Builder will exit with zero (which is normal, the standard, the default slay). 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. (RIP, the count caps out. π)
π§΅ THREADS π§΅
In perl 5.8.1 and later, Test::Builder is thread-safe. The test number is shared by all threads. This means if one thread sets the test number using current_test() they will all be affected.
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.
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. 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. (we're waiting patiently π«Ά)
πΈ EXAMPLES πΈ
CPAN can provide the best examples. Test::Simple, Test::More, Test::Exception and Test::Differences all use Test::Builder. If you want inspo, that's where the inspo lives. β¨
π SEE ALSO π
INTERNALS
Test2, Test2::API
LEGACY
Test::Simple, Test::More
EXTERNAL
Test::Harness
π AUTHORS π
Ok so the origin story!! π
- The original code was written by chromatic β lowkey a legend for this fr
- and it's maintained by Michael G Schwern β hit him up at
schwern@pobox.comif you gotta π«Ά
π οΈ MAINTAINERS π οΈ
The person holding it down these days is:
- Chad Granum β
exodist@cpan.orgβ¨
bestie if you're filing a bug, this is your guy, no cap π
Β©οΈ COPYRIGHT Β©οΈ
The legal tea, and we're keeping every single word of it β:
Copyright 2002-2008 by chromatic <chromatic@wgz.org> and Michael G Schwern <schwern@pobox.com>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. π
See <https://dev.perl.org/licenses/> for the whole licensing situation β go read it, iykyk π
ok and that's literally the whole page, we made it π thank you for coming to my TED talk, you're now a Test::Builder main character, go write some tests and slay π
this was Test::Builder(3perl) β perl v5.44.0, dated 2026-10-17 πΈ byeeee bestie π¦
π¦ where this page comes from
- arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms