Test::More(3)
π Test::More(3) β yet another framework for writing test scripts π
ok so bestie, welcome to Test::More(3) β the Perl testing module that's literally the moment. It ships with Perl's user-contributed docs, and it's the one everybody reaches for when they wanna write test scripts that actually tell them what went wrong. Buckle up, we're doing this properly. π
β¨ NAME β¨
Test::More β yet another framework for writing test scripts. Yes, "yet another." It's humble like that. π
πΈ SYNOPSIS πΈ
Like, here's the whole vibe at a glance:
use Test::More tests => 23;
# or
use Test::More skip_all => $reason;
# or
use Test::More; # see done_testing()
require_ok( 'Some::Module' );
# Various ways to say "ok"
ok($got eq $expected, $test_name);
is ($got, $expected, $test_name);
isnt($got, $expected, $test_name);
# Rather than print STDERR "# here's what went wrong\n"
diag("here's what went wrong");
like ($got, qr/expected/, $test_name);
unlike($got, qr/expected/, $test_name);
cmp_ok($got, '==', $expected, $test_name);
is_deeply($got_complex_structure, $expected_complex_structure, $test_name);
SKIP: {
skip $why, $how_many unless $have_some_feature;
ok( foo(), $test_name );
is( foo(42), 23, $test_name );
};
TODO: {
local $TODO = $why;
ok( foo(), $test_name );
is( foo(42), 23, $test_name );
};
can_ok($module, @methods);
isa_ok($object, $class);
pass($test_name);
fail($test_name);
BAIL_OUT($why);
# UNIMPLEMENTED!!!
my @status = Test::More::status;
Iconic. No notes. π
π DESCRIPTION π
π STOP! If you're just getting started writing tests, have a look at Test2::Suite first.
Okay so context: this module is a drop-in replacement for Test::Simple β you can switch over to it once you've got the hang of basic testing. Bestie glow-up moment. β¨
The whole point of this module is to hand you a wide range of testing utilities. Various ways to say "ok" with better diagnostics, plus facilities to skip tests, test future features, and compare complicated data structures. Like, you can do almost anything with a plain ok() function, but it doesn't give you good diagnostic output, and that's the whole tragedy. π
π I love it when a plan comes together
Before anything else, you need a testing plan. It's basically declaring how many tests your script is gonna run, and it protects you against premature failure. Manifesting a clean test run. π¦
The preferred way to do this is to declare a plan right when you use Test::More:
use Test::More tests => 23;
There are cases when you won't know beforehand how many tests your script is gonna run. In that case, you declare your tests at the end:
use Test::More;
... run your tests ...
done_testing( $number_of_tests_run );
β οΈ NOTE:done_testing()should never be called in anEND { ... }block. Fr fr, don't do it.
Sometimes you genuinely don't know how many tests were run, or it's just too difficult to calculate. In which case, you can leave off $number_of_tests_run. Cute and low-effort. π
In some cases, you'll wanna completely skip an entire testing script:
use Test::More skip_all => $skip_reason;
Your script will declare a skip with the reason why you skipped, and exit immediately with a zero (success). See Test::Harness for details. iykyk.
If you want to control what functions Test::More will export, you have to use the 'import' option. For example, to import everything but 'fail', you'd do:
use Test::More tests => 23, import => ['!fail'];
Alternatively, you can use the plan() function. Super useful for when you have to calculate the number of tests:
use Test::More;
plan tests => keys %Stuff * 3;
Or for deciding between running the tests at all:
use Test::More;
if( $^O eq 'MacOS' ) {
plan skip_all => 'Test irrelevant on MacOS';
}
else {
plan tests => 42;
}
π done_testing
done_testing();
done_testing($number_of_tests);
If you don't know how many tests you're gonna run, you can issue the plan when you're done running tests. Procrastination but make it valid. β¨
$number_of_tests is the same as plan() β it's the number of tests you expected to run. You can omit this, in which case the number of tests you ran doesn't matter; all that matters is the fact that your tests ran to conclusion. Slay.
This is safer than and replaces the "no_plan" plan. π
β οΈ Note: You must never putdone_testing()inside anEND { ... }block. The plan is there to ensure your test does not exit before testing has completed. If you use an END block you completely bypass this protection. Like, that's the whole shield, gone. π
π¦ Test names
By convention, each test is assigned a number in order. This is largely done automatically for you. However, it's often very useful to assign a name to each test. Which would you rather see?
ok 4
not ok 5
ok 6
or
ok 4 - basic multi-variable
not ok 5 - simple exponential
ok 6 - force == mass * acceleration
The latter gives you some idea of what failed. It also makes it easier to find the test in your script β simply search for "simple exponential". Searchable, findable, iconic. π
All test functions take a name argument. It's optional, but highly suggested that you use it. Please. For me. π«Ά
π I'm ok, you're not ok.
The basic purpose of this module is to print out either "ok #" or "not ok #" depending on if a given test succeeded or failed. Everything else is just gravy. π
All of the following print "ok" or "not ok" depending on if the test succeeded or failed. They all also return true or false, respectively.
π ok
ok($got eq $expected, $test_name);
This simply evaluates any expression ("$got eq $expected" is just a simple example) and uses that to determine if the test succeeded or failed. A true expression passes, a false one fails. Very simple. No cap, that's it.
For example:
ok( $exp{9} == 81, 'simple exponential' );
ok( Film->can('db_Main'), 'set_db()' );
ok( $p->tests == 4, 'saw tests' );
ok( !grep(!defined $_, @items), 'all items defined' );
(Mnemonic: "This is ok.") β¨
$test_name is a very short description of the test that will be printed out. It makes it very easy to find a test in your script when it fails, and gives others an idea of your intentions. $test_name is optional, but we very strongly encourage its use. Do it for the plot. π
Should an ok() fail, it will produce some diagnostics:
not ok 18 - sufficient mucus
# Failed test 'sufficient mucus'
# in foo.t at line 42.
This is the same as Test::Simple's ok() routine. Same energy, different module.
π§ is / isnt
is ( $got, $expected, $test_name );
isnt( $got, $expected, $test_name );
Similar to ok(), is() and isnt() compare their two arguments with "eq" and "ne" respectively, and use the result of that to determine if the test succeeded or failed. So these:
# Is the ultimate answer 42?
is( ultimate_answer(), 42, "Meaning of Life" );
# $foo isn't empty
isnt( $foo, '', "Got some foo" );
are similar to these:
ok( ultimate_answer() eq 42, "Meaning of Life" );
ok( $foo ne '', "Got some foo" );
"undef" will only ever match "undef". So you can test a value against "undef" like this:
is($not_defined, undef, "undefined as expected");
(Mnemonic: "This is that." "This isn't that.") π
So why use these? They produce better diagnostics on failure. ok() cannot know what you are testing for (beyond the name), but is() and isnt() know what the test was and why it failed. For example this test:
my $foo = 'waffle'; my $bar = 'yarblokos';
is( $foo, $bar, 'Is foo the same as bar?' );
Will produce something like this:
not ok 17 - Is foo the same as bar?
# Failed test 'Is foo the same as bar?'
# in foo.t at line 139.
# got: 'waffle'
# expected: 'yarblokos'
So you can figure out what went wrong without rerunning the test. Diagnostics ATE. Left no crumbs. π
You are encouraged to use is() and isnt() over ok() where possible, however do not be tempted to use them to find out if something is true or false!
# XXX BAD!
is( exists $brooklyn{tree}, 1, 'A tree grows in Brooklyn' );
This does not check if "exists $brooklyn{tree}" is true β it checks if it returns 1. Very different. Similar caveats exist for false and 0. In these cases, use ok().
ok( exists $brooklyn{tree}, 'A tree grows in Brooklyn' );
A simple call to isnt() usually does not provide a strong test, but there are cases when you cannot say much more about a value than that it is different from some other value:
new_ok $obj, "Foo";
my $clone = $obj->clone;
isa_ok $obj, "Foo", "Foo->clone";
isnt $obj, $clone, "clone() produces a different object";
Historically we supported an "isn't()" function as an alias of isnt(), however in Perl 5.37.9 support for the use of apostrophe as a package separator was deprecated and by Perl 5.42.0 support for it will have been removed completely. Accordingly, use of "isn't()" is also deprecated, and will produce warnings when used unless 'deprecated' warnings are specifically disabled in the scope where it is used. You are strongly advised to migrate to using isnt() instead. Like, it's giving legacy code. Don't be legacy code. π
πΈ like
like( $got, qr/expected/, $test_name );
Similar to ok(), like() matches $got against the regex "qr/expected/".
So this:
like($got, qr/expected/, 'this is like that');
is similar to:
ok( $got =~ m/expected/, 'this is like that');
(Mnemonic "This is like that".) π
The second argument is a regular expression. It may be given as a regex reference (i.e. "qr//") or (for better compatibility with older perls) as a string that looks like a regex (alternative delimiters are currently not supported):
like( $got, '/expected/', 'this is like that' );
Regex options may be placed on the end ('/expected/i'). Fancy. β¨
Its advantages over ok() are similar to that of is() and isnt(): better diagnostics on failure. Better diagnostics = better life.
π unlike
unlike( $got, qr/expected/, $test_name );
Works exactly as like(), only it checks if $got does not match the given pattern. Same icon behavior, opposite direction. π¦
π₯ cmp_ok
cmp_ok( $got, $op, $expected, $test_name );
Halfway between ok() and is() lies cmp_ok(). This allows you to compare two arguments using any binary perl operator. The test passes if the comparison is true and fails otherwise. Versatility queen. π
# ok( $got eq $expected );
cmp_ok( $got, 'eq', $expected, 'this eq that' );
# ok( $got == $expected );
cmp_ok( $got, '==', $expected, 'this == that' );
# ok( $got && $expected );
cmp_ok( $got, '&&', $expected, 'this && that' );
...etc...
Its advantage over ok() is when the test fails you'll know what $got and $expected were:
...and when it flops, the output is giving:
not ok 1
# Failed test in foo.t at line 12.
# '23'
# &&
# undef
It's also lowkey a lifesaver when you're comparing numbers and is()'s use of eq would just get in the way and start drama:
cmp_ok( $big_hairy_number, '==', $another_big_hairy_number );
And it's especially iconic when you need a greater-than or smaller-than situation between values:
cmp_ok( $some_value, '<=', $upper_limit );
can_ok πͺ
can_ok($module, @methods);
can_ok($object, @methods);
Checks that the $module or $object can actually do these @methods (works with plain functions too, bestie, not just methods).
can_ok('Foo', qw(this that whatever));
is almost exactly like saying:
ok( Foo->can('this') &&
Foo->can('that') &&
Foo->can('whatever')
);
only without all the typing and with a way nicer interface. Handy for quickly vibe-checking an interface, fr.
No matter how many @methods you check, a single can_ok() call counts as one test. If you're not about that life, do this instead:
foreach my $meth (@methods) {
can_ok('Foo', $meth);
}
isa_ok π
isa_ok($object, $class, $object_name);
isa_ok($subclass, $class, $object_name);
isa_ok($ref, $type, $ref_name);
Checks whether the given $object->isa($class). It also checks that the object was defined in the first place β because nothing ruins a test suite like an undef blowing up mid-run. Handy for this sort of thing:
my $obj = Some::Module->new;
isa_ok( $obj, 'Some::Module' );
where you'd otherwise have to write:
my $obj = Some::Module->new;
ok( defined $obj && $obj->isa('Some::Module') );
to safeguard against your test script absolutely perishing on the spot.
You can also test a class, to make sure it has the right ancestor:
isa_ok( 'Vole', 'Rodent' );
It works on references, too:
isa_ok( $array_ref, 'ARRAY' );
The diagnostics of this test normally just refer to 'the object'. If you want them to be more specific, you can supply an $object_name (for example 'Test customer') β cute AND informative.
new_ok β¨
my $obj = new_ok( $class );
my $obj = new_ok( $class => \@args );
my $obj = new_ok( $class => \@args, $object_name );
A convenience function that combines creating an object and calling isa_ok() on that object. Two birds, one slay.
It's basically equivalent to:
my $obj = $class->new(@args);
isa_ok $obj, $class, $object_name;
If @args is not given, an empty list will be used.
This function only works on new() and it assumes new() will return just a single object which isa $class. That's the whole deal, no cap.
subtest π
subtest $name => \&code, @args;
subtest() runs the &code as its own little test with its own plan and its own result. The main test counts this as a single test, using the result of the whole subtest to decide if it's ok or not ok. Nested tests, main character energy.
For example...
use Test::More tests => 3;
pass("First test");
subtest 'An example subtest' => sub {
plan tests => 2;
pass("This is a subtest");
pass("So is this");
};
pass("Third test");
This would produce:
1..3
ok 1 - First test
# Subtest: An example subtest
1..2
ok 1 - This is a subtest
ok 2 - So is this
ok 2 - An example subtest
ok 3 - Third test
A subtest may call skip_all. No tests will be run, but the subtest is considered a skip. Respectful, honestly.
subtest 'skippy' => sub {
plan skip_all => 'cuz I said so';
pass('this test will never be run');
};
Returns true if the subtest passed, false otherwise.
Due to how subtests work, you may omit a plan if you desire. This adds an implicit done_testing() to the end of your subtest. The following two subtests are equivalent:
subtest 'subtest with implicit done_testing()', sub {
ok 1, 'subtests with an implicit done testing should work';
ok 1, '... and support more than one test';
ok 1, '... no matter how many tests are run';
};
subtest 'subtest with explicit done_testing()', sub {
ok 1, 'subtests with an explicit done testing should work';
ok 1, '... and support more than one test';
ok 1, '... no matter how many tests are run';
done_testing();
};
Extra arguments given to subtest are passed to the callback. For example:
sub my_subtest {
my $range = shift;
...
}
for my $range (1, 10, 100, 1000) {
subtest "testing range $range", \&my_subtest, $range;
}
pass / fail π«Ά
pass($test_name);
fail($test_name);
Sometimes you just want to say that the tests have passed. Usually the case is you've got some complicated condition that is difficult to wedge into an ok(). In this case, you can simply use pass() (to declare the test ok) or fail() (for not ok). They are synonyms for ok(1) and ok(0).
Use these very, very, very sparingly. Like, seriously bestie, sparingly. π«£
π§ͺ Module tests
Sometimes you want to test if a module, or a list of modules, can successfully load. For example, you'll often want a first test which simply loads all the modules in the distribution to make sure they work before going on to do more complicated testing.
For such purposes we have use_ok and require_ok.
require_ok π¦
require_ok($module);
require_ok($file);
Tries to require the given $module or $file. If it loads successfully, the test will pass. Otherwise it fails and displays the load error.
require_ok will guess whether the input is a module name or a filename. Psychic, but make it Perl.
No exception will be thrown if the load fails. It's chill like that.
# require Some::Module
require_ok "Some::Module";
# require "Some/File.pl";
require_ok "Some/File.pl";
# stop testing if any of your modules will not load
for my $module (@module) {
require_ok $module or BAIL_OUT "Can't load $module";
}
use_ok π₯
BEGIN { use_ok($module); }
BEGIN { use_ok($module, @imports); }
Like require_ok, but it will use the $module in question β and it only loads modules, not files.
If you just want to test a module can be loaded, use require_ok.
If you just want to load a module in a test, we recommend simply using use directly. It will cause the test to stop.
It's recommended that you run use_ok() inside a BEGIN block so its functions are exported at compile-time and prototypes are properly honored. Trust the process. β¨
If @imports are given, they are passed through to the use. So this:
BEGIN { use_ok('Some::Module', qw(foo bar)) }
is like doing this:
use Some::Module qw(foo bar);
Version numbers can be checked like so:
# Just like "use Some::Module 1.02"
BEGIN { use_ok('Some::Module', 1.02) }
Don't try to do this:
BEGIN {
use_ok('Some::Module');
...some code that depends on the use...
...happening at compile time...
}
because the notion of "compile-time" is relative. Instead, you want:
BEGIN { use_ok('Some::Module') }
BEGIN { ...some code that depends on the use... }
If you want the equivalent of use Foo () β use a module but not import anything β use require_ok.
BEGIN { require_ok "Foo" }
π§© Complex data structures
Not everything is a simple eq check or regex. There are times you need to see if two data structures are equivalent. For these instances Test::More provides a handful of useful functions.
NOTE: I'm not quite sure what will happen with filehandles. π (That's a direct quote from the docs, bestie β don't shoot the messenger.)
is_deeply π
is_deeply( $got, $expected, $test_name );
Similar to is(), except that if $got and $expected are references, it does a deep comparison, walking each data structure to see if they're equivalent. If the two structures are different, it will display the place where they start differing. So helpful, honestly.
is_deeply() compares the dereferenced values of references; the references themselves (except for their type) are ignored. This means aspects such as blessing and ties are not considered "different".
is_deeply() currently has very limited handling of function reference and globs. It merely checks if they have the same referent. This may improve in the future.
Test::Differences and Test::Deep provide more in-depth functionality along these lines.
NOTE:is_deeply()has limitations when it comes to comparing strings and refs:perl my $path = path('.'); my $hash = {}; is_deeply( $path, "$path" ); # ok is_deeply( $hash, "$hash" ); # failThis happens becauseis_deeplywill unoverload all arguments unconditionally. It is probably best not to useis_deeplywith overloading. For legacy reasons this is not likely to ever be fixed. If you would like a much better tool for this you should see Test2::Suite β specifically Test2::Tools::Compare has anis()function that works likeis_deeplywith many improvements. π
π©Ί Diagnostics
If you pick the right test function, you'll usually get a good idea of what went wrong when it failed. But sometimes it doesn't work out that way. So here we have ways for you to write your own diagnostic messages, which are safer than just print STDERR.
diag π¬
diag(@diagnostic_message);
Prints a diagnostic message which is guaranteed not to interfere with test output. Like print, @diagnostic_message is simply concatenated together.
Returns false, so as to preserve failure. Sneaky but correct.
Handy for this sort of thing:
ok( grep(/foo/, @users), "There's a foo user" ) or
diag("Since there's no foo, check that /etc/bar is set up right");
which would produce:
not ok 42 - There's a foo user
# Failed test 'There's a foo user'
# in foo.t at line 52.
# Since there's no foo, check that /etc/bar is set up right.
You might remember ok() or diag() with the mnemonic open() or die(). Brain hack, you're welcome. π§ β¨
NOTE: The exact formatting of the diagnostic output is still changing, but it is guaranteed that whatever you throw at it won't interfere with the test. Pinky promise. π«Ά
note
note(@diagnostic_message);
okay so this is literally diag()'s chill sibling π
same energy, except the message won't show up when the test runs inside a harness β it only peeks out in the verbose TAP stream. So it's the icon for dropping lil notes that might help you debug later, without screaming "PROBLEM" at anyone. No cap.
note("Tempfile is $tempfile");
explain
my @dump = explain @diagnostic_message;
this one dumps the contents of any references in a human readable format β¨ and usually you're gonna wanna feed the result straight into "note" or "diag". It's giving helpful bestie energy.
Handy for things like...
is_deeply($have, $want) || diag explain $have;
or
note explain \%args;
Some::Class->method(%args);
Conditional tests π¦
Sometimes running a test under certain conditions will straight-up cause the test script to die π A certain function or method isn't implemented (like fork() on MacOS), some resource isn't available (like a net connection), or a module isn't available. In these cases it's necessary to skip tests, or declare that they're supposed to fail but will work in the future (a todo test).
For more deets on the mechanics of skip and todo tests, go look at Test::Harness π
The way Test::More handles this is with a named block. Basically, a block of tests that can be skipped over or made todo. Honestly it's best if I just show you...
SKIP: BLOCK
SKIP: {
skip $why, $how_many if $condition;
...normal testing code goes here...
}
This declares a block of tests that might be skipped β $how_many says how many tests there are, $why says why, and $condition says when to skip them. An example is literally the easiest way to illustrate:
SKIP: {
eval { require HTML::Lint };
skip "HTML::Lint not installed", 2 if $@;
my $lint = new HTML::Lint;
isa_ok( $lint, "HTML::Lint" );
$lint->parse( $html );
is( $lint->errors, 0, "No errors found in HTML" );
}
If the user doesn't have HTML::Lint installed, the whole block of code won't be run at all π«Ά Test::More will output special ok's which Test::Harness interprets as skipped but passing tests.
It's super important that $how_many accurately reflects the number of tests in the SKIP block so the number of tests run will match up with your plan π If your plan is "no_plan" then $how_many is optional and will default to 1.
It's perfectly safe to nest SKIP blocks, bestie β nest away. But each SKIP block must have the label "SKIP", or Test::More can't work its magic β¨
You do not skip tests which are failing because there's a bug in your program, or for which you don't yet have code written. For that you use TODO. Read on π
TODO: BLOCK
TODO: {
local $TODO = $why if $condition;
...normal testing code goes here...
}
Declares a block of tests you expect to fail, plus $why. Maybe it's because you haven't fixed a bug or haven't finished a new feature π
TODO: {
local $TODO = "URI::Geller not finished";
my $card = "Eight of clubs";
is( URI::Geller->your_card, $card, 'Is THIS your card?' );
my $spoon;
URI::Geller->bend_spoon;
is( $spoon, 'bent', "Spoon bending, that's original" );
}
With a todo block, the tests inside are expected to fail. Test::More will run the tests normally, but print out special flags indicating they're "todo". Test::Harness will interpret failures as being ok π Should anything succeed, it will report it as an unexpected success β so you immediately know the thing you had todo is done and you can remove the TODO flag π
The nice part about todo tests, as opposed to simply commenting out a block of tests, is that it's like having a programmatic todo list π You know how much work is left to be done, you're aware of what bugs there are, and you'll know immediately when they're fixed. Obsessed.
Once a todo test starts succeeding, simply move it outside the block. When the block is empty, delete it. Periodt.
Note that, if you leave $TODO unset or undef, Test::More reports failures as normal. This can be useful to mark the tests as expected to fail only in certain conditions, e.g.:
TODO: {
local $TODO = "$^O doesn't work yet. :(" if !_os_is_supported($^O);
...
}
todo_skip
TODO: {
todo_skip $why, $how_many if $condition;
...normal testing code...
}
With todo tests, it's best to have the tests actually run β that way you'll know when they start passing π Sometimes this isn't possible though. Often a failing test will cause the whole program to die or hang, even inside an "eval BLOCK" with and using "alarm" π In these extreme cases you have no choice but to skip over the broken tests entirely.
The syntax and behavior is similar to a "SKIP: BLOCK" except the tests will be marked as failing but todo. Test::Harness will interpret them as passing π«Ά
When do I use SKIP vs. TODO?
If it's something the user might not be able to do, use SKIP. This includes optional modules that aren't installed, running under an OS that doesn't have some feature (like fork() or symlinks), or maybe you need an Internet connection and one isn't available π
If it's something the programmer hasn't done yet, use TODO. This is for any code you haven't written yet, or bugs you have yet to fix, but wanna put tests for in your testing script (always a good idea btw π
).
Test control π
BAIL_OUT
BAIL_OUT($reason);
Indicates to the harness that things are going so badly that all testing should terminate π This includes the running of any additional test scripts.
This is typically used when testing cannot continue β like a critical module failing to compile, or a necessary external utility not being available, like a database connection failing.
The test will exit with 255.
For even better control look at Test::Most β¨
Discouraged comparison functions π
The use of the following functions is discouraged because they are not actually testing functions and produce no diagnostics to help figure out what went wrong π They were written before is_deeply() existed because I couldn't figure out how to display a useful diff of two arbitrary data structures.
These functions are usually used inside an ok():
ok( eq_array(\@got, \@expected) );
is_deeply() can do that better and with diagnostics β¨
is_deeply( \@got, \@expected );
They may be deprecated in future versions π
eq_array
my $is_eq = eq_array(\@got, \@expected);
Checks if two arrays are equivalent. This is a deep check, so multi-level structures are handled correctly π§
eq_hash
my $is_eq = eq_hash(\%got, \%expected);
Determines if the two hashes contain the same keys and values. This is a deep check.
eq_set
my $is_eq = eq_set(\@got, \@expected);
Similar to eq_array(), except the order of the elements is not important. This is a deep check, but the irrelevancy of order only applies to the top level.
ok( eq_set(\@got, \@expected) );
Is better written:
is_deeply( [sort @got], [sort @expected] );
NOTE By historical accident, this is not a true set comparison. While the order of elements does not matter, duplicate elements do.
NOTEeq_set()does not know how to deal with references at the top level. The following is an example of a comparison which might not work:perl eq_set([\1, \2], [\2, \1]);
Test::Deep contains much better set comparison functions π
Extending and Embedding Test::More π
Sometimes the Test::More interface isn't quite enough. Fortunately, Test::More is built on top of Test::Builder, which provides a single, unified backend for any test library to use π«Ά This means two test libraries which both use Test::Builder can be used together in the same program. Slay.
If you simply wanna do a little tweaking of how the tests behave, you can access the underlying Test::Builder object like so:
builder
my $test_builder = Test::More->builder;
Returns the Test::Builder object underlying Test::More for you to play with β¨
EXIT CODES π
If all your tests passed, Test::Builder will exit with zero (which is normal, iconic, no notes). 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 This behavior may go away in future versions.
β¨ COMPATIBILITY β¨
Okay so the tea β: Test::More works with Perls as old as 5.8.1. Like, genuinely ancient. Respect the elders π.
Thread support is not very reliable before 5.10.1 β but honestly, that's because threads themselves were not very reliable before 5.10.1. Not our fault, bestie π.
So here's the situation: even though Test::More has been a core module in versions of Perl since 5.6.2, it has evolved since then, and not all of the features you're used to will be present in the shipped version. If you're writing a module, don't forget to indicate in your package metadata the minimum version of Test::More that you require. For example, if you want to use done_testing() but want your test script to run on Perl 5.10.0, you will need to explicitly require Test::More > 0.88.
Key feature milestones, because the timeline is kind of iconic π:
- subtests β Subtests were released in
Test::More 0.94, which came with Perl5.12.0. Subtests did not implicitly calldone_testing()until0.96; the first Perl with that fix was Perl5.14.0with0.98. done_testing()β This was released inTest::More 0.88and first shipped with Perl in5.10.1as part ofTest::More 0.92.cmp_ok()β Althoughcmp_ok()was introduced in0.40,0.86fixed an important bug to make it safe for overloaded objects; the fixed one first shipped with Perl in5.10.1as part ofTest::More 0.92.new_ok()note()andexplain()β These were released inTest::More 0.82, and first shipped with Perl in5.10.1as part ofTest::More 0.92.
There's a full version history in the Changes file, and the Test::More versions included as core can be found using Module::CoreList:
$ corelist -a Test::More
π CAVEATS and NOTES π
π UTF-8 / "Wide character in print"
If you use UTF-8 or other non-ASCII characters with Test::More you might get a "Wide character in print" warning. And before you come for me β using binmode STDOUT, ":utf8" will not fix it. Nope. Because Test::Builder (which powers Test::More) duplicates STDOUT and STDERR. So any changes to them, including changing their output disciplines, will not be seen by Test::More. It's giving "I don't know her" π
.
One work around is to apply encodings to STDOUT and STDERR as early as possible and before Test::More (or any other Test module) loads:
use open ':std', ':encoding(UTF-8)';
use Test::More;
A more direct work around is to change the filehandles used by Test::Builder:
my $builder = Test::More->builder;
binmode $builder->output, ":encoding(UTF-8)";
binmode $builder->failure_output, ":encoding(UTF-8)";
binmode $builder->todo_output, ":encoding(UTF-8)";
π¦ Overloaded objects
String overloaded objects are compared as strings (or in cmp_ok()'s case, strings or numbers as appropriate to the comparison op). This prevents Test::More from piercing an object's interface, allowing better blackbox testing. So if a function starts returning overloaded objects instead of bare strings, your tests won't notice the difference. This is good. Slay, honestly β¨.
However, it does mean that functions like is_deeply() cannot be used to test the internals of string overloaded objects. In this case the author would suggest Test::Deep, which contains more flexible testing functions for complex data structures.
π§΅ Threads
Test::More will only be aware of threads if use threads has been done before Test::More is loaded. This is ok:
use threads;
use Test::More;
This may cause problems:
use Test::More
use threads;
5.8.1 and above are supported. Anything below that has too many bugs. Periodt π.
π HISTORY π
This is a case of convergent evolution with Joshua Pritikin's Test module. The author was largely unaware of its existence when he'd first written his own ok() routines. This module exists because he couldn't figure out how to easily wedge test names into Test's interface (along with a few other problems).
The goal here is to have a testing utility that's simple to learn, quick to use and difficult to trip yourself up with, while still providing more flexibility than the existing Test.pm. As such, the names of the most common routines are kept tiny, special cases and magic side-effects are kept to a minimum. WYSIWYG. π
π₯ SEE ALSO π₯
β ALTERNATIVES
Test2::Suiteis the most recent and modern set of tools for testing.Test::Simpleβ pick this if all this confuses you and you just want to write some tests. You can upgrade toTest::Morelater (it's forward compatible). Glow-up potential π¦.Test::Legacyβ tests written withTest.pm, the original testing module, do not play well with other testing libraries.Test::Legacyemulates theTest.pminterface and does play well with others.
πΈ ADDITIONAL LIBRARIES
Test::Differencesfor more ways to test complex data structures. And it plays well withTest::More.Test::Classis like xUnit but more perlish.Test::Deepgives you more powerful complex data structure testing.Test::Inlineshows the idea of embedded testing.Mock::Quickβ the ultimate mocking library. Easily spawn objects defined on the fly. Can also override, block, or reimplement packages as needed.Test::FixtureBuilderβ quickly define fixture data for unit tests.
π OTHER COMPONENTS
Test::Harnessis the test runner and output interpreter for Perl. It's the thing that powersmake testand where theproveutility comes from. Main character energy, lowkey π.
π BUNDLES
Test::Mostβ most commonly needed test functions and features.
π± ENVIRONMENT VARIABLES π±
See Test2::Env for a list of meaningful environment variables.
π AUTHORS π
Michael G Schwern <schwern@pobox.com> with much inspiration from Joshua Pritikin's Test module and lots of help from Barrie Slaymaker, Tony Bowden, blackstar.co.uk, chromatic, Fergal Daly and the perl-qa gang. π«Ά
π§ MAINTAINERS π§
Chad Granum <exodist@cpan.org>
π BUGS π
See <https://github.com/Test-More/test-more/issues> to report and view bugs.
π SOURCE π
The source code repository for Test::More can be found at <https://github.com/Test-More/test-more/>.
πΈ COPYRIGHT πΈ
Copyright 2001-2008 by 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/>
And that's the whole page bestie, we ate and left no crumbs π β¨ β this isperl v5.42.0, dated2025-07-28, and you just readTest::More(3). Now go write some tests, you absolute icon ππ¦π
π¦ where this page comes from
- opensuse-leap 16.0: perl-Test-Simple 1.302214-bp160.1.2 Β· Artistic-1.0 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