8 # Can't use Carp because it might cause use_ok() to accidentally succeed
9 # even though the module being used forgot to use Carp. Yes, this
12 my($file, $line) = (caller(1))[1,2];
13 warn @_, " at $file line $line\n";
18 use vars qw($VERSION @ISA @EXPORT %EXPORT_TAGS $TODO);
20 $VERSION = eval $VERSION; # make the alpha version come out as a number
22 use Test::Builder::Module;
23 @ISA = qw(Test::Builder::Module);
24 @EXPORT = qw(ok use_ok require_ok
25 is isnt like unlike is_deeply
29 eq_array eq_hash eq_set
40 Test::More - yet another framework for writing test scripts
44 use Test::More tests => 23;
46 use Test::More qw(no_plan);
48 use Test::More skip_all => $reason;
50 BEGIN { use_ok( 'Some::Module' ); }
51 require_ok( 'Some::Module' );
53 # Various ways to say "ok"
54 ok($got eq $expected, $test_name);
56 is ($got, $expected, $test_name);
57 isnt($got, $expected, $test_name);
59 # Rather than print STDERR "# here's what went wrong\n"
60 diag("here's what went wrong");
62 like ($got, qr/expected/, $test_name);
63 unlike($got, qr/expected/, $test_name);
65 cmp_ok($got, '==', $expected, $test_name);
67 is_deeply($got_complex_structure, $expected_complex_structure, $test_name);
70 skip $why, $how_many unless $have_some_feature;
72 ok( foo(), $test_name );
73 is( foo(42), 23, $test_name );
79 ok( foo(), $test_name );
80 is( foo(42), 23, $test_name );
83 can_ok($module, @methods);
84 isa_ok($object, $class);
92 my @status = Test::More::status;
97 B<STOP!> If you're just getting started writing tests, have a look at
98 Test::Simple first. This is a drop in replacement for Test::Simple
99 which you can switch to once you get the hang of basic testing.
101 The purpose of this module is to provide a wide range of testing
102 utilities. Various ways to say "ok" with better diagnostics,
103 facilities to skip tests, test future features and compare complicated
104 data structures. While you can do almost anything with a simple
105 C<ok()> function, it doesn't provide good diagnostic output.
108 =head2 I love it when a plan comes together
110 Before anything else, you need a testing plan. This basically declares
111 how many tests your script is going to run to protect against premature
114 The preferred way to do this is to declare a plan when you C<use Test::More>.
116 use Test::More tests => 23;
118 There are rare cases when you will not know beforehand how many tests
119 your script is going to run. In this case, you can declare that you
120 have no plan. (Try to avoid using this as it weakens your test.)
122 use Test::More qw(no_plan);
124 B<NOTE>: using no_plan requires a Test::Harness upgrade else it will
125 think everything has failed. See L<CAVEATS and NOTES>).
127 In some cases, you'll want to completely skip an entire testing script.
129 use Test::More skip_all => $skip_reason;
131 Your script will declare a skip with the reason why you skipped and
132 exit immediately with a zero (success). See L<Test::Harness> for
135 If you want to control what functions Test::More will export, you
136 have to use the 'import' option. For example, to import everything
137 but 'fail', you'd do:
139 use Test::More tests => 23, import => ['!fail'];
141 Alternatively, you can use the plan() function. Useful for when you
142 have to calculate the number of tests.
145 plan tests => keys %Stuff * 3;
147 or for deciding between running the tests at all:
150 if( $^O eq 'MacOS' ) {
151 plan skip_all => 'Test irrelevant on MacOS';
160 my $tb = Test::More->builder;
166 # This implements "use Test::More 'no_diag'" but the behavior is
174 while( $idx <= $#{$list} ) {
175 my $item = $list->[$idx];
177 if( defined $item and $item eq 'no_diag' ) {
178 $class->builder->no_diag(1);
193 By convention, each test is assigned a number in order. This is
194 largely done automatically for you. However, it's often very useful to
195 assign a name to each test. Which would you rather see:
203 ok 4 - basic multi-variable
204 not ok 5 - simple exponential
205 ok 6 - force == mass * acceleration
207 The later gives you some idea of what failed. It also makes it easier
208 to find the test in your script, simply search for "simple
211 All test functions take a name argument. It's optional, but highly
212 suggested that you use it.
215 =head2 I'm ok, you're not ok.
217 The basic purpose of this module is to print out either "ok #" or "not
218 ok #" depending on if a given test succeeded or failed. Everything
221 All of the following print "ok" or "not ok" depending on if the test
222 succeeded or failed. They all also return true or false,
229 ok($got eq $expected, $test_name);
231 This simply evaluates any expression (C<$got eq $expected> is just a
232 simple example) and uses that to determine if the test succeeded or
233 failed. A true expression passes, a false one fails. Very simple.
237 ok( $exp{9} == 81, 'simple exponential' );
238 ok( Film->can('db_Main'), 'set_db()' );
239 ok( $p->tests == 4, 'saw tests' );
240 ok( !grep !defined $_, @items, 'items populated' );
242 (Mnemonic: "This is ok.")
244 $test_name is a very short description of the test that will be printed
245 out. It makes it very easy to find a test in your script when it fails
246 and gives others an idea of your intentions. $test_name is optional,
247 but we B<very> strongly encourage its use.
249 Should an ok() fail, it will produce some diagnostics:
251 not ok 18 - sufficient mucus
252 # Failed test 'sufficient mucus'
253 # in foo.t at line 42.
255 This is the same as Test::Simple's ok() routine.
260 my($test, $name) = @_;
261 my $tb = Test::More->builder;
263 $tb->ok($test, $name);
270 is ( $got, $expected, $test_name );
271 isnt( $got, $expected, $test_name );
273 Similar to ok(), is() and isnt() compare their two arguments
274 with C<eq> and C<ne> respectively and use the result of that to
275 determine if the test succeeded or failed. So these:
277 # Is the ultimate answer 42?
278 is( ultimate_answer(), 42, "Meaning of Life" );
281 isnt( $foo, '', "Got some foo" );
283 are similar to these:
285 ok( ultimate_answer() eq 42, "Meaning of Life" );
286 ok( $foo ne '', "Got some foo" );
288 (Mnemonic: "This is that." "This isn't that.")
290 So why use these? They produce better diagnostics on failure. ok()
291 cannot know what you are testing for (beyond the name), but is() and
292 isnt() know what the test was and why it failed. For example this
295 my $foo = 'waffle'; my $bar = 'yarblokos';
296 is( $foo, $bar, 'Is foo the same as bar?' );
298 Will produce something like this:
300 not ok 17 - Is foo the same as bar?
301 # Failed test 'Is foo the same as bar?'
302 # in foo.t at line 139.
304 # expected: 'yarblokos'
306 So you can figure out what went wrong without rerunning the test.
308 You are encouraged to use is() and isnt() over ok() where possible,
309 however do not be tempted to use them to find out if something is
313 is( exists $brooklyn{tree}, 1, 'A tree grows in Brooklyn' );
315 This does not check if C<exists $brooklyn{tree}> is true, it checks if
316 it returns 1. Very different. Similar caveats exist for false and 0.
317 In these cases, use ok().
319 ok( exists $brooklyn{tree}, 'A tree grows in Brooklyn' );
321 For those grammatical pedants out there, there's an C<isn't()>
322 function which is an alias of isnt().
327 my $tb = Test::More->builder;
333 my $tb = Test::More->builder;
343 like( $got, qr/expected/, $test_name );
345 Similar to ok(), like() matches $got against the regex C<qr/expected/>.
349 like($got, qr/expected/, 'this is like that');
353 ok( $got =~ /expected/, 'this is like that');
355 (Mnemonic "This is like that".)
357 The second argument is a regular expression. It may be given as a
358 regex reference (i.e. C<qr//>) or (for better compatibility with older
359 perls) as a string that looks like a regex (alternative delimiters are
360 currently not supported):
362 like( $got, '/expected/', 'this is like that' );
364 Regex options may be placed on the end (C<'/expected/i'>).
366 Its advantages over ok() are similar to that of is() and isnt(). Better
367 diagnostics on failure.
372 my $tb = Test::More->builder;
380 unlike( $got, qr/expected/, $test_name );
382 Works exactly as like(), only it checks if $got B<does not> match the
388 my $tb = Test::More->builder;
396 cmp_ok( $got, $op, $expected, $test_name );
398 Halfway between ok() and is() lies cmp_ok(). This allows you to
399 compare two arguments using any binary perl operator.
401 # ok( $got eq $expected );
402 cmp_ok( $got, 'eq', $expected, 'this eq that' );
404 # ok( $got == $expected );
405 cmp_ok( $got, '==', $expected, 'this == that' );
407 # ok( $got && $expected );
408 cmp_ok( $got, '&&', $expected, 'this && that' );
411 Its advantage over ok() is when the test fails you'll know what $got
415 # Failed test in foo.t at line 12.
420 It's also useful in those cases where you are comparing numbers and
421 is()'s use of C<eq> will interfere:
423 cmp_ok( $big_hairy_number, '==', $another_big_hairy_number );
428 my $tb = Test::More->builder;
436 can_ok($module, @methods);
437 can_ok($object, @methods);
439 Checks to make sure the $module or $object can do these @methods
440 (works with functions, too).
442 can_ok('Foo', qw(this that whatever));
444 is almost exactly like saying:
446 ok( Foo->can('this') &&
451 only without all the typing and with a better interface. Handy for
452 quickly testing an interface.
454 No matter how many @methods you check, a single can_ok() call counts
455 as one test. If you desire otherwise, use:
457 foreach my $meth (@methods) {
458 can_ok('Foo', $meth);
464 my($proto, @methods) = @_;
465 my $class = ref $proto || $proto;
466 my $tb = Test::More->builder;
469 my $ok = $tb->ok( 0, "->can(...)" );
470 $tb->diag(' can_ok() called with empty class or reference');
475 my $ok = $tb->ok( 0, "$class->can(...)" );
476 $tb->diag(' can_ok() called with no methods');
481 foreach my $method (@methods) {
482 $tb->_try(sub { $proto->can($method) }) or push @nok, $method;
486 $name = @methods == 1 ? "$class->can('$methods[0]')"
487 : "$class->can(...)";
489 my $ok = $tb->ok( !@nok, $name );
491 $tb->diag(map " $class->can('$_') failed\n", @nok);
498 isa_ok($object, $class, $object_name);
499 isa_ok($ref, $type, $ref_name);
501 Checks to see if the given C<< $object->isa($class) >>. Also checks to make
502 sure the object was defined in the first place. Handy for this sort
505 my $obj = Some::Module->new;
506 isa_ok( $obj, 'Some::Module' );
508 where you'd otherwise have to write
510 my $obj = Some::Module->new;
511 ok( defined $obj && $obj->isa('Some::Module') );
513 to safeguard against your test script blowing up.
515 It works on references, too:
517 isa_ok( $array_ref, 'ARRAY' );
519 The diagnostics of this test normally just refer to 'the object'. If
520 you'd like them to be more specific, you can supply an $object_name
521 (for example 'Test customer').
526 my($object, $class, $obj_name) = @_;
527 my $tb = Test::More->builder;
530 $obj_name = 'The object' unless defined $obj_name;
531 my $name = "$obj_name isa $class";
532 if( !defined $object ) {
533 $diag = "$obj_name isn't defined";
535 elsif( !ref $object ) {
536 $diag = "$obj_name isn't a reference";
539 # We can't use UNIVERSAL::isa because we want to honor isa() overrides
540 my($rslt, $error) = $tb->_try(sub { $object->isa($class) });
542 if( $error =~ /^Can't call method "isa" on unblessed reference/ ) {
543 # Its an unblessed reference
544 if( !UNIVERSAL::isa($object, $class) ) {
545 my $ref = ref $object;
546 $diag = "$obj_name isn't a '$class' it's a '$ref'";
550 WHOA! I tried to call ->isa on your object and got some weird error.
557 my $ref = ref $object;
558 $diag = "$obj_name isn't a '$class' it's a '$ref'";
566 $ok = $tb->ok( 0, $name );
567 $tb->diag(" $diag\n");
570 $ok = $tb->ok( 1, $name );
584 Sometimes you just want to say that the tests have passed. Usually
585 the case is you've got some complicated condition that is difficult to
586 wedge into an ok(). In this case, you can simply use pass() (to
587 declare the test ok) or fail (for not ok). They are synonyms for
590 Use these very, very, very sparingly.
595 my $tb = Test::More->builder;
600 my $tb = Test::More->builder;
609 You usually want to test if the module you're testing loads ok, rather
610 than just vomiting if its load fails. For such purposes we have
611 C<use_ok> and C<require_ok>.
617 BEGIN { use_ok($module); }
618 BEGIN { use_ok($module, @imports); }
620 These simply use the given $module and test to make sure the load
621 happened ok. It's recommended that you run use_ok() inside a BEGIN
622 block so its functions are exported at compile-time and prototypes are
625 If @imports are given, they are passed through to the use. So this:
627 BEGIN { use_ok('Some::Module', qw(foo bar)) }
631 use Some::Module qw(foo bar);
633 Version numbers can be checked like so:
635 # Just like "use Some::Module 1.02"
636 BEGIN { use_ok('Some::Module', 1.02) }
638 Don't try to do this:
641 use_ok('Some::Module');
643 ...some code that depends on the use...
644 ...happening at compile time...
647 because the notion of "compile-time" is relative. Instead, you want:
649 BEGIN { use_ok('Some::Module') }
650 BEGIN { ...some code that depends on the use... }
656 my($module, @imports) = @_;
657 @imports = () unless @imports;
658 my $tb = Test::More->builder;
660 my($pack,$filename,$line) = caller;
662 # Work around a glitch in $@ and eval
665 local($@,$!,$SIG{__DIE__}); # isolate eval
667 if( @imports == 1 and $imports[0] =~ /^\d+(?:\.\d+)?$/ ) {
668 # probably a version check. Perl needs to see the bare number
669 # for it to work with non-Exporter based modules.
672 use $module $imports[0];
678 use $module \@imports;
684 my $ok = $tb->ok( !$eval_error, "use $module;" );
688 $@ =~ s{^BEGIN failed--compilation aborted at .*$}
689 {BEGIN failed--compilation aborted at $filename line $line.}m;
690 $tb->diag(<<DIAGNOSTIC);
691 Tried to use '$module'.
705 Like use_ok(), except it requires the $module or $file.
711 my $tb = Test::More->builder;
715 # Try to deterine if we've been given a module name or file.
716 # Module names must be barewords, files not.
717 $module = qq['$module'] unless _is_module_name($module);
719 local($!, $@, $SIG{__DIE__}); # isolate eval
726 my $ok = $tb->ok( !$@, "require $module;" );
730 $tb->diag(<<DIAGNOSTIC);
731 Tried to require '$module'.
741 sub _is_module_name {
744 # Module names start with a letter.
745 # End with an alphanumeric.
746 # The rest is an alphanumeric or ::
747 $module =~ s/\b::\b//g;
748 $module =~ /^[a-zA-Z]\w*$/;
754 =head2 Complex data structures
756 Not everything is a simple eq check or regex. There are times you
757 need to see if two data structures are equivalent. For these
758 instances Test::More provides a handful of useful functions.
760 B<NOTE> I'm not quite sure what will happen with filehandles.
766 is_deeply( $got, $expected, $test_name );
768 Similar to is(), except that if $got and $expected are references, it
769 does a deep comparison walking each data structure to see if they are
770 equivalent. If the two structures are different, it will display the
771 place where they start differing.
773 is_deeply() compares the dereferenced values of references, the
774 references themselves (except for their type) are ignored. This means
775 aspects such as blessing and ties are not considered "different".
777 is_deeply() current has very limited handling of function reference
778 and globs. It merely checks if they have the same referent. This may
779 improve in the future.
781 Test::Differences and Test::Deep provide more in-depth functionality
786 use vars qw(@Data_Stack %Refs_Seen);
787 my $DNE = bless [], 'Does::Not::Exist';
790 ref $_[0] eq ref $DNE;
795 my $tb = Test::More->builder;
797 unless( @_ == 2 or @_ == 3 ) {
799 is_deeply() takes two or three args, you gave %d.
800 This usually means you passed an array or hash instead
803 chop $msg; # clip off newline so carp() will put in line/file
805 _carp sprintf $msg, scalar @_;
810 my($got, $expected, $name) = @_;
812 $tb->_unoverload_str(\$expected, \$got);
815 if( !ref $got and !ref $expected ) { # neither is a reference
816 $ok = $tb->is_eq($got, $expected, $name);
818 elsif( !ref $got xor !ref $expected ) { # one's a reference, one isn't
819 $ok = $tb->ok(0, $name);
820 $tb->diag( _format_stack({ vals => [ $got, $expected ] }) );
822 else { # both references
823 local @Data_Stack = ();
824 if( _deep_check($got, $expected) ) {
825 $ok = $tb->ok(1, $name);
828 $ok = $tb->ok(0, $name);
829 $tb->diag(_format_stack(@Data_Stack));
841 foreach my $entry (@Stack) {
842 my $type = $entry->{type} || '';
843 my $idx = $entry->{'idx'};
844 if( $type eq 'HASH' ) {
845 $var .= "->" unless $did_arrow++;
848 elsif( $type eq 'ARRAY' ) {
849 $var .= "->" unless $did_arrow++;
852 elsif( $type eq 'REF' ) {
857 my @vals = @{$Stack[-1]{vals}}[0,1];
859 ($vars[0] = $var) =~ s/\$FOO/ \$got/;
860 ($vars[1] = $var) =~ s/\$FOO/\$expected/;
862 my $out = "Structures begin differing at:\n";
863 foreach my $idx (0..$#vals) {
864 my $val = $vals[$idx];
865 $vals[$idx] = !defined $val ? 'undef' :
866 _dne($val) ? "Does not exist" :
871 $out .= "$vars[0] = $vals[0]\n";
872 $out .= "$vars[1] = $vals[1]\n";
882 return '' if !ref $thing;
884 for my $type (qw(ARRAY HASH REF SCALAR GLOB CODE Regexp)) {
885 return $type if UNIVERSAL::isa($thing, $type);
896 If you pick the right test function, you'll usually get a good idea of
897 what went wrong when it failed. But sometimes it doesn't work out
898 that way. So here we have ways for you to write your own diagnostic
899 messages which are safer than just C<print STDERR>.
905 diag(@diagnostic_message);
907 Prints a diagnostic message which is guaranteed not to interfere with
908 test output. Like C<print> @diagnostic_message is simply concatenated
911 Handy for this sort of thing:
913 ok( grep(/foo/, @users), "There's a foo user" ) or
914 diag("Since there's no foo, check that /etc/bar is set up right");
918 not ok 42 - There's a foo user
919 # Failed test 'There's a foo user'
920 # in foo.t at line 52.
921 # Since there's no foo, check that /etc/bar is set up right.
923 You might remember C<ok() or diag()> with the mnemonic C<open() or
926 B<NOTE> The exact formatting of the diagnostic output is still
927 changing, but it is guaranteed that whatever you throw at it it won't
928 interfere with the test.
933 my $tb = Test::More->builder;
942 =head2 Conditional tests
944 Sometimes running a test under certain conditions will cause the
945 test script to die. A certain function or method isn't implemented
946 (such as fork() on MacOS), some resource isn't available (like a
947 net connection) or a module isn't available. In these cases it's
948 necessary to skip tests, or declare that they are supposed to fail
949 but will work in the future (a todo test).
951 For more details on the mechanics of skip and todo tests see
954 The way Test::More handles this is with a named block. Basically, a
955 block of tests which can be skipped over or made todo. It's best if I
963 skip $why, $how_many if $condition;
965 ...normal testing code goes here...
968 This declares a block of tests that might be skipped, $how_many tests
969 there are, $why and under what $condition to skip them. An example is
970 the easiest way to illustrate:
973 eval { require HTML::Lint };
975 skip "HTML::Lint not installed", 2 if $@;
977 my $lint = new HTML::Lint;
978 isa_ok( $lint, "HTML::Lint" );
980 $lint->parse( $html );
981 is( $lint->errors, 0, "No errors found in HTML" );
984 If the user does not have HTML::Lint installed, the whole block of
985 code I<won't be run at all>. Test::More will output special ok's
986 which Test::Harness interprets as skipped, but passing, tests.
988 It's important that $how_many accurately reflects the number of tests
989 in the SKIP block so the # of tests run will match up with your plan.
990 If your plan is C<no_plan> $how_many is optional and will default to 1.
992 It's perfectly safe to nest SKIP blocks. Each SKIP block must have
993 the label C<SKIP>, or Test::More can't work its magic.
995 You don't skip tests which are failing because there's a bug in your
996 program, or for which you don't yet have code written. For that you
1003 my($why, $how_many) = @_;
1004 my $tb = Test::More->builder;
1006 unless( defined $how_many ) {
1007 # $how_many can only be avoided when no_plan is in use.
1008 _carp "skip() needs to know \$how_many tests are in the block"
1009 unless $tb->has_plan eq 'no_plan';
1013 if( defined $how_many and $how_many =~ /\D/ ) {
1014 _carp "skip() was passed a non-numeric number of tests. Did you get the arguments backwards?";
1018 for( 1..$how_many ) {
1027 =item B<TODO: BLOCK>
1030 local $TODO = $why if $condition;
1032 ...normal testing code goes here...
1035 Declares a block of tests you expect to fail and $why. Perhaps it's
1036 because you haven't fixed a bug or haven't finished a new feature:
1039 local $TODO = "URI::Geller not finished";
1041 my $card = "Eight of clubs";
1042 is( URI::Geller->your_card, $card, 'Is THIS your card?' );
1045 URI::Geller->bend_spoon;
1046 is( $spoon, 'bent', "Spoon bending, that's original" );
1049 With a todo block, the tests inside are expected to fail. Test::More
1050 will run the tests normally, but print out special flags indicating
1051 they are "todo". Test::Harness will interpret failures as being ok.
1052 Should anything succeed, it will report it as an unexpected success.
1053 You then know the thing you had todo is done and can remove the
1056 The nice part about todo tests, as opposed to simply commenting out a
1057 block of tests, is it's like having a programmatic todo list. You know
1058 how much work is left to be done, you're aware of what bugs there are,
1059 and you'll know immediately when they're fixed.
1061 Once a todo test starts succeeding, simply move it outside the block.
1062 When the block is empty, delete it.
1064 B<NOTE>: TODO tests require a Test::Harness upgrade else it will
1065 treat it as a normal failure. See L<CAVEATS and NOTES>).
1071 todo_skip $why, $how_many if $condition;
1073 ...normal testing code...
1076 With todo tests, it's best to have the tests actually run. That way
1077 you'll know when they start passing. Sometimes this isn't possible.
1078 Often a failing test will cause the whole program to die or hang, even
1079 inside an C<eval BLOCK> with and using C<alarm>. In these extreme
1080 cases you have no choice but to skip over the broken tests entirely.
1082 The syntax and behavior is similar to a C<SKIP: BLOCK> except the
1083 tests will be marked as failing but todo. Test::Harness will
1084 interpret them as passing.
1089 my($why, $how_many) = @_;
1090 my $tb = Test::More->builder;
1092 unless( defined $how_many ) {
1093 # $how_many can only be avoided when no_plan is in use.
1094 _carp "todo_skip() needs to know \$how_many tests are in the block"
1095 unless $tb->has_plan eq 'no_plan';
1099 for( 1..$how_many ) {
1100 $tb->todo_skip($why);
1107 =item When do I use SKIP vs. TODO?
1109 B<If it's something the user might not be able to do>, use SKIP.
1110 This includes optional modules that aren't installed, running under
1111 an OS that doesn't have some feature (like fork() or symlinks), or maybe
1112 you need an Internet connection and one isn't available.
1114 B<If it's something the programmer hasn't done yet>, use TODO. This
1115 is for any code you haven't written yet, or bugs you have yet to fix,
1116 but want to put tests in your testing script (always a good idea).
1130 Indicates to the harness that things are going so badly all testing
1131 should terminate. This includes the running any additional test scripts.
1133 This is typically used when testing cannot continue such as a critical
1134 module failing to compile or a necessary external utility not being
1135 available such as a database connection failing.
1137 The test will exit with 255.
1143 my $tb = Test::More->builder;
1145 $tb->BAIL_OUT($reason);
1151 =head2 Discouraged comparison functions
1153 The use of the following functions is discouraged as they are not
1154 actually testing functions and produce no diagnostics to help figure
1155 out what went wrong. They were written before is_deeply() existed
1156 because I couldn't figure out how to display a useful diff of two
1157 arbitrary data structures.
1159 These functions are usually used inside an ok().
1161 ok( eq_array(\@got, \@expected) );
1163 C<is_deeply()> can do that better and with diagnostics.
1165 is_deeply( \@got, \@expected );
1167 They may be deprecated in future versions.
1173 my $is_eq = eq_array(\@got, \@expected);
1175 Checks if two arrays are equivalent. This is a deep check, so
1176 multi-level structures are handled correctly.
1189 if( grep !_type($_) eq 'ARRAY', $a1, $a2 ) {
1190 warn "eq_array passed a non-array ref";
1194 return 1 if $a1 eq $a2;
1197 my $max = $#$a1 > $#$a2 ? $#$a1 : $#$a2;
1199 my $e1 = $_ > $#$a1 ? $DNE : $a1->[$_];
1200 my $e2 = $_ > $#$a2 ? $DNE : $a2->[$_];
1202 push @Data_Stack, { type => 'ARRAY', idx => $_, vals => [$e1, $e2] };
1203 $ok = _deep_check($e1,$e2);
1204 pop @Data_Stack if $ok;
1214 my $tb = Test::More->builder;
1218 # Effectively turn %Refs_Seen into a stack. This avoids picking up
1219 # the same referenced used twice (such as [\$a, \$a]) to be considered
1221 local %Refs_Seen = %Refs_Seen;
1224 # Quiet uninitialized value warnings when comparing undefs.
1227 $tb->_unoverload_str(\$e1, \$e2);
1229 # Either they're both references or both not.
1230 my $same_ref = !(!ref $e1 xor !ref $e2);
1231 my $not_ref = (!ref $e1 and !ref $e2);
1233 if( defined $e1 xor defined $e2 ) {
1236 elsif ( _dne($e1) xor _dne($e2) ) {
1239 elsif ( $same_ref and ($e1 eq $e2) ) {
1242 elsif ( $not_ref ) {
1243 push @Data_Stack, { type => '', vals => [$e1, $e2] };
1247 if( $Refs_Seen{$e1} ) {
1248 return $Refs_Seen{$e1} eq $e2;
1251 $Refs_Seen{$e1} = "$e2";
1254 my $type = _type($e1);
1255 $type = 'DIFFERENT' unless _type($e2) eq $type;
1257 if( $type eq 'DIFFERENT' ) {
1258 push @Data_Stack, { type => $type, vals => [$e1, $e2] };
1261 elsif( $type eq 'ARRAY' ) {
1262 $ok = _eq_array($e1, $e2);
1264 elsif( $type eq 'HASH' ) {
1265 $ok = _eq_hash($e1, $e2);
1267 elsif( $type eq 'REF' ) {
1268 push @Data_Stack, { type => $type, vals => [$e1, $e2] };
1269 $ok = _deep_check($$e1, $$e2);
1270 pop @Data_Stack if $ok;
1272 elsif( $type eq 'SCALAR' ) {
1273 push @Data_Stack, { type => 'REF', vals => [$e1, $e2] };
1274 $ok = _deep_check($$e1, $$e2);
1275 pop @Data_Stack if $ok;
1278 push @Data_Stack, { type => $type, vals => [$e1, $e2] };
1282 _whoa(1, "No type in _deep_check");
1292 my($check, $desc) = @_;
1296 This should never happen! Please contact the author immediately!
1304 my $is_eq = eq_hash(\%got, \%expected);
1306 Determines if the two hashes contain the same keys and values. This
1313 return _deep_check(@_);
1319 if( grep !_type($_) eq 'HASH', $a1, $a2 ) {
1320 warn "eq_hash passed a non-hash ref";
1324 return 1 if $a1 eq $a2;
1327 my $bigger = keys %$a1 > keys %$a2 ? $a1 : $a2;
1328 foreach my $k (keys %$bigger) {
1329 my $e1 = exists $a1->{$k} ? $a1->{$k} : $DNE;
1330 my $e2 = exists $a2->{$k} ? $a2->{$k} : $DNE;
1332 push @Data_Stack, { type => 'HASH', idx => $k, vals => [$e1, $e2] };
1333 $ok = _deep_check($e1, $e2);
1334 pop @Data_Stack if $ok;
1344 my $is_eq = eq_set(\@got, \@expected);
1346 Similar to eq_array(), except the order of the elements is B<not>
1347 important. This is a deep check, but the irrelevancy of order only
1348 applies to the top level.
1350 ok( eq_set(\@got, \@expected) );
1354 is_deeply( [sort @got], [sort @expected] );
1356 B<NOTE> By historical accident, this is not a true set comparison.
1357 While the order of elements does not matter, duplicate elements do.
1359 B<NOTE> eq_set() does not know how to deal with references at the top
1360 level. The following is an example of a comparison which might not work:
1362 eq_set([\1, \2], [\2, \1]);
1364 Test::Deep contains much better set comparison functions.
1370 return 0 unless @$a1 == @$a2;
1372 # There's faster ways to do this, but this is easiest.
1375 # It really doesn't matter how we sort them, as long as both arrays are
1376 # sorted with the same algorithm.
1378 # Ensure that references are not accidentally treated the same as a
1379 # string containing the reference.
1381 # Have to inline the sort routine due to a threading/sort bug.
1382 # See [rt.cpan.org 6782]
1384 # I don't know how references would be sorted so we just don't sort
1385 # them. This means eq_set doesn't really work with refs.
1387 [grep(ref, @$a1), sort( grep(!ref, @$a1) )],
1388 [grep(ref, @$a2), sort( grep(!ref, @$a2) )],
1395 =head2 Extending and Embedding Test::More
1397 Sometimes the Test::More interface isn't quite enough. Fortunately,
1398 Test::More is built on top of Test::Builder which provides a single,
1399 unified backend for any test library to use. This means two test
1400 libraries which both use Test::Builder B<can be used together in the
1403 If you simply want to do a little tweaking of how the tests behave,
1404 you can access the underlying Test::Builder object like so:
1410 my $test_builder = Test::More->builder;
1412 Returns the Test::Builder object underlying Test::More for you to play
1421 If all your tests passed, Test::Builder will exit with zero (which is
1422 normal). If anything failed it will exit with how many failed. If
1423 you run less (or more) tests than you planned, the missing (or extras)
1424 will be considered failures. If no tests were ever run Test::Builder
1425 will throw a warning and exit with 255. If the test died, even after
1426 having successfully completed all its tests, it will still be
1427 considered a failure and will exit with 255.
1429 So the exit codes are...
1431 0 all tests successful
1432 255 test died or all passed but wrong # of tests run
1433 any other number how many failed (including missing or extras)
1435 If you fail more than 254 tests, it will be reported as 254.
1437 B<NOTE> This behavior may go away in future versions.
1440 =head1 CAVEATS and NOTES
1444 =item Backwards compatibility
1446 Test::More works with Perls as old as 5.004_05.
1449 =item Overloaded objects
1451 String overloaded objects are compared B<as strings> (or in cmp_ok()'s
1452 case, strings or numbers as appropriate to the comparison op). This
1453 prevents Test::More from piercing an object's interface allowing
1454 better blackbox testing. So if a function starts returning overloaded
1455 objects instead of bare strings your tests won't notice the
1456 difference. This is good.
1458 However, it does mean that functions like is_deeply() cannot be used to
1459 test the internals of string overloaded objects. In this case I would
1460 suggest Test::Deep which contains more flexible testing functions for
1461 complex data structures.
1466 Test::More will only be aware of threads if "use threads" has been done
1467 I<before> Test::More is loaded. This is ok:
1472 This may cause problems:
1477 5.8.1 and above are supported. Anything below that has too many bugs.
1480 =item Test::Harness upgrade
1482 no_plan and todo depend on new Test::Harness features and fixes. If
1483 you're going to distribute tests that use no_plan or todo your
1484 end-users will have to upgrade Test::Harness to the latest one on
1485 CPAN. If you avoid no_plan and TODO tests, the stock Test::Harness
1488 Installing Test::More should also upgrade Test::Harness.
1495 This is a case of convergent evolution with Joshua Pritikin's Test
1496 module. I was largely unaware of its existence when I'd first
1497 written my own ok() routines. This module exists because I can't
1498 figure out how to easily wedge test names into Test's interface (along
1499 with a few other problems).
1501 The goal here is to have a testing utility that's simple to learn,
1502 quick to use and difficult to trip yourself up with while still
1503 providing more flexibility than the existing Test.pm. As such, the
1504 names of the most common routines are kept tiny, special cases and
1505 magic side-effects are kept to a minimum. WYSIWYG.
1510 L<Test::Simple> if all this confuses you and you just want to write
1511 some tests. You can upgrade to Test::More later (it's forward
1514 L<Test> is the old testing module. Its main benefit is that it has
1515 been distributed with Perl since 5.004_05.
1517 L<Test::Harness> for details on how your test results are interpreted
1520 L<Test::Differences> for more ways to test complex data structures.
1521 And it plays well with Test::More.
1523 L<Test::Class> is like XUnit but more perlish.
1525 L<Test::Deep> gives you more powerful complex data structure testing.
1527 L<Test::Unit> is XUnit style testing.
1529 L<Test::Inline> shows the idea of embedded testing.
1531 L<Bundle::Test> installs a whole bunch of useful test modules.
1536 Michael G Schwern E<lt>schwern@pobox.comE<gt> with much inspiration
1537 from Joshua Pritikin's Test module and lots of help from Barrie
1538 Slaymaker, Tony Bowden, blackstar.co.uk, chromatic, Fergal Daly and
1544 See F<http://rt.cpan.org> to report and view bugs.
1549 Copyright 2001-2002, 2004-2006 by Michael G Schwern E<lt>schwern@pobox.comE<gt>.
1551 This program is free software; you can redistribute it and/or
1552 modify it under the same terms as Perl itself.
1554 See F<http://www.perl.com/perl/misc/Artistic.html>