table of contents
other versions
- wheezy 5.14.2-21+deb7u3
- jessie 5.20.2-3+deb8u6
- testing 5.24.1-3
- unstable 5.24.1-3
- experimental 5.26.0-1
other sections
Test::More(3perl) | Perl Programmers Reference Guide | Test::More(3perl) |
NAME¶
Test::More - yet another framework for writing test scriptsSYNOPSIS¶
use Test::More tests => 23; # or use Test::More skip_all => $reason; # or use Test::More; # see done_testing() BEGIN { use_ok( 'Some::Module' ); } 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;
DESCRIPTION¶
STOP! If you're just getting started writing tests, have a look at Test::Simple first. This is a drop in replacement for Test::Simple which you can switch to once you get the hang of basic testing. The purpose of this module is to provide a wide range of testing utilities. Various ways to say "ok" with better diagnostics, facilities to skip tests, test future features and compare complicated data structures. While you can do almost anything with a simple "ok()" function, it doesn't provide good diagnostic output.I love it when a plan comes together¶
Before anything else, you need a testing plan. This basically declares how many tests your script is going to run to protect against premature failure. The preferred way to do this is to declare a plan when you "use Test::More".use Test::More tests => 23;There are cases when you will not know beforehand how many tests your script is going to run. In this case, you can declare your tests at the end.
use Test::More; ... run your tests ... done_testing( $number_of_tests_run );Sometimes you really don't know how many tests were run, or it's too difficult to calculate. In which case you can leave off $number_of_tests_run. In some cases, you'll want to 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. 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. 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);
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 6or
ok 4 - basic multi-variable not ok 5 - simple exponential ok 6 - force == mass * accelerationThe later gives you some idea of what failed. It also makes it easier to find the test in your script, simply search for "simple exponential". All test functions take a name argument. It's optional, but highly suggested that you use it.
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);
ok( $exp{9} == 81, 'simple exponential' ); ok( Film->can('db_Main'), 'set_db()' ); ok( $p->tests == 4, 'saw tests' ); ok( !grep !defined $_, @items, 'items populated' );
not ok 18 - sufficient mucus # Failed test 'sufficient mucus' # in foo.t at line 42.
- is
- isnt
-
is ( $got, $expected, $test_name ); isnt( $got, $expected, $test_name );
# Is the ultimate answer 42? is( ultimate_answer(), 42, "Meaning of Life" ); # $foo isn't empty isnt( $foo, '', "Got some foo" );
ok( ultimate_answer() eq 42, "Meaning of Life" ); ok( $foo ne '', "Got some foo" );
is($not_defined, undef, "undefined as expected");
my $foo = 'waffle'; my $bar = 'yarblokos'; is( $foo, $bar, 'Is foo the same as bar?' );
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'
# XXX BAD! is( exists $brooklyn{tree}, 1, 'A tree grows in Brooklyn' );
ok( exists $brooklyn{tree}, 'A tree grows in Brooklyn' );
new_ok $obj, "Foo"; my $clone = $obj->clone; isa_ok $obj, "Foo", "Foo->clone"; isnt $obj, $clone, "clone() produces a different object";
- like
-
like( $got, qr/expected/, $test_name );
like($got, qr/expected/, 'this is like that');
ok( $got =~ /expected/, 'this is like that');
like( $got, '/expected/', 'this is like that' );
- unlike
-
unlike( $got, qr/expected/, $test_name );
- cmp_ok
-
cmp_ok( $got, $op, $expected, $test_name );
# 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...
not ok 1 # Failed test in foo.t at line 12. # '23' # && # undef
cmp_ok( $big_hairy_number, '==', $another_big_hairy_number );
cmp_ok( $some_value, '<=', $upper_limit );
- can_ok
-
can_ok($module, @methods); can_ok($object, @methods);
can_ok('Foo', qw(this that whatever));
ok( Foo->can('this') && Foo->can('that') && Foo->can('whatever') );
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);
my $obj = Some::Module->new; isa_ok( $obj, 'Some::Module' );
my $obj = Some::Module->new; ok( defined $obj && $obj->isa('Some::Module') );
isa_ok( 'Vole', 'Rodent' );
isa_ok( $array_ref, 'ARRAY' );
- new_ok
-
my $obj = new_ok( $class ); my $obj = new_ok( $class => \@args ); my $obj = new_ok( $class => \@args, $object_name );
my $obj = $class->new(@args); isa_ok $obj, $class, $object_name;
- subtest
-
subtest $name => \&code;
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");
1..3 ok 1 - First test 1..2 ok 1 - This is a subtest ok 2 - So is this ok 2 - An example subtest ok 3 - Third test
subtest 'skippy' => sub { plan skip_all => 'cuz I said so'; pass('this test will never be run'); };
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(); };
- pass
- fail
-
pass($test_name); fail($test_name);
Module tests¶
You usually want to test if the module you're testing loads ok, rather than just vomiting if its load fails. For such purposes we have "use_ok" and "require_ok".- use_ok
-
BEGIN { use_ok($module); } BEGIN { use_ok($module, @imports); }
BEGIN { use_ok('Some::Module', qw(foo bar)) }
use Some::Module qw(foo bar);
# Just like "use Some::Module 1.02" BEGIN { use_ok('Some::Module', 1.02) }
BEGIN { use_ok('Some::Module'); ...some code that depends on the use... ...happening at compile time... }
BEGIN { use_ok('Some::Module') } BEGIN { ...some code that depends on the use... }
BEGIN { require_ok "Foo" }
- require_ok
-
require_ok($module); require_ok($file);
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.- is_deeply
-
is_deeply( $got, $expected, $test_name );
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);
ok( grep(/foo/, @users), "There's a foo user" ) or diag("Since there's no foo, check that /etc/bar is set up right");
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.
- note
-
note(@diagnostic_message);
note("Tempfile is $tempfile");
- explain
-
my @dump = explain @diagnostic_message;
is_deeply($have, $want) || diag explain $have;
note explain \%args; Some::Class->method(%args);
Conditional tests¶
Sometimes running a test under certain conditions will cause the test script to die. A certain function or method isn't implemented (such as 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 are supposed to fail but will work in the future (a todo test). For more details on the mechanics of skip and todo tests see Test::Harness. The way Test::More handles this is with a named block. Basically, a block of tests which can be skipped over or made todo. It's best if I just show you...- SKIP: BLOCK
-
SKIP: { skip $why, $how_many if $condition; ...normal testing code goes here... }
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" ); }
- TODO: BLOCK
-
TODO: { local $TODO = $why if $condition; ...normal testing code goes here... }
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" ); }
- todo_skip
-
TODO: { todo_skip $why, $how_many if $condition; ...normal testing code... }
- 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.
Test control¶
- BAIL_OUT
-
BAIL_OUT($reason);
Discouraged comparison functions¶
The use of the following functions is discouraged as 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);
- eq_hash
-
my $is_eq = eq_hash(\%got, \%expected);
- eq_set
-
my $is_eq = eq_set(\@got, \@expected);
ok( eq_set(\@got, \@expected) );
is_deeply( [sort @got], [sort @expected] );
eq_set([\1, \2], [\2, \1]);
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. If you simply want to 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;
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 This behavior may go away in future versions.
CAVEATS and NOTES¶
- Backwards compatibility
- Test::More works with Perls as old as 5.6.0.
- utf8 / "Wide character in print"
- If you use utf8 or other non-ASCII characters with
Test::More you might get a "Wide character in print" warning.
Using "binmode STDOUT, ":utf8"" will not fix it.
Test::Builder (which powers Test::More) duplicates STDOUT and STDERR. So
any changes to them, including changing their output disciplines, will not
be seem by Test::More.
my $builder = Test::More->builder; binmode $builder->output, ":utf8"; binmode $builder->failure_output, ":utf8"; binmode $builder->todo_output, ":utf8";
- 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.
- 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;
use Test::More use threads;
HISTORY¶
This is a case of convergent evolution with Joshua Pritikin's Test module. I was largely unaware of its existence when I'd first written my own ok() routines. This module exists because I can'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¶
Test::Simple if all this confuses you and you just want to write some tests. You can upgrade to Test::More later (it's forward compatible). Test::Harness is the test runner and output interpreter for Perl. It's the thing that powers "make test" and where the "prove" utility comes from. Test::Legacy tests written with Test.pm, the original testing module, do not play well with other testing libraries. Test::Legacy emulates the Test.pm interface and does play well with others. Test::Differences for more ways to test complex data structures. And it plays well with Test::More. Test::Class is like xUnit but more perlish. Test::Deep gives you more powerful complex data structure testing. Test::Inline shows the idea of embedded testing. Bundle::Test installs a whole bunch of useful test modules.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.BUGS¶
See http://rt.cpan.org to report and view bugs.SOURCE¶
The source code repository for Test::More can be found at http://github.com/schwern/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 http://www.perl.com/perl/misc/Artistic.html2011-09-19 | perl v5.14.2 |