Move Test::Simple from lib to ext.
[p5sagit/p5-mst-13.2.git] / ext / Test-Simple / lib / Test / More.pm
CommitLineData
3f2ec160 1package Test::More;
2
705e6672 3use 5.006;
d020a79a 4use strict;
ccbd73a4 5use warnings;
3f2ec160 6
ccbd73a4 7#---- perlcritic exemptions. ----#
8
9# We use a lot of subroutine prototypes
10## no critic (Subroutines::ProhibitSubroutinePrototypes)
33459055 11
12# Can't use Carp because it might cause use_ok() to accidentally succeed
13# even though the module being used forgot to use Carp. Yes, this
14# actually happened.
15sub _carp {
ccbd73a4 16 my( $file, $line ) = ( caller(1) )[ 1, 2 ];
17 return warn @_, " at $file line $line\n";
3f2ec160 18}
19
3e887aae 20our $VERSION = '0.92';
ccbd73a4 21$VERSION = eval $VERSION; ## no critic (BuiltinFunctions::ProhibitStringyEval)
7483b81c 22
b1ddf169 23use Test::Builder::Module;
ccbd73a4 24our @ISA = qw(Test::Builder::Module);
25our @EXPORT = qw(ok use_ok require_ok
26 is isnt like unlike is_deeply
27 cmp_ok
28 skip todo todo_skip
29 pass fail
30 eq_array eq_hash eq_set
31 $TODO
32 plan
3e887aae 33 done_testing
ccbd73a4 34 can_ok isa_ok new_ok
35 diag note explain
36 BAIL_OUT
37);
3f2ec160 38
39=head1 NAME
40
41Test::More - yet another framework for writing test scripts
42
43=head1 SYNOPSIS
44
b7f9bbeb 45 use Test::More tests => 23;
3f2ec160 46 # or
d020a79a 47 use Test::More skip_all => $reason;
3e887aae 48 # or
49 use Test::More; # see done_testing()
3f2ec160 50
51 BEGIN { use_ok( 'Some::Module' ); }
52 require_ok( 'Some::Module' );
53
54 # Various ways to say "ok"
004caa16 55 ok($got eq $expected, $test_name);
3f2ec160 56
6b38a9b9 57 is ($got, $expected, $test_name);
58 isnt($got, $expected, $test_name);
a9153838 59
60 # Rather than print STDERR "# here's what went wrong\n"
61 diag("here's what went wrong");
62
004caa16 63 like ($got, qr/expected/, $test_name);
64 unlike($got, qr/expected/, $test_name);
a9153838 65
004caa16 66 cmp_ok($got, '==', $expected, $test_name);
3f2ec160 67
004caa16 68 is_deeply($got_complex_structure, $expected_complex_structure, $test_name);
33459055 69
d020a79a 70 SKIP: {
71 skip $why, $how_many unless $have_some_feature;
72
3f2ec160 73 ok( foo(), $test_name );
74 is( foo(42), 23, $test_name );
d020a79a 75 };
76
77 TODO: {
78 local $TODO = $why;
3f2ec160 79
3f2ec160 80 ok( foo(), $test_name );
81 is( foo(42), 23, $test_name );
d020a79a 82 };
83
84 can_ok($module, @methods);
85 isa_ok($object, $class);
3f2ec160 86
87 pass($test_name);
88 fail($test_name);
89
b1ddf169 90 BAIL_OUT($why);
3f2ec160 91
d020a79a 92 # UNIMPLEMENTED!!!
b1ddf169 93 my @status = Test::More::status;
d020a79a 94
3f2ec160 95
96=head1 DESCRIPTION
97
a9153838 98B<STOP!> If you're just getting started writing tests, have a look at
3e887aae 99L<Test::Simple> first. This is a drop in replacement for Test::Simple
d020a79a 100which you can switch to once you get the hang of basic testing.
3f2ec160 101
a9153838 102The purpose of this module is to provide a wide range of testing
103utilities. Various ways to say "ok" with better diagnostics,
104facilities to skip tests, test future features and compare complicated
105data structures. While you can do almost anything with a simple
106C<ok()> function, it doesn't provide good diagnostic output.
3f2ec160 107
108
109=head2 I love it when a plan comes together
110
111Before anything else, you need a testing plan. This basically declares
112how many tests your script is going to run to protect against premature
113failure.
114
4bd4e70a 115The preferred way to do this is to declare a plan when you C<use Test::More>.
3f2ec160 116
b7f9bbeb 117 use Test::More tests => 23;
3f2ec160 118
3e887aae 119There are cases when you will not know beforehand how many tests your
120script is going to run. In this case, you can declare your tests at
121the end.
122
123 use Test::More;
124
125 ... run your tests ...
3f2ec160 126
3e887aae 127 done_testing( $number_of_tests_run );
3f2ec160 128
3e887aae 129Sometimes you really don't know how many tests were run, or it's too
130difficult to calculate. In which case you can leave off
131$number_of_tests_run.
30e302f8 132
3f2ec160 133In some cases, you'll want to completely skip an entire testing script.
134
d020a79a 135 use Test::More skip_all => $skip_reason;
3f2ec160 136
d020a79a 137Your script will declare a skip with the reason why you skipped and
138exit immediately with a zero (success). See L<Test::Harness> for
139details.
3f2ec160 140
33459055 141If you want to control what functions Test::More will export, you
142have to use the 'import' option. For example, to import everything
143but 'fail', you'd do:
144
145 use Test::More tests => 23, import => ['!fail'];
146
147Alternatively, you can use the plan() function. Useful for when you
148have to calculate the number of tests.
149
150 use Test::More;
151 plan tests => keys %Stuff * 3;
152
153or for deciding between running the tests at all:
154
155 use Test::More;
156 if( $^O eq 'MacOS' ) {
4bd4e70a 157 plan skip_all => 'Test irrelevant on MacOS';
33459055 158 }
159 else {
160 plan tests => 42;
161 }
162
163=cut
164
165sub plan {
b1ddf169 166 my $tb = Test::More->builder;
7483b81c 167
ccbd73a4 168 return $tb->plan(@_);
33459055 169}
170
b1ddf169 171# This implements "use Test::More 'no_diag'" but the behavior is
172# deprecated.
173sub import_extra {
174 my $class = shift;
175 my $list = shift;
7483b81c 176
b1ddf169 177 my @other = ();
ccbd73a4 178 my $idx = 0;
b1ddf169 179 while( $idx <= $#{$list} ) {
180 my $item = $list->[$idx];
181
182 if( defined $item and $item eq 'no_diag' ) {
183 $class->builder->no_diag(1);
7483b81c 184 }
185 else {
b1ddf169 186 push @other, $item;
7483b81c 187 }
188
189 $idx++;
190 }
191
b1ddf169 192 @$list = @other;
33459055 193
ccbd73a4 194 return;
195}
3f2ec160 196
3e887aae 197=over 4
198
199=item B<done_testing>
200
201 done_testing();
202 done_testing($number_of_tests);
203
204If you don't know how many tests you're going to run, you can issue
205the plan when you're done running tests.
206
207$number_of_tests is the same as plan(), it's the number of tests you
208expected to run. You can omit this, in which case the number of tests
209you ran doesn't matter, just the fact that your tests ran to
210conclusion.
211
212This is safer than and replaces the "no_plan" plan.
213
214=back
215
216=cut
217
218sub done_testing {
219 my $tb = Test::More->builder;
220 $tb->done_testing(@_);
221}
222
3f2ec160 223=head2 Test names
224
225By convention, each test is assigned a number in order. This is
6686786d 226largely done automatically for you. However, it's often very useful to
3f2ec160 227assign a name to each test. Which would you rather see:
228
229 ok 4
230 not ok 5
231 ok 6
232
233or
234
235 ok 4 - basic multi-variable
236 not ok 5 - simple exponential
237 ok 6 - force == mass * acceleration
238
239The later gives you some idea of what failed. It also makes it easier
240to find the test in your script, simply search for "simple
241exponential".
242
6686786d 243All test functions take a name argument. It's optional, but highly
3f2ec160 244suggested that you use it.
245
246
247=head2 I'm ok, you're not ok.
248
249The basic purpose of this module is to print out either "ok #" or "not
250ok #" depending on if a given test succeeded or failed. Everything
251else is just gravy.
252
253All of the following print "ok" or "not ok" depending on if the test
254succeeded or failed. They all also return true or false,
255respectively.
256
257=over 4
258
259=item B<ok>
260
004caa16 261 ok($got eq $expected, $test_name);
3f2ec160 262
004caa16 263This simply evaluates any expression (C<$got eq $expected> is just a
3f2ec160 264simple example) and uses that to determine if the test succeeded or
265failed. A true expression passes, a false one fails. Very simple.
266
267For example:
268
269 ok( $exp{9} == 81, 'simple exponential' );
270 ok( Film->can('db_Main'), 'set_db()' );
271 ok( $p->tests == 4, 'saw tests' );
272 ok( !grep !defined $_, @items, 'items populated' );
273
274(Mnemonic: "This is ok.")
275
276$test_name is a very short description of the test that will be printed
277out. It makes it very easy to find a test in your script when it fails
278and gives others an idea of your intentions. $test_name is optional,
279but we B<very> strongly encourage its use.
280
281Should an ok() fail, it will produce some diagnostics:
282
283 not ok 18 - sufficient mucus
b1ddf169 284 # Failed test 'sufficient mucus'
285 # in foo.t at line 42.
3f2ec160 286
004caa16 287This is the same as Test::Simple's ok() routine.
3f2ec160 288
289=cut
290
33459055 291sub ok ($;$) {
ccbd73a4 292 my( $test, $name ) = @_;
b1ddf169 293 my $tb = Test::More->builder;
294
ccbd73a4 295 return $tb->ok( $test, $name );
33459055 296}
3f2ec160 297
298=item B<is>
299
300=item B<isnt>
301
004caa16 302 is ( $got, $expected, $test_name );
303 isnt( $got, $expected, $test_name );
3f2ec160 304
d020a79a 305Similar to ok(), is() and isnt() compare their two arguments
306with C<eq> and C<ne> respectively and use the result of that to
307determine if the test succeeded or failed. So these:
3f2ec160 308
309 # Is the ultimate answer 42?
310 is( ultimate_answer(), 42, "Meaning of Life" );
311
312 # $foo isn't empty
313 isnt( $foo, '', "Got some foo" );
314
315are similar to these:
316
317 ok( ultimate_answer() eq 42, "Meaning of Life" );
318 ok( $foo ne '', "Got some foo" );
319
320(Mnemonic: "This is that." "This isn't that.")
321
322So why use these? They produce better diagnostics on failure. ok()
323cannot know what you are testing for (beyond the name), but is() and
324isnt() know what the test was and why it failed. For example this
d020a79a 325test:
3f2ec160 326
327 my $foo = 'waffle'; my $bar = 'yarblokos';
328 is( $foo, $bar, 'Is foo the same as bar?' );
329
330Will produce something like this:
331
332 not ok 17 - Is foo the same as bar?
b1ddf169 333 # Failed test 'Is foo the same as bar?'
334 # in foo.t at line 139.
3f2ec160 335 # got: 'waffle'
336 # expected: 'yarblokos'
337
338So you can figure out what went wrong without rerunning the test.
339
340You are encouraged to use is() and isnt() over ok() where possible,
341however do not be tempted to use them to find out if something is
342true or false!
343
30e302f8 344 # XXX BAD!
345 is( exists $brooklyn{tree}, 1, 'A tree grows in Brooklyn' );
3f2ec160 346
30e302f8 347This does not check if C<exists $brooklyn{tree}> is true, it checks if
3f2ec160 348it returns 1. Very different. Similar caveats exist for false and 0.
349In these cases, use ok().
350
30e302f8 351 ok( exists $brooklyn{tree}, 'A tree grows in Brooklyn' );
3f2ec160 352
3e887aae 353A simple call to isnt() usually does not provide a strong test but there
354are cases when you cannot say much more about a value than that it is
355different from some other value:
356
357 new_ok $obj, "Foo";
358
359 my $clone = $obj->clone;
360 isa_ok $obj, "Foo", "Foo->clone";
361
362 isnt $obj, $clone, "clone() produces a different object";
363
d020a79a 364For those grammatical pedants out there, there's an C<isn't()>
365function which is an alias of isnt().
3f2ec160 366
367=cut
368
369sub is ($$;$) {
b1ddf169 370 my $tb = Test::More->builder;
371
ccbd73a4 372 return $tb->is_eq(@_);
3f2ec160 373}
374
375sub isnt ($$;$) {
b1ddf169 376 my $tb = Test::More->builder;
377
ccbd73a4 378 return $tb->isnt_eq(@_);
3f2ec160 379}
380
381*isn't = \&isnt;
382
3f2ec160 383=item B<like>
384
004caa16 385 like( $got, qr/expected/, $test_name );
3f2ec160 386
004caa16 387Similar to ok(), like() matches $got against the regex C<qr/expected/>.
3f2ec160 388
389So this:
390
004caa16 391 like($got, qr/expected/, 'this is like that');
3f2ec160 392
393is similar to:
394
004caa16 395 ok( $got =~ /expected/, 'this is like that');
3f2ec160 396
397(Mnemonic "This is like that".)
398
399The second argument is a regular expression. It may be given as a
4bd4e70a 400regex reference (i.e. C<qr//>) or (for better compatibility with older
3f2ec160 401perls) as a string that looks like a regex (alternative delimiters are
402currently not supported):
403
004caa16 404 like( $got, '/expected/', 'this is like that' );
3f2ec160 405
004caa16 406Regex options may be placed on the end (C<'/expected/i'>).
3f2ec160 407
408Its advantages over ok() are similar to that of is() and isnt(). Better
409diagnostics on failure.
410
411=cut
412
413sub like ($$;$) {
b1ddf169 414 my $tb = Test::More->builder;
415
ccbd73a4 416 return $tb->like(@_);
3f2ec160 417}
418
a9153838 419=item B<unlike>
420
004caa16 421 unlike( $got, qr/expected/, $test_name );
a9153838 422
004caa16 423Works exactly as like(), only it checks if $got B<does not> match the
a9153838 424given pattern.
425
426=cut
427
30e302f8 428sub unlike ($$;$) {
b1ddf169 429 my $tb = Test::More->builder;
430
ccbd73a4 431 return $tb->unlike(@_);
a9153838 432}
433
a9153838 434=item B<cmp_ok>
435
004caa16 436 cmp_ok( $got, $op, $expected, $test_name );
a9153838 437
438Halfway between ok() and is() lies cmp_ok(). This allows you to
439compare two arguments using any binary perl operator.
440
004caa16 441 # ok( $got eq $expected );
442 cmp_ok( $got, 'eq', $expected, 'this eq that' );
a9153838 443
004caa16 444 # ok( $got == $expected );
445 cmp_ok( $got, '==', $expected, 'this == that' );
a9153838 446
004caa16 447 # ok( $got && $expected );
448 cmp_ok( $got, '&&', $expected, 'this && that' );
a9153838 449 ...etc...
450
004caa16 451Its advantage over ok() is when the test fails you'll know what $got
452and $expected were:
a9153838 453
454 not ok 1
b1ddf169 455 # Failed test in foo.t at line 12.
a9153838 456 # '23'
457 # &&
458 # undef
459
6686786d 460It's also useful in those cases where you are comparing numbers and
a9153838 461is()'s use of C<eq> will interfere:
462
463 cmp_ok( $big_hairy_number, '==', $another_big_hairy_number );
464
3e887aae 465It's especially useful when comparing greater-than or smaller-than
466relation between values:
467
468 cmp_ok( $some_value, '<=', $upper_limit );
469
470
a9153838 471=cut
472
473sub cmp_ok($$$;$) {
b1ddf169 474 my $tb = Test::More->builder;
475
ccbd73a4 476 return $tb->cmp_ok(@_);
a9153838 477}
478
d020a79a 479=item B<can_ok>
480
481 can_ok($module, @methods);
482 can_ok($object, @methods);
483
484Checks to make sure the $module or $object can do these @methods
485(works with functions, too).
486
487 can_ok('Foo', qw(this that whatever));
488
489is almost exactly like saying:
490
491 ok( Foo->can('this') &&
492 Foo->can('that') &&
493 Foo->can('whatever')
494 );
495
496only without all the typing and with a better interface. Handy for
497quickly testing an interface.
498
a9153838 499No matter how many @methods you check, a single can_ok() call counts
500as one test. If you desire otherwise, use:
501
502 foreach my $meth (@methods) {
503 can_ok('Foo', $meth);
504 }
505
d020a79a 506=cut
507
508sub can_ok ($@) {
ccbd73a4 509 my( $proto, @methods ) = @_;
89c1e84a 510 my $class = ref $proto || $proto;
b1ddf169 511 my $tb = Test::More->builder;
d020a79a 512
ccbd73a4 513 unless($class) {
68938d83 514 my $ok = $tb->ok( 0, "->can(...)" );
515 $tb->diag(' can_ok() called with empty class or reference');
516 return $ok;
517 }
518
ccbd73a4 519 unless(@methods) {
b1ddf169 520 my $ok = $tb->ok( 0, "$class->can(...)" );
521 $tb->diag(' can_ok() called with no methods');
a9153838 522 return $ok;
523 }
524
d020a79a 525 my @nok = ();
526 foreach my $method (@methods) {
ccbd73a4 527 $tb->_try( sub { $proto->can($method) } ) or push @nok, $method;
d020a79a 528 }
529
ccbd73a4 530 my $name = (@methods == 1) ? "$class->can('$methods[0]')" :
531 "$class->can(...)" ;
1be77ff7 532
b1ddf169 533 my $ok = $tb->ok( !@nok, $name );
d020a79a 534
ccbd73a4 535 $tb->diag( map " $class->can('$_') failed\n", @nok );
d020a79a 536
33459055 537 return $ok;
d020a79a 538}
539
540=item B<isa_ok>
541
3e887aae 542 isa_ok($object, $class, $object_name);
543 isa_ok($subclass, $class, $object_name);
544 isa_ok($ref, $type, $ref_name);
d020a79a 545
30e302f8 546Checks to see if the given C<< $object->isa($class) >>. Also checks to make
d020a79a 547sure the object was defined in the first place. Handy for this sort
548of thing:
549
550 my $obj = Some::Module->new;
551 isa_ok( $obj, 'Some::Module' );
552
553where you'd otherwise have to write
554
555 my $obj = Some::Module->new;
556 ok( defined $obj && $obj->isa('Some::Module') );
557
558to safeguard against your test script blowing up.
559
3e887aae 560You can also test a class, to make sure that it has the right ancestor:
561
562 isa_ok( 'Vole', 'Rodent' );
563
a9153838 564It works on references, too:
565
566 isa_ok( $array_ref, 'ARRAY' );
567
33459055 568The diagnostics of this test normally just refer to 'the object'. If
569you'd like them to be more specific, you can supply an $object_name
570(for example 'Test customer').
571
d020a79a 572=cut
573
33459055 574sub isa_ok ($$;$) {
ccbd73a4 575 my( $object, $class, $obj_name ) = @_;
b1ddf169 576 my $tb = Test::More->builder;
d020a79a 577
578 my $diag;
3e887aae 579
d020a79a 580 if( !defined $object ) {
3e887aae 581 $obj_name = 'The thing' unless defined $obj_name;
33459055 582 $diag = "$obj_name isn't defined";
d020a79a 583 }
a9153838 584 else {
3e887aae 585 my $whatami = ref $object ? 'object' : 'class';
a9153838 586 # We can't use UNIVERSAL::isa because we want to honor isa() overrides
ccbd73a4 587 my( $rslt, $error ) = $tb->_try( sub { $object->isa($class) } );
588 if($error) {
c00d8759 589 if( $error =~ /^Can't call method "isa" on unblessed reference/ ) {
590 # Its an unblessed reference
3e887aae 591 $obj_name = 'The reference' unless defined $obj_name;
ccbd73a4 592 if( !UNIVERSAL::isa( $object, $class ) ) {
a9153838 593 my $ref = ref $object;
6686786d 594 $diag = "$obj_name isn't a '$class' it's a '$ref'";
a9153838 595 }
ccbd73a4 596 }
3e887aae 597 elsif( $error =~ /Can't call method "isa" without a package/ ) {
598 # It's something that can't even be a class
599 $diag = "$obj_name isn't a class or reference";
600 }
ccbd73a4 601 else {
a9153838 602 die <<WHOA;
3e887aae 603WHOA! I tried to call ->isa on your $whatami and got some weird error.
a9153838 604Here's the error.
c00d8759 605$error
a9153838 606WHOA
607 }
608 }
3e887aae 609 else {
610 $obj_name = "The $whatami" unless defined $obj_name;
611 if( !$rslt ) {
612 my $ref = ref $object;
613 $diag = "$obj_name isn't a '$class' it's a '$ref'";
614 }
a9153838 615 }
d020a79a 616 }
617
3e887aae 618 my $name = "$obj_name isa $class";
33459055 619 my $ok;
ccbd73a4 620 if($diag) {
b1ddf169 621 $ok = $tb->ok( 0, $name );
622 $tb->diag(" $diag\n");
d020a79a 623 }
624 else {
b1ddf169 625 $ok = $tb->ok( 1, $name );
d020a79a 626 }
33459055 627
628 return $ok;
d020a79a 629}
630
ccbd73a4 631=item B<new_ok>
632
633 my $obj = new_ok( $class );
634 my $obj = new_ok( $class => \@args );
635 my $obj = new_ok( $class => \@args, $object_name );
636
637A convenience function which combines creating an object and calling
638isa_ok() on that object.
639
640It is basically equivalent to:
641
642 my $obj = $class->new(@args);
643 isa_ok $obj, $class, $object_name;
644
645If @args is not given, an empty list will be used.
646
647This function only works on new() and it assumes new() will return
648just a single object which isa C<$class>.
649
650=cut
651
652sub new_ok {
653 my $tb = Test::More->builder;
654 $tb->croak("new_ok() must be given at least a class") unless @_;
655
656 my( $class, $args, $object_name ) = @_;
657
658 $args ||= [];
659 $object_name = "The object" unless defined $object_name;
660
661 my $obj;
662 my( $success, $error ) = $tb->_try( sub { $obj = $class->new(@$args); 1 } );
663 if($success) {
664 local $Test::Builder::Level = $Test::Builder::Level + 1;
665 isa_ok $obj, $class, $object_name;
666 }
667 else {
668 $tb->ok( 0, "new() died" );
669 $tb->diag(" Error was: $error");
670 }
671
672 return $obj;
673}
d020a79a 674
3f2ec160 675=item B<pass>
676
677=item B<fail>
678
679 pass($test_name);
680 fail($test_name);
681
682Sometimes you just want to say that the tests have passed. Usually
683the case is you've got some complicated condition that is difficult to
684wedge into an ok(). In this case, you can simply use pass() (to
685declare the test ok) or fail (for not ok). They are synonyms for
686ok(1) and ok(0).
687
688Use these very, very, very sparingly.
689
690=cut
691
d020a79a 692sub pass (;$) {
b1ddf169 693 my $tb = Test::More->builder;
ccbd73a4 694
695 return $tb->ok( 1, @_ );
3f2ec160 696}
697
d020a79a 698sub fail (;$) {
b1ddf169 699 my $tb = Test::More->builder;
ccbd73a4 700
701 return $tb->ok( 0, @_ );
3f2ec160 702}
703
704=back
705
a9153838 706
3f2ec160 707=head2 Module tests
708
709You usually want to test if the module you're testing loads ok, rather
710than just vomiting if its load fails. For such purposes we have
711C<use_ok> and C<require_ok>.
712
713=over 4
714
715=item B<use_ok>
716
3f2ec160 717 BEGIN { use_ok($module); }
d020a79a 718 BEGIN { use_ok($module, @imports); }
719
720These simply use the given $module and test to make sure the load
89c1e84a 721happened ok. It's recommended that you run use_ok() inside a BEGIN
d020a79a 722block so its functions are exported at compile-time and prototypes are
723properly honored.
724
725If @imports are given, they are passed through to the use. So this:
726
727 BEGIN { use_ok('Some::Module', qw(foo bar)) }
728
729is like doing this:
730
731 use Some::Module qw(foo bar);
3f2ec160 732
30e302f8 733Version numbers can be checked like so:
734
735 # Just like "use Some::Module 1.02"
736 BEGIN { use_ok('Some::Module', 1.02) }
737
738Don't try to do this:
a344be10 739
740 BEGIN {
741 use_ok('Some::Module');
742
743 ...some code that depends on the use...
744 ...happening at compile time...
745 }
746
30e302f8 747because the notion of "compile-time" is relative. Instead, you want:
a344be10 748
749 BEGIN { use_ok('Some::Module') }
750 BEGIN { ...some code that depends on the use... }
751
3f2ec160 752
753=cut
754
d020a79a 755sub use_ok ($;@) {
ccbd73a4 756 my( $module, @imports ) = @_;
d020a79a 757 @imports = () unless @imports;
b1ddf169 758 my $tb = Test::More->builder;
3f2ec160 759
ccbd73a4 760 my( $pack, $filename, $line ) = caller;
3f2ec160 761
705e6672 762 my $code;
763 if( @imports == 1 and $imports[0] =~ /^\d+(?:\.\d+)?$/ ) {
764 # probably a version check. Perl needs to see the bare number
765 # for it to work with non-Exporter based modules.
766 $code = <<USE;
3f2ec160 767package $pack;
30e302f8 768use $module $imports[0];
705e6672 7691;
3f2ec160 770USE
705e6672 771 }
772 else {
773 $code = <<USE;
30e302f8 774package $pack;
705e6672 775use $module \@{\$args[0]};
7761;
30e302f8 777USE
778 }
3f2ec160 779
ccbd73a4 780 my( $eval_result, $eval_error ) = _eval( $code, \@imports );
705e6672 781 my $ok = $tb->ok( $eval_result, "use $module;" );
ccbd73a4 782
783 unless($ok) {
00881caa 784 chomp $eval_error;
30e302f8 785 $@ =~ s{^BEGIN failed--compilation aborted at .*$}
786 {BEGIN failed--compilation aborted at $filename line $line.}m;
b1ddf169 787 $tb->diag(<<DIAGNOSTIC);
a9153838 788 Tried to use '$module'.
00881caa 789 Error: $eval_error
3f2ec160 790DIAGNOSTIC
791
792 }
793
794 return $ok;
795}
796
705e6672 797sub _eval {
ccbd73a4 798 my( $code, @args ) = @_;
705e6672 799
800 # Work around oddities surrounding resetting of $@ by immediately
801 # storing it.
ccbd73a4 802 my( $sigdie, $eval_result, $eval_error );
803 {
804 local( $@, $!, $SIG{__DIE__} ); # isolate eval
805 $eval_result = eval $code; ## no critic (BuiltinFunctions::ProhibitStringyEval)
806 $eval_error = $@;
807 $sigdie = $SIG{__DIE__} || undef;
808 }
809 # make sure that $code got a chance to set $SIG{__DIE__}
810 $SIG{__DIE__} = $sigdie if defined $sigdie;
705e6672 811
ccbd73a4 812 return( $eval_result, $eval_error );
705e6672 813}
814
d020a79a 815=item B<require_ok>
816
817 require_ok($module);
7483b81c 818 require_ok($file);
d020a79a 819
7483b81c 820Like use_ok(), except it requires the $module or $file.
d020a79a 821
822=cut
3f2ec160 823
824sub require_ok ($) {
825 my($module) = shift;
b1ddf169 826 my $tb = Test::More->builder;
3f2ec160 827
828 my $pack = caller;
829
7483b81c 830 # Try to deterine if we've been given a module name or file.
831 # Module names must be barewords, files not.
832 $module = qq['$module'] unless _is_module_name($module);
833
705e6672 834 my $code = <<REQUIRE;
3f2ec160 835package $pack;
836require $module;
705e6672 8371;
3f2ec160 838REQUIRE
839
ccbd73a4 840 my( $eval_result, $eval_error ) = _eval($code);
705e6672 841 my $ok = $tb->ok( $eval_result, "require $module;" );
3f2ec160 842
ccbd73a4 843 unless($ok) {
705e6672 844 chomp $eval_error;
b1ddf169 845 $tb->diag(<<DIAGNOSTIC);
a9153838 846 Tried to require '$module'.
705e6672 847 Error: $eval_error
3f2ec160 848DIAGNOSTIC
849
850 }
851
852 return $ok;
853}
854
7483b81c 855sub _is_module_name {
856 my $module = shift;
857
858 # Module names start with a letter.
859 # End with an alphanumeric.
860 # The rest is an alphanumeric or ::
861 $module =~ s/\b::\b//g;
ccbd73a4 862
863 return $module =~ /^[a-zA-Z]\w*$/ ? 1 : 0;
7483b81c 864}
865
d020a79a 866=back
3f2ec160 867
b1ddf169 868
869=head2 Complex data structures
870
871Not everything is a simple eq check or regex. There are times you
872need to see if two data structures are equivalent. For these
873instances Test::More provides a handful of useful functions.
874
875B<NOTE> I'm not quite sure what will happen with filehandles.
876
877=over 4
878
879=item B<is_deeply>
880
004caa16 881 is_deeply( $got, $expected, $test_name );
b1ddf169 882
004caa16 883Similar to is(), except that if $got and $expected are references, it
b1ddf169 884does a deep comparison walking each data structure to see if they are
885equivalent. If the two structures are different, it will display the
886place where they start differing.
887
888is_deeply() compares the dereferenced values of references, the
889references themselves (except for their type) are ignored. This means
890aspects such as blessing and ties are not considered "different".
891
3e887aae 892is_deeply() currently has very limited handling of function reference
845d7e37 893and globs. It merely checks if they have the same referent. This may
894improve in the future.
895
3e887aae 896L<Test::Differences> and L<Test::Deep> provide more in-depth functionality
b1ddf169 897along these lines.
898
899=cut
900
ccbd73a4 901our( @Data_Stack, %Refs_Seen );
b1ddf169 902my $DNE = bless [], 'Does::Not::Exist';
6b38a9b9 903
904sub _dne {
ccbd73a4 905 return ref $_[0] eq ref $DNE;
6b38a9b9 906}
907
ccbd73a4 908## no critic (Subroutines::RequireArgUnpacking)
b1ddf169 909sub is_deeply {
910 my $tb = Test::More->builder;
911
912 unless( @_ == 2 or @_ == 3 ) {
ccbd73a4 913 my $msg = <<'WARNING';
b1ddf169 914is_deeply() takes two or three args, you gave %d.
915This usually means you passed an array or hash instead
916of a reference to it
917WARNING
ccbd73a4 918 chop $msg; # clip off newline so carp() will put in line/file
b1ddf169 919
920 _carp sprintf $msg, scalar @_;
921
ccbd73a4 922 return $tb->ok(0);
b1ddf169 923 }
924
ccbd73a4 925 my( $got, $expected, $name ) = @_;
b1ddf169 926
ccbd73a4 927 $tb->_unoverload_str( \$expected, \$got );
b1ddf169 928
929 my $ok;
ccbd73a4 930 if( !ref $got and !ref $expected ) { # neither is a reference
931 $ok = $tb->is_eq( $got, $expected, $name );
b1ddf169 932 }
ccbd73a4 933 elsif( !ref $got xor !ref $expected ) { # one's a reference, one isn't
934 $ok = $tb->ok( 0, $name );
935 $tb->diag( _format_stack({ vals => [ $got, $expected ] }) );
b1ddf169 936 }
ccbd73a4 937 else { # both references
b1ddf169 938 local @Data_Stack = ();
ccbd73a4 939 if( _deep_check( $got, $expected ) ) {
940 $ok = $tb->ok( 1, $name );
b1ddf169 941 }
942 else {
ccbd73a4 943 $ok = $tb->ok( 0, $name );
944 $tb->diag( _format_stack(@Data_Stack) );
b1ddf169 945 }
946 }
947
948 return $ok;
949}
950
951sub _format_stack {
952 my(@Stack) = @_;
953
ccbd73a4 954 my $var = '$FOO';
b1ddf169 955 my $did_arrow = 0;
956 foreach my $entry (@Stack) {
957 my $type = $entry->{type} || '';
ccbd73a4 958 my $idx = $entry->{'idx'};
b1ddf169 959 if( $type eq 'HASH' ) {
960 $var .= "->" unless $did_arrow++;
961 $var .= "{$idx}";
962 }
963 elsif( $type eq 'ARRAY' ) {
964 $var .= "->" unless $did_arrow++;
965 $var .= "[$idx]";
966 }
967 elsif( $type eq 'REF' ) {
968 $var = "\${$var}";
969 }
970 }
971
ccbd73a4 972 my @vals = @{ $Stack[-1]{vals} }[ 0, 1 ];
b1ddf169 973 my @vars = ();
ccbd73a4 974 ( $vars[0] = $var ) =~ s/\$FOO/ \$got/;
975 ( $vars[1] = $var ) =~ s/\$FOO/\$expected/;
b1ddf169 976
977 my $out = "Structures begin differing at:\n";
ccbd73a4 978 foreach my $idx ( 0 .. $#vals ) {
b1ddf169 979 my $val = $vals[$idx];
ccbd73a4 980 $vals[$idx]
981 = !defined $val ? 'undef'
982 : _dne($val) ? "Does not exist"
983 : ref $val ? "$val"
984 : "'$val'";
b1ddf169 985 }
986
987 $out .= "$vars[0] = $vals[0]\n";
988 $out .= "$vars[1] = $vals[1]\n";
989
990 $out =~ s/^/ /msg;
991 return $out;
992}
993
b1ddf169 994sub _type {
995 my $thing = shift;
996
997 return '' if !ref $thing;
998
845d7e37 999 for my $type (qw(ARRAY HASH REF SCALAR GLOB CODE Regexp)) {
ccbd73a4 1000 return $type if UNIVERSAL::isa( $thing, $type );
b1ddf169 1001 }
1002
1003 return '';
1004}
1005
1006=back
1007
1008
1009=head2 Diagnostics
1010
1011If you pick the right test function, you'll usually get a good idea of
1012what went wrong when it failed. But sometimes it doesn't work out
1013that way. So here we have ways for you to write your own diagnostic
1014messages which are safer than just C<print STDERR>.
1015
1016=over 4
1017
1018=item B<diag>
1019
1020 diag(@diagnostic_message);
1021
1022Prints a diagnostic message which is guaranteed not to interfere with
1023test output. Like C<print> @diagnostic_message is simply concatenated
1024together.
1025
ccbd73a4 1026Returns false, so as to preserve failure.
1027
b1ddf169 1028Handy for this sort of thing:
1029
1030 ok( grep(/foo/, @users), "There's a foo user" ) or
1031 diag("Since there's no foo, check that /etc/bar is set up right");
1032
1033which would produce:
1034
1035 not ok 42 - There's a foo user
1036 # Failed test 'There's a foo user'
1037 # in foo.t at line 52.
1038 # Since there's no foo, check that /etc/bar is set up right.
1039
1040You might remember C<ok() or diag()> with the mnemonic C<open() or
1041die()>.
1042
1043B<NOTE> The exact formatting of the diagnostic output is still
1044changing, but it is guaranteed that whatever you throw at it it won't
1045interfere with the test.
1046
ccbd73a4 1047=item B<note>
1048
1049 note(@diagnostic_message);
1050
1051Like diag(), except the message will not be seen when the test is run
1052in a harness. It will only be visible in the verbose TAP stream.
1053
1054Handy for putting in notes which might be useful for debugging, but
1055don't indicate a problem.
1056
1057 note("Tempfile is $tempfile");
1058
b1ddf169 1059=cut
1060
1061sub diag {
ccbd73a4 1062 return Test::More->builder->diag(@_);
1063}
b1ddf169 1064
ccbd73a4 1065sub note {
1066 return Test::More->builder->note(@_);
b1ddf169 1067}
1068
ccbd73a4 1069=item B<explain>
1070
1071 my @dump = explain @diagnostic_message;
1072
1073Will dump the contents of any references in a human readable format.
3e887aae 1074Usually you want to pass this into C<note> or C<diag>.
ccbd73a4 1075
1076Handy for things like...
1077
1078 is_deeply($have, $want) || diag explain $have;
1079
1080or
1081
1082 note explain \%args;
1083 Some::Class->method(%args);
1084
1085=cut
1086
1087sub explain {
1088 return Test::More->builder->explain(@_);
1089}
b1ddf169 1090
1091=back
1092
1093
3f2ec160 1094=head2 Conditional tests
1095
1096Sometimes running a test under certain conditions will cause the
1097test script to die. A certain function or method isn't implemented
1098(such as fork() on MacOS), some resource isn't available (like a
d020a79a 1099net connection) or a module isn't available. In these cases it's
1100necessary to skip tests, or declare that they are supposed to fail
3f2ec160 1101but will work in the future (a todo test).
1102
a9153838 1103For more details on the mechanics of skip and todo tests see
1104L<Test::Harness>.
d020a79a 1105
1106The way Test::More handles this is with a named block. Basically, a
1107block of tests which can be skipped over or made todo. It's best if I
1108just show you...
3f2ec160 1109
1110=over 4
1111
d020a79a 1112=item B<SKIP: BLOCK>
1113
1114 SKIP: {
1115 skip $why, $how_many if $condition;
3f2ec160 1116
d020a79a 1117 ...normal testing code goes here...
1118 }
3f2ec160 1119
a344be10 1120This declares a block of tests that might be skipped, $how_many tests
1121there are, $why and under what $condition to skip them. An example is
1122the easiest way to illustrate:
3f2ec160 1123
d020a79a 1124 SKIP: {
a344be10 1125 eval { require HTML::Lint };
3f2ec160 1126
a344be10 1127 skip "HTML::Lint not installed", 2 if $@;
d020a79a 1128
a344be10 1129 my $lint = new HTML::Lint;
60ffb308 1130 isa_ok( $lint, "HTML::Lint" );
3f2ec160 1131
a344be10 1132 $lint->parse( $html );
60ffb308 1133 is( $lint->errors, 0, "No errors found in HTML" );
a344be10 1134 }
d020a79a 1135
a344be10 1136If the user does not have HTML::Lint installed, the whole block of
1137code I<won't be run at all>. Test::More will output special ok's
1138which Test::Harness interprets as skipped, but passing, tests.
0257f296 1139
a344be10 1140It's important that $how_many accurately reflects the number of tests
1141in the SKIP block so the # of tests run will match up with your plan.
0257f296 1142If your plan is C<no_plan> $how_many is optional and will default to 1.
a9153838 1143
a344be10 1144It's perfectly safe to nest SKIP blocks. Each SKIP block must have
1145the label C<SKIP>, or Test::More can't work its magic.
a9153838 1146
1147You don't skip tests which are failing because there's a bug in your
a344be10 1148program, or for which you don't yet have code written. For that you
1149use TODO. Read on.
3f2ec160 1150
1151=cut
1152
ccbd73a4 1153## no critic (Subroutines::RequireFinalReturn)
1af51bd3 1154sub skip {
ccbd73a4 1155 my( $why, $how_many ) = @_;
b1ddf169 1156 my $tb = Test::More->builder;
33459055 1157
1158 unless( defined $how_many ) {
d020a79a 1159 # $how_many can only be avoided when no_plan is in use.
33459055 1160 _carp "skip() needs to know \$how_many tests are in the block"
b1ddf169 1161 unless $tb->has_plan eq 'no_plan';
d020a79a 1162 $how_many = 1;
1163 }
1164
1be77ff7 1165 if( defined $how_many and $how_many =~ /\D/ ) {
ccbd73a4 1166 _carp
1167 "skip() was passed a non-numeric number of tests. Did you get the arguments backwards?";
1be77ff7 1168 $how_many = 1;
1169 }
1170
ccbd73a4 1171 for( 1 .. $how_many ) {
b1ddf169 1172 $tb->skip($why);
d020a79a 1173 }
1174
ccbd73a4 1175 no warnings 'exiting';
d020a79a 1176 last SKIP;
3f2ec160 1177}
1178
d020a79a 1179=item B<TODO: BLOCK>
3f2ec160 1180
d020a79a 1181 TODO: {
a9153838 1182 local $TODO = $why if $condition;
3f2ec160 1183
d020a79a 1184 ...normal testing code goes here...
1185 }
3f2ec160 1186
d020a79a 1187Declares a block of tests you expect to fail and $why. Perhaps it's
1188because you haven't fixed a bug or haven't finished a new feature:
3f2ec160 1189
d020a79a 1190 TODO: {
1191 local $TODO = "URI::Geller not finished";
3f2ec160 1192
d020a79a 1193 my $card = "Eight of clubs";
1194 is( URI::Geller->your_card, $card, 'Is THIS your card?' );
3f2ec160 1195
d020a79a 1196 my $spoon;
1197 URI::Geller->bend_spoon;
1198 is( $spoon, 'bent', "Spoon bending, that's original" );
1199 }
1200
1201With a todo block, the tests inside are expected to fail. Test::More
1202will run the tests normally, but print out special flags indicating
1203they are "todo". Test::Harness will interpret failures as being ok.
1204Should anything succeed, it will report it as an unexpected success.
a344be10 1205You then know the thing you had todo is done and can remove the
1206TODO flag.
d020a79a 1207
1208The nice part about todo tests, as opposed to simply commenting out a
4bd4e70a 1209block of tests, is it's like having a programmatic todo list. You know
d020a79a 1210how much work is left to be done, you're aware of what bugs there are,
1211and you'll know immediately when they're fixed.
1212
1213Once a todo test starts succeeding, simply move it outside the block.
1214When the block is empty, delete it.
1215
30e302f8 1216B<NOTE>: TODO tests require a Test::Harness upgrade else it will
b1ddf169 1217treat it as a normal failure. See L<CAVEATS and NOTES>).
30e302f8 1218
d020a79a 1219
a9153838 1220=item B<todo_skip>
1221
1222 TODO: {
1223 todo_skip $why, $how_many if $condition;
1224
1225 ...normal testing code...
1226 }
1227
89c1e84a 1228With todo tests, it's best to have the tests actually run. That way
a9153838 1229you'll know when they start passing. Sometimes this isn't possible.
1230Often a failing test will cause the whole program to die or hang, even
1231inside an C<eval BLOCK> with and using C<alarm>. In these extreme
1232cases you have no choice but to skip over the broken tests entirely.
1233
1234The syntax and behavior is similar to a C<SKIP: BLOCK> except the
1235tests will be marked as failing but todo. Test::Harness will
1236interpret them as passing.
1237
1238=cut
1239
1240sub todo_skip {
ccbd73a4 1241 my( $why, $how_many ) = @_;
b1ddf169 1242 my $tb = Test::More->builder;
a9153838 1243
1244 unless( defined $how_many ) {
1245 # $how_many can only be avoided when no_plan is in use.
1246 _carp "todo_skip() needs to know \$how_many tests are in the block"
b1ddf169 1247 unless $tb->has_plan eq 'no_plan';
a9153838 1248 $how_many = 1;
1249 }
1250
ccbd73a4 1251 for( 1 .. $how_many ) {
b1ddf169 1252 $tb->todo_skip($why);
a9153838 1253 }
1254
ccbd73a4 1255 no warnings 'exiting';
a9153838 1256 last TODO;
1257}
1258
a344be10 1259=item When do I use SKIP vs. TODO?
1260
1261B<If it's something the user might not be able to do>, use SKIP.
1262This includes optional modules that aren't installed, running under
1263an OS that doesn't have some feature (like fork() or symlinks), or maybe
1264you need an Internet connection and one isn't available.
1265
1266B<If it's something the programmer hasn't done yet>, use TODO. This
1267is for any code you haven't written yet, or bugs you have yet to fix,
1268but want to put tests in your testing script (always a good idea).
1269
a9153838 1270
d020a79a 1271=back
3f2ec160 1272
3f2ec160 1273
b1ddf169 1274=head2 Test control
3f2ec160 1275
1276=over 4
1277
b1ddf169 1278=item B<BAIL_OUT>
33459055 1279
b1ddf169 1280 BAIL_OUT($reason);
33459055 1281
68938d83 1282Indicates to the harness that things are going so badly all testing
b1ddf169 1283should terminate. This includes the running any additional test scripts.
33459055 1284
b1ddf169 1285This is typically used when testing cannot continue such as a critical
1286module failing to compile or a necessary external utility not being
1287available such as a database connection failing.
33459055 1288
b1ddf169 1289The test will exit with 255.
33459055 1290
3e887aae 1291For even better control look at L<Test::Most>.
1292
b1ddf169 1293=cut
33459055 1294
b1ddf169 1295sub BAIL_OUT {
1296 my $reason = shift;
ccbd73a4 1297 my $tb = Test::More->builder;
33459055 1298
b1ddf169 1299 $tb->BAIL_OUT($reason);
33459055 1300}
1301
b1ddf169 1302=back
0257f296 1303
1304
5143c659 1305=head2 Discouraged comparison functions
1306
1307The use of the following functions is discouraged as they are not
1308actually testing functions and produce no diagnostics to help figure
1309out what went wrong. They were written before is_deeply() existed
1310because I couldn't figure out how to display a useful diff of two
1311arbitrary data structures.
1312
1313These functions are usually used inside an ok().
1314
004caa16 1315 ok( eq_array(\@got, \@expected) );
5143c659 1316
1317C<is_deeply()> can do that better and with diagnostics.
1318
004caa16 1319 is_deeply( \@got, \@expected );
5143c659 1320
1321They may be deprecated in future versions.
1322
b1ddf169 1323=over 4
5143c659 1324
3f2ec160 1325=item B<eq_array>
1326
004caa16 1327 my $is_eq = eq_array(\@got, \@expected);
3f2ec160 1328
1329Checks if two arrays are equivalent. This is a deep check, so
1330multi-level structures are handled correctly.
1331
1332=cut
1333
1334#'#
7483b81c 1335sub eq_array {
ccbd73a4 1336 local @Data_Stack = ();
5143c659 1337 _deep_check(@_);
7483b81c 1338}
1339
ccbd73a4 1340sub _eq_array {
1341 my( $a1, $a2 ) = @_;
7483b81c 1342
ccbd73a4 1343 if( grep _type($_) ne 'ARRAY', $a1, $a2 ) {
7483b81c 1344 warn "eq_array passed a non-array ref";
1345 return 0;
1346 }
1347
3f2ec160 1348 return 1 if $a1 eq $a2;
1349
1350 my $ok = 1;
33459055 1351 my $max = $#$a1 > $#$a2 ? $#$a1 : $#$a2;
ccbd73a4 1352 for( 0 .. $max ) {
33459055 1353 my $e1 = $_ > $#$a1 ? $DNE : $a1->[$_];
1354 my $e2 = $_ > $#$a2 ? $DNE : $a2->[$_];
1355
ccbd73a4 1356 push @Data_Stack, { type => 'ARRAY', idx => $_, vals => [ $e1, $e2 ] };
1357 $ok = _deep_check( $e1, $e2 );
33459055 1358 pop @Data_Stack if $ok;
1359
3f2ec160 1360 last unless $ok;
1361 }
7483b81c 1362
3f2ec160 1363 return $ok;
1364}
1365
1366sub _deep_check {
ccbd73a4 1367 my( $e1, $e2 ) = @_;
b1ddf169 1368 my $tb = Test::More->builder;
1369
3f2ec160 1370 my $ok = 0;
1371
5143c659 1372 # Effectively turn %Refs_Seen into a stack. This avoids picking up
1373 # the same referenced used twice (such as [\$a, \$a]) to be considered
1374 # circular.
1375 local %Refs_Seen = %Refs_Seen;
1376
d020a79a 1377 {
4bd4e70a 1378 # Quiet uninitialized value warnings when comparing undefs.
ccbd73a4 1379 no warnings 'uninitialized';
d020a79a 1380
ccbd73a4 1381 $tb->_unoverload_str( \$e1, \$e2 );
7483b81c 1382
1383 # Either they're both references or both not.
ccbd73a4 1384 my $same_ref = !( !ref $e1 xor !ref $e2 );
1385 my $not_ref = ( !ref $e1 and !ref $e2 );
7483b81c 1386
1387 if( defined $e1 xor defined $e2 ) {
1388 $ok = 0;
1389 }
3e887aae 1390 elsif( !defined $e1 and !defined $e2 ) {
1391 # Shortcut if they're both defined.
1392 $ok = 1;
1393 }
ccbd73a4 1394 elsif( _dne($e1) xor _dne($e2) ) {
7483b81c 1395 $ok = 0;
1396 }
ccbd73a4 1397 elsif( $same_ref and( $e1 eq $e2 ) ) {
d020a79a 1398 $ok = 1;
3f2ec160 1399 }
ccbd73a4 1400 elsif($not_ref) {
1401 push @Data_Stack, { type => '', vals => [ $e1, $e2 ] };
1402 $ok = 0;
1403 }
3f2ec160 1404 else {
5143c659 1405 if( $Refs_Seen{$e1} ) {
1406 return $Refs_Seen{$e1} eq $e2;
1407 }
1408 else {
1409 $Refs_Seen{$e1} = "$e2";
1410 }
1411
0257f296 1412 my $type = _type($e1);
5143c659 1413 $type = 'DIFFERENT' unless _type($e2) eq $type;
0257f296 1414
5143c659 1415 if( $type eq 'DIFFERENT' ) {
ccbd73a4 1416 push @Data_Stack, { type => $type, vals => [ $e1, $e2 ] };
0257f296 1417 $ok = 0;
1418 }
1419 elsif( $type eq 'ARRAY' ) {
ccbd73a4 1420 $ok = _eq_array( $e1, $e2 );
d020a79a 1421 }
0257f296 1422 elsif( $type eq 'HASH' ) {
ccbd73a4 1423 $ok = _eq_hash( $e1, $e2 );
d020a79a 1424 }
0257f296 1425 elsif( $type eq 'REF' ) {
ccbd73a4 1426 push @Data_Stack, { type => $type, vals => [ $e1, $e2 ] };
1427 $ok = _deep_check( $$e1, $$e2 );
33459055 1428 pop @Data_Stack if $ok;
1429 }
0257f296 1430 elsif( $type eq 'SCALAR' ) {
ccbd73a4 1431 push @Data_Stack, { type => 'REF', vals => [ $e1, $e2 ] };
1432 $ok = _deep_check( $$e1, $$e2 );
7483b81c 1433 pop @Data_Stack if $ok;
33459055 1434 }
ccbd73a4 1435 elsif($type) {
1436 push @Data_Stack, { type => $type, vals => [ $e1, $e2 ] };
845d7e37 1437 $ok = 0;
1438 }
ccbd73a4 1439 else {
1440 _whoa( 1, "No type in _deep_check" );
1441 }
3f2ec160 1442 }
1443 }
d020a79a 1444
3f2ec160 1445 return $ok;
1446}
1447
5143c659 1448sub _whoa {
ccbd73a4 1449 my( $check, $desc ) = @_;
1450 if($check) {
1451 die <<"WHOA";
5143c659 1452WHOA! $desc
1453This should never happen! Please contact the author immediately!
1454WHOA
1455 }
1456}
1457
3f2ec160 1458=item B<eq_hash>
1459
004caa16 1460 my $is_eq = eq_hash(\%got, \%expected);
3f2ec160 1461
1462Determines if the two hashes contain the same keys and values. This
1463is a deep check.
1464
1465=cut
1466
1467sub eq_hash {
ccbd73a4 1468 local @Data_Stack = ();
5143c659 1469 return _deep_check(@_);
7483b81c 1470}
1471
1472sub _eq_hash {
ccbd73a4 1473 my( $a1, $a2 ) = @_;
7483b81c 1474
ccbd73a4 1475 if( grep _type($_) ne 'HASH', $a1, $a2 ) {
7483b81c 1476 warn "eq_hash passed a non-hash ref";
1477 return 0;
1478 }
1479
3f2ec160 1480 return 1 if $a1 eq $a2;
1481
1482 my $ok = 1;
33459055 1483 my $bigger = keys %$a1 > keys %$a2 ? $a1 : $a2;
ccbd73a4 1484 foreach my $k ( keys %$bigger ) {
33459055 1485 my $e1 = exists $a1->{$k} ? $a1->{$k} : $DNE;
1486 my $e2 = exists $a2->{$k} ? $a2->{$k} : $DNE;
1487
ccbd73a4 1488 push @Data_Stack, { type => 'HASH', idx => $k, vals => [ $e1, $e2 ] };
1489 $ok = _deep_check( $e1, $e2 );
33459055 1490 pop @Data_Stack if $ok;
1491
3f2ec160 1492 last unless $ok;
1493 }
1494
1495 return $ok;
1496}
1497
1498=item B<eq_set>
1499
004caa16 1500 my $is_eq = eq_set(\@got, \@expected);
3f2ec160 1501
1502Similar to eq_array(), except the order of the elements is B<not>
1503important. This is a deep check, but the irrelevancy of order only
1504applies to the top level.
1505
004caa16 1506 ok( eq_set(\@got, \@expected) );
5143c659 1507
1508Is better written:
1509
004caa16 1510 is_deeply( [sort @got], [sort @expected] );
5143c659 1511
3c4b39be 1512B<NOTE> By historical accident, this is not a true set comparison.
60ffb308 1513While the order of elements does not matter, duplicate elements do.
1514
b1ddf169 1515B<NOTE> eq_set() does not know how to deal with references at the top
1516level. The following is an example of a comparison which might not work:
1517
1518 eq_set([\1, \2], [\2, \1]);
1519
3e887aae 1520L<Test::Deep> contains much better set comparison functions.
5143c659 1521
3f2ec160 1522=cut
1523
ccbd73a4 1524sub eq_set {
1525 my( $a1, $a2 ) = @_;
3f2ec160 1526 return 0 unless @$a1 == @$a2;
1527
ccbd73a4 1528 no warnings 'uninitialized';
7483b81c 1529
ccbd73a4 1530 # It really doesn't matter how we sort them, as long as both arrays are
b1ddf169 1531 # sorted with the same algorithm.
1532 #
1533 # Ensure that references are not accidentally treated the same as a
1534 # string containing the reference.
1535 #
7483b81c 1536 # Have to inline the sort routine due to a threading/sort bug.
1537 # See [rt.cpan.org 6782]
b1ddf169 1538 #
1539 # I don't know how references would be sorted so we just don't sort
1540 # them. This means eq_set doesn't really work with refs.
7483b81c 1541 return eq_array(
ccbd73a4 1542 [ grep( ref, @$a1 ), sort( grep( !ref, @$a1 ) ) ],
1543 [ grep( ref, @$a2 ), sort( grep( !ref, @$a2 ) ) ],
7483b81c 1544 );
3f2ec160 1545}
1546
3f2ec160 1547=back
1548
d020a79a 1549
a9153838 1550=head2 Extending and Embedding Test::More
d020a79a 1551
a9153838 1552Sometimes the Test::More interface isn't quite enough. Fortunately,
1553Test::More is built on top of Test::Builder which provides a single,
1554unified backend for any test library to use. This means two test
1555libraries which both use Test::Builder B<can be used together in the
1556same program>.
1557
1558If you simply want to do a little tweaking of how the tests behave,
1559you can access the underlying Test::Builder object like so:
3f2ec160 1560
d020a79a 1561=over 4
1562
a9153838 1563=item B<builder>
d020a79a 1564
a9153838 1565 my $test_builder = Test::More->builder;
d020a79a 1566
a9153838 1567Returns the Test::Builder object underlying Test::More for you to play
1568with.
1569
d020a79a 1570
a9153838 1571=back
3f2ec160 1572
d020a79a 1573
30e302f8 1574=head1 EXIT CODES
1575
1576If all your tests passed, Test::Builder will exit with zero (which is
1577normal). If anything failed it will exit with how many failed. If
1578you run less (or more) tests than you planned, the missing (or extras)
1579will be considered failures. If no tests were ever run Test::Builder
1580will throw a warning and exit with 255. If the test died, even after
1581having successfully completed all its tests, it will still be
1582considered a failure and will exit with 255.
1583
1584So the exit codes are...
1585
1586 0 all tests successful
b1ddf169 1587 255 test died or all passed but wrong # of tests run
30e302f8 1588 any other number how many failed (including missing or extras)
1589
1590If you fail more than 254 tests, it will be reported as 254.
1591
5143c659 1592B<NOTE> This behavior may go away in future versions.
1593
30e302f8 1594
7483b81c 1595=head1 CAVEATS and NOTES
a9153838 1596
7483b81c 1597=over 4
d020a79a 1598
7483b81c 1599=item Backwards compatibility
1600
705e6672 1601Test::More works with Perls as old as 5.6.0.
7483b81c 1602
1603
3e887aae 1604=item utf8 / "Wide character in print"
1605
1606If you use utf8 or other non-ASCII characters with Test::More you
1607might get a "Wide character in print" warning. Using C<binmode
1608STDOUT, ":utf8"> will not fix it. Test::Builder (which powers
1609Test::More) duplicates STDOUT and STDERR. So any changes to them,
1610including changing their output disciplines, will not be seem by
1611Test::More.
1612
1613The work around is to change the filehandles used by Test::Builder
1614directly.
1615
1616 my $builder = Test::More->builder;
1617 binmode $builder->output, ":utf8";
1618 binmode $builder->failure_output, ":utf8";
1619 binmode $builder->todo_output, ":utf8";
1620
1621
7483b81c 1622=item Overloaded objects
1623
b1ddf169 1624String overloaded objects are compared B<as strings> (or in cmp_ok()'s
1625case, strings or numbers as appropriate to the comparison op). This
1626prevents Test::More from piercing an object's interface allowing
1627better blackbox testing. So if a function starts returning overloaded
1628objects instead of bare strings your tests won't notice the
1629difference. This is good.
7483b81c 1630
1631However, it does mean that functions like is_deeply() cannot be used to
1632test the internals of string overloaded objects. In this case I would
3e887aae 1633suggest L<Test::Deep> which contains more flexible testing functions for
7483b81c 1634complex data structures.
a9153838 1635
a9153838 1636
30e302f8 1637=item Threads
1638
1639Test::More will only be aware of threads if "use threads" has been done
1640I<before> Test::More is loaded. This is ok:
1641
1642 use threads;
1643 use Test::More;
1644
1645This may cause problems:
1646
1647 use Test::More
1648 use threads;
1649
b7f9bbeb 16505.8.1 and above are supported. Anything below that has too many bugs.
1651
d020a79a 1652
30e302f8 1653=item Test::Harness upgrade
3f2ec160 1654
3e887aae 1655no_plan, todo and done_testing() depend on new Test::Harness features
1656and fixes. If you're going to distribute tests that use no_plan or
1657todo your end-users will have to upgrade Test::Harness to the latest
1658one on CPAN. If you avoid no_plan and TODO tests, the stock
1659Test::Harness will work fine.
d020a79a 1660
30e302f8 1661Installing Test::More should also upgrade Test::Harness.
d020a79a 1662
1663=back
3f2ec160 1664
3f2ec160 1665
1666=head1 HISTORY
1667
1668This is a case of convergent evolution with Joshua Pritikin's Test
4bd4e70a 1669module. I was largely unaware of its existence when I'd first
3f2ec160 1670written my own ok() routines. This module exists because I can't
1671figure out how to easily wedge test names into Test's interface (along
1672with a few other problems).
1673
1674The goal here is to have a testing utility that's simple to learn,
1675quick to use and difficult to trip yourself up with while still
1676providing more flexibility than the existing Test.pm. As such, the
1677names of the most common routines are kept tiny, special cases and
1678magic side-effects are kept to a minimum. WYSIWYG.
1679
1680
1681=head1 SEE ALSO
1682
1683L<Test::Simple> if all this confuses you and you just want to write
89c1e84a 1684some tests. You can upgrade to Test::More later (it's forward
3f2ec160 1685compatible).
1686
ccbd73a4 1687L<Test::Harness> is the test runner and output interpreter for Perl.
1688It's the thing that powers C<make test> and where the C<prove> utility
1689comes from.
3f2ec160 1690
ccbd73a4 1691L<Test::Legacy> tests written with Test.pm, the original testing
1692module, do not play well with other testing libraries. Test::Legacy
1693emulates the Test.pm interface and does play well with others.
3f2ec160 1694
30e302f8 1695L<Test::Differences> for more ways to test complex data structures.
1696And it plays well with Test::More.
1697
ccbd73a4 1698L<Test::Class> is like xUnit but more perlish.
30e302f8 1699
1700L<Test::Deep> gives you more powerful complex data structure testing.
1701
4bd4e70a 1702L<Test::Inline> shows the idea of embedded testing.
3f2ec160 1703
30e302f8 1704L<Bundle::Test> installs a whole bunch of useful test modules.
3f2ec160 1705
4bd4e70a 1706
1707=head1 AUTHORS
1708
a9153838 1709Michael G Schwern E<lt>schwern@pobox.comE<gt> with much inspiration
1710from Joshua Pritikin's Test module and lots of help from Barrie
7483b81c 1711Slaymaker, Tony Bowden, blackstar.co.uk, chromatic, Fergal Daly and
1712the perl-qa gang.
1713
1714
1715=head1 BUGS
1716
1717See F<http://rt.cpan.org> to report and view bugs.
4bd4e70a 1718
1719
3e887aae 1720=head1 SOURCE
1721
1722The source code repository for Test::More can be found at
1723F<http://github.com/schwern/test-more/>.
1724
1725
4bd4e70a 1726=head1 COPYRIGHT
1727
ccbd73a4 1728Copyright 2001-2008 by Michael G Schwern E<lt>schwern@pobox.comE<gt>.
4bd4e70a 1729
004caa16 1730This program is free software; you can redistribute it and/or
4bd4e70a 1731modify it under the same terms as Perl itself.
1732
a9153838 1733See F<http://www.perl.com/perl/misc/Artistic.html>
4bd4e70a 1734
3f2ec160 1735=cut
1736
17371;