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