Upgrade to Test-Simple-0.82.
[p5sagit/p5-mst-13.2.git] / lib / Test / Builder.pm
1 package Test::Builder;
2 # $Id: /mirror/googlecode/test-more-trunk/lib/Test/Builder.pm 67223 2008-10-15T03:08:18.888155Z schwern  $
3
4 use 5.006;
5 use strict;
6 use warnings;
7
8 our $VERSION = '0.82';
9 $VERSION = eval $VERSION;    ## no critic (BuiltinFunctions::ProhibitStringyEval)
10
11 # Make Test::Builder thread-safe for ithreads.
12 BEGIN {
13     use Config;
14     # Load threads::shared when threads are turned on.
15     # 5.8.0's threads are so busted we no longer support them.
16     if( $] >= 5.008001 && $Config{useithreads} && $INC{'threads.pm'} ) {
17         require threads::shared;
18
19         # Hack around YET ANOTHER threads::shared bug.  It would
20         # occassionally forget the contents of the variable when sharing it.
21         # So we first copy the data, then share, then put our copy back.
22         *share = sub (\[$@%]) {
23             my $type = ref $_[0];
24             my $data;
25
26             if( $type eq 'HASH' ) {
27                 %$data = %{ $_[0] };
28             }
29             elsif( $type eq 'ARRAY' ) {
30                 @$data = @{ $_[0] };
31             }
32             elsif( $type eq 'SCALAR' ) {
33                 $$data = ${ $_[0] };
34             }
35             else {
36                 die( "Unknown type: " . $type );
37             }
38
39             $_[0] = &threads::shared::share( $_[0] );
40
41             if( $type eq 'HASH' ) {
42                 %{ $_[0] } = %$data;
43             }
44             elsif( $type eq 'ARRAY' ) {
45                 @{ $_[0] } = @$data;
46             }
47             elsif( $type eq 'SCALAR' ) {
48                 ${ $_[0] } = $$data;
49             }
50             else {
51                 die( "Unknown type: " . $type );
52             }
53
54             return $_[0];
55         };
56     }
57     # 5.8.0's threads::shared is busted when threads are off
58     # and earlier Perls just don't have that module at all.
59     else {
60         *share = sub { return $_[0] };
61         *lock  = sub { 0 };
62     }
63 }
64
65 =head1 NAME
66
67 Test::Builder - Backend for building test libraries
68
69 =head1 SYNOPSIS
70
71   package My::Test::Module;
72   use base 'Test::Builder::Module';
73
74   my $CLASS = __PACKAGE__;
75
76   sub ok {
77       my($test, $name) = @_;
78       my $tb = $CLASS->builder;
79
80       $tb->ok($test, $name);
81   }
82
83
84 =head1 DESCRIPTION
85
86 Test::Simple and Test::More have proven to be popular testing modules,
87 but they're not always flexible enough.  Test::Builder provides the a
88 building block upon which to write your own test libraries I<which can
89 work together>.
90
91 =head2 Construction
92
93 =over 4
94
95 =item B<new>
96
97   my $Test = Test::Builder->new;
98
99 Returns a Test::Builder object representing the current state of the
100 test.
101
102 Since you only run one test per program C<new> always returns the same
103 Test::Builder object.  No matter how many times you call new(), you're
104 getting the same object.  This is called a singleton.  This is done so that
105 multiple modules share such global information as the test counter and
106 where test output is going.
107
108 If you want a completely new Test::Builder object different from the
109 singleton, use C<create>.
110
111 =cut
112
113 my $Test = Test::Builder->new;
114
115 sub new {
116     my($class) = shift;
117     $Test ||= $class->create;
118     return $Test;
119 }
120
121 =item B<create>
122
123   my $Test = Test::Builder->create;
124
125 Ok, so there can be more than one Test::Builder object and this is how
126 you get it.  You might use this instead of C<new()> if you're testing
127 a Test::Builder based module, but otherwise you probably want C<new>.
128
129 B<NOTE>: the implementation is not complete.  C<level>, for example, is
130 still shared amongst B<all> Test::Builder objects, even ones created using
131 this method.  Also, the method name may change in the future.
132
133 =cut
134
135 sub create {
136     my $class = shift;
137
138     my $self = bless {}, $class;
139     $self->reset;
140
141     return $self;
142 }
143
144 =item B<reset>
145
146   $Test->reset;
147
148 Reinitializes the Test::Builder singleton to its original state.
149 Mostly useful for tests run in persistent environments where the same
150 test might be run multiple times in the same process.
151
152 =cut
153
154 our $Level;
155
156 sub reset {    ## no critic (Subroutines::ProhibitBuiltinHomonyms)
157     my($self) = @_;
158
159     # We leave this a global because it has to be localized and localizing
160     # hash keys is just asking for pain.  Also, it was documented.
161     $Level = 1;
162
163     $self->{Have_Plan}    = 0;
164     $self->{No_Plan}      = 0;
165     $self->{Original_Pid} = $$;
166
167     share( $self->{Curr_Test} );
168     $self->{Curr_Test} = 0;
169     $self->{Test_Results} = &share( [] );
170
171     $self->{Exported_To}    = undef;
172     $self->{Expected_Tests} = 0;
173
174     $self->{Skip_All} = 0;
175
176     $self->{Use_Nums} = 1;
177
178     $self->{No_Header} = 0;
179     $self->{No_Ending} = 0;
180
181     $self->{Todo}       = undef;
182     $self->{Todo_Stack} = [];
183     $self->{Start_Todo} = 0;
184
185     $self->_dup_stdhandles;
186
187     return;
188 }
189
190 =back
191
192 =head2 Setting up tests
193
194 These methods are for setting up tests and declaring how many there
195 are.  You usually only want to call one of these methods.
196
197 =over 4
198
199 =item B<plan>
200
201   $Test->plan('no_plan');
202   $Test->plan( skip_all => $reason );
203   $Test->plan( tests => $num_tests );
204
205 A convenient way to set up your tests.  Call this and Test::Builder
206 will print the appropriate headers and take the appropriate actions.
207
208 If you call plan(), don't call any of the other methods below.
209
210 =cut
211
212 sub plan {
213     my( $self, $cmd, $arg ) = @_;
214
215     return unless $cmd;
216
217     local $Level = $Level + 1;
218
219     $self->croak("You tried to plan twice")
220       if $self->{Have_Plan};
221
222     if( $cmd eq 'no_plan' ) {
223         $self->carp("no_plan takes no arguments") if $arg;
224         $self->no_plan;
225     }
226     elsif( $cmd eq 'skip_all' ) {
227         return $self->skip_all($arg);
228     }
229     elsif( $cmd eq 'tests' ) {
230         if($arg) {
231             local $Level = $Level + 1;
232             return $self->expected_tests($arg);
233         }
234         elsif( !defined $arg ) {
235             $self->croak("Got an undefined number of tests");
236         }
237         else {
238             $self->croak("You said to run 0 tests");
239         }
240     }
241     else {
242         my @args = grep { defined } ( $cmd, $arg );
243         $self->croak("plan() doesn't understand @args");
244     }
245
246     return 1;
247 }
248
249 =item B<expected_tests>
250
251     my $max = $Test->expected_tests;
252     $Test->expected_tests($max);
253
254 Gets/sets the # of tests we expect this test to run and prints out
255 the appropriate headers.
256
257 =cut
258
259 sub expected_tests {
260     my $self = shift;
261     my($max) = @_;
262
263     if(@_) {
264         $self->croak("Number of tests must be a positive integer.  You gave it '$max'")
265           unless $max =~ /^\+?\d+$/;
266
267         $self->{Expected_Tests} = $max;
268         $self->{Have_Plan}      = 1;
269
270         $self->_print("1..$max\n") unless $self->no_header;
271     }
272     return $self->{Expected_Tests};
273 }
274
275 =item B<no_plan>
276
277   $Test->no_plan;
278
279 Declares that this test will run an indeterminate # of tests.
280
281 =cut
282
283 sub no_plan {
284     my $self = shift;
285
286     $self->{No_Plan}   = 1;
287     $self->{Have_Plan} = 1;
288
289     return 1;
290 }
291
292 =item B<has_plan>
293
294   $plan = $Test->has_plan
295
296 Find out whether a plan has been defined. $plan is either C<undef> (no plan has been set), C<no_plan> (indeterminate # of tests) or an integer (the number of expected tests).
297
298 =cut
299
300 sub has_plan {
301     my $self = shift;
302
303     return( $self->{Expected_Tests} ) if $self->{Expected_Tests};
304     return('no_plan') if $self->{No_Plan};
305     return(undef);
306 }
307
308 =item B<skip_all>
309
310   $Test->skip_all;
311   $Test->skip_all($reason);
312
313 Skips all the tests, using the given $reason.  Exits immediately with 0.
314
315 =cut
316
317 sub skip_all {
318     my( $self, $reason ) = @_;
319
320     my $out = "1..0";
321     $out .= " # Skip $reason" if $reason;
322     $out .= "\n";
323
324     $self->{Skip_All} = 1;
325
326     $self->_print($out) unless $self->no_header;
327     exit(0);
328 }
329
330 =item B<exported_to>
331
332   my $pack = $Test->exported_to;
333   $Test->exported_to($pack);
334
335 Tells Test::Builder what package you exported your functions to.
336
337 This method isn't terribly useful since modules which share the same
338 Test::Builder object might get exported to different packages and only
339 the last one will be honored.
340
341 =cut
342
343 sub exported_to {
344     my( $self, $pack ) = @_;
345
346     if( defined $pack ) {
347         $self->{Exported_To} = $pack;
348     }
349     return $self->{Exported_To};
350 }
351
352 =back
353
354 =head2 Running tests
355
356 These actually run the tests, analogous to the functions in Test::More.
357
358 They all return true if the test passed, false if the test failed.
359
360 $name is always optional.
361
362 =over 4
363
364 =item B<ok>
365
366   $Test->ok($test, $name);
367
368 Your basic test.  Pass if $test is true, fail if $test is false.  Just
369 like Test::Simple's ok().
370
371 =cut
372
373 sub ok {
374     my( $self, $test, $name ) = @_;
375
376     # $test might contain an object which we don't want to accidentally
377     # store, so we turn it into a boolean.
378     $test = $test ? 1 : 0;
379
380     $self->_plan_check;
381
382     lock $self->{Curr_Test};
383     $self->{Curr_Test}++;
384
385     # In case $name is a string overloaded object, force it to stringify.
386     $self->_unoverload_str( \$name );
387
388     $self->diag(<<"ERR") if defined $name and $name =~ /^[\d\s]+$/;
389     You named your test '$name'.  You shouldn't use numbers for your test names.
390     Very confusing.
391 ERR
392
393     # Capture the value of $TODO for the rest of this ok() call
394     # so it can more easily be found by other routines.
395     my $todo    = $self->todo();
396     my $in_todo = $self->in_todo;
397     local $self->{Todo} = $todo if $in_todo;
398
399     $self->_unoverload_str( \$todo );
400
401     my $out;
402     my $result = &share( {} );
403
404     unless($test) {
405         $out .= "not ";
406         @$result{ 'ok', 'actual_ok' } = ( ( $self->in_todo ? 1 : 0 ), 0 );
407     }
408     else {
409         @$result{ 'ok', 'actual_ok' } = ( 1, $test );
410     }
411
412     $out .= "ok";
413     $out .= " $self->{Curr_Test}" if $self->use_numbers;
414
415     if( defined $name ) {
416         $name =~ s|#|\\#|g;    # # in a name can confuse Test::Harness.
417         $out .= " - $name";
418         $result->{name} = $name;
419     }
420     else {
421         $result->{name} = '';
422     }
423
424     if( $self->in_todo ) {
425         $out .= " # TODO $todo";
426         $result->{reason} = $todo;
427         $result->{type}   = 'todo';
428     }
429     else {
430         $result->{reason} = '';
431         $result->{type}   = '';
432     }
433
434     $self->{Test_Results}[ $self->{Curr_Test} - 1 ] = $result;
435     $out .= "\n";
436
437     $self->_print($out);
438
439     unless($test) {
440         my $msg = $self->in_todo ? "Failed (TODO)" : "Failed";
441         $self->_print_to_fh( $self->_diag_fh, "\n" ) if $ENV{HARNESS_ACTIVE};
442
443         my( undef, $file, $line ) = $self->caller;
444         if( defined $name ) {
445             $self->diag(qq[  $msg test '$name'\n]);
446             $self->diag(qq[  at $file line $line.\n]);
447         }
448         else {
449             $self->diag(qq[  $msg test at $file line $line.\n]);
450         }
451     }
452
453     return $test ? 1 : 0;
454 }
455
456 sub _unoverload {
457     my $self = shift;
458     my $type = shift;
459
460     $self->_try( sub { require overload } ) || return;
461
462     foreach my $thing (@_) {
463         if( $self->_is_object($$thing) ) {
464             if( my $string_meth = overload::Method( $$thing, $type ) ) {
465                 $$thing = $$thing->$string_meth();
466             }
467         }
468     }
469
470     return;
471 }
472
473 sub _is_object {
474     my( $self, $thing ) = @_;
475
476     return $self->_try( sub { ref $thing && $thing->isa('UNIVERSAL') } ) ? 1 : 0;
477 }
478
479 sub _unoverload_str {
480     my $self = shift;
481
482     return $self->_unoverload( q[""], @_ );
483 }
484
485 sub _unoverload_num {
486     my $self = shift;
487
488     $self->_unoverload( '0+', @_ );
489
490     for my $val (@_) {
491         next unless $self->_is_dualvar($$val);
492         $$val = $$val + 0;
493     }
494
495     return;
496 }
497
498 # This is a hack to detect a dualvar such as $!
499 sub _is_dualvar {
500     my( $self, $val ) = @_;
501
502     no warnings 'numeric';
503     my $numval = $val + 0;
504     return $numval != 0 and $numval ne $val ? 1 : 0;
505 }
506
507 =item B<is_eq>
508
509   $Test->is_eq($got, $expected, $name);
510
511 Like Test::More's is().  Checks if $got eq $expected.  This is the
512 string version.
513
514 =item B<is_num>
515
516   $Test->is_num($got, $expected, $name);
517
518 Like Test::More's is().  Checks if $got == $expected.  This is the
519 numeric version.
520
521 =cut
522
523 sub is_eq {
524     my( $self, $got, $expect, $name ) = @_;
525     local $Level = $Level + 1;
526
527     $self->_unoverload_str( \$got, \$expect );
528
529     if( !defined $got || !defined $expect ) {
530         # undef only matches undef and nothing else
531         my $test = !defined $got && !defined $expect;
532
533         $self->ok( $test, $name );
534         $self->_is_diag( $got, 'eq', $expect ) unless $test;
535         return $test;
536     }
537
538     return $self->cmp_ok( $got, 'eq', $expect, $name );
539 }
540
541 sub is_num {
542     my( $self, $got, $expect, $name ) = @_;
543     local $Level = $Level + 1;
544
545     $self->_unoverload_num( \$got, \$expect );
546
547     if( !defined $got || !defined $expect ) {
548         # undef only matches undef and nothing else
549         my $test = !defined $got && !defined $expect;
550
551         $self->ok( $test, $name );
552         $self->_is_diag( $got, '==', $expect ) unless $test;
553         return $test;
554     }
555
556     return $self->cmp_ok( $got, '==', $expect, $name );
557 }
558
559 sub _diag_fmt {
560     my( $self, $type, $val ) = @_;
561
562     if( defined $$val ) {
563         if( $type eq 'eq' or $type eq 'ne' ) {
564             # quote and force string context
565             $$val = "'$$val'";
566         }
567         else {
568             # force numeric context
569             $self->_unoverload_num($val);
570         }
571     }
572     else {
573         $$val = 'undef';
574     }
575
576     return;
577 }
578
579 sub _is_diag {
580     my( $self, $got, $type, $expect ) = @_;
581
582     $self->_diag_fmt( $type, $_ ) for \$got, \$expect;
583
584     local $Level = $Level + 1;
585     return $self->diag(<<"DIAGNOSTIC");
586          got: $got
587     expected: $expect
588 DIAGNOSTIC
589
590 }
591
592 sub _isnt_diag {
593     my( $self, $got, $type ) = @_;
594
595     $self->_diag_fmt( $type, \$got );
596
597     local $Level = $Level + 1;
598     return $self->diag(<<"DIAGNOSTIC");
599          got: $got
600     expected: anything else
601 DIAGNOSTIC
602 }
603
604 =item B<isnt_eq>
605
606   $Test->isnt_eq($got, $dont_expect, $name);
607
608 Like Test::More's isnt().  Checks if $got ne $dont_expect.  This is
609 the string version.
610
611 =item B<isnt_num>
612
613   $Test->isnt_num($got, $dont_expect, $name);
614
615 Like Test::More's isnt().  Checks if $got ne $dont_expect.  This is
616 the numeric version.
617
618 =cut
619
620 sub isnt_eq {
621     my( $self, $got, $dont_expect, $name ) = @_;
622     local $Level = $Level + 1;
623
624     if( !defined $got || !defined $dont_expect ) {
625         # undef only matches undef and nothing else
626         my $test = defined $got || defined $dont_expect;
627
628         $self->ok( $test, $name );
629         $self->_isnt_diag( $got, 'ne' ) unless $test;
630         return $test;
631     }
632
633     return $self->cmp_ok( $got, 'ne', $dont_expect, $name );
634 }
635
636 sub isnt_num {
637     my( $self, $got, $dont_expect, $name ) = @_;
638     local $Level = $Level + 1;
639
640     if( !defined $got || !defined $dont_expect ) {
641         # undef only matches undef and nothing else
642         my $test = defined $got || defined $dont_expect;
643
644         $self->ok( $test, $name );
645         $self->_isnt_diag( $got, '!=' ) unless $test;
646         return $test;
647     }
648
649     return $self->cmp_ok( $got, '!=', $dont_expect, $name );
650 }
651
652 =item B<like>
653
654   $Test->like($this, qr/$regex/, $name);
655   $Test->like($this, '/$regex/', $name);
656
657 Like Test::More's like().  Checks if $this matches the given $regex.
658
659 You'll want to avoid qr// if you want your tests to work before 5.005.
660
661 =item B<unlike>
662
663   $Test->unlike($this, qr/$regex/, $name);
664   $Test->unlike($this, '/$regex/', $name);
665
666 Like Test::More's unlike().  Checks if $this B<does not match> the
667 given $regex.
668
669 =cut
670
671 sub like {
672     my( $self, $this, $regex, $name ) = @_;
673
674     local $Level = $Level + 1;
675     return $self->_regex_ok( $this, $regex, '=~', $name );
676 }
677
678 sub unlike {
679     my( $self, $this, $regex, $name ) = @_;
680
681     local $Level = $Level + 1;
682     return $self->_regex_ok( $this, $regex, '!~', $name );
683 }
684
685 =item B<cmp_ok>
686
687   $Test->cmp_ok($this, $type, $that, $name);
688
689 Works just like Test::More's cmp_ok().
690
691     $Test->cmp_ok($big_num, '!=', $other_big_num);
692
693 =cut
694
695 my %numeric_cmps = map { ( $_, 1 ) } ( "<", "<=", ">", ">=", "==", "!=", "<=>" );
696
697 sub cmp_ok {
698     my( $self, $got, $type, $expect, $name ) = @_;
699
700     # Treat overloaded objects as numbers if we're asked to do a
701     # numeric comparison.
702     my $unoverload
703       = $numeric_cmps{$type}
704       ? '_unoverload_num'
705       : '_unoverload_str';
706
707     $self->$unoverload( \$got, \$expect );
708
709     my $test;
710     {
711         ## no critic (BuiltinFunctions::ProhibitStringyEval)
712
713         local( $@, $!, $SIG{__DIE__} );    # isolate eval
714
715         my $code = $self->_caller_context;
716
717         # Yes, it has to look like this or 5.4.5 won't see the #line
718         # directive.
719         # Don't ask me, man, I just work here.
720         $test = eval "
721 $code" . "\$got $type \$expect;";
722
723     }
724     local $Level = $Level + 1;
725     my $ok = $self->ok( $test, $name );
726
727     unless($ok) {
728         if( $type =~ /^(eq|==)$/ ) {
729             $self->_is_diag( $got, $type, $expect );
730         }
731         elsif( $type =~ /^(ne|!=)$/ ) {
732             $self->_isnt_diag( $got, $type );
733         }
734         else {
735             $self->_cmp_diag( $got, $type, $expect );
736         }
737     }
738     return $ok;
739 }
740
741 sub _cmp_diag {
742     my( $self, $got, $type, $expect ) = @_;
743
744     $got    = defined $got    ? "'$got'"    : 'undef';
745     $expect = defined $expect ? "'$expect'" : 'undef';
746
747     local $Level = $Level + 1;
748     return $self->diag(<<"DIAGNOSTIC");
749     $got
750         $type
751     $expect
752 DIAGNOSTIC
753 }
754
755 sub _caller_context {
756     my $self = shift;
757
758     my( $pack, $file, $line ) = $self->caller(1);
759
760     my $code = '';
761     $code .= "#line $line $file\n" if defined $file and defined $line;
762
763     return $code;
764 }
765
766 =back
767
768
769 =head2 Other Testing Methods
770
771 These are methods which are used in the course of writing a test but are not themselves tests.
772
773 =over 4
774
775 =item B<BAIL_OUT>
776
777     $Test->BAIL_OUT($reason);
778
779 Indicates to the Test::Harness that things are going so badly all
780 testing should terminate.  This includes running any additional test
781 scripts.
782
783 It will exit with 255.
784
785 =cut
786
787 sub BAIL_OUT {
788     my( $self, $reason ) = @_;
789
790     $self->{Bailed_Out} = 1;
791     $self->_print("Bail out!  $reason");
792     exit 255;
793 }
794
795 =for deprecated
796 BAIL_OUT() used to be BAILOUT()
797
798 =cut
799
800 *BAILOUT = \&BAIL_OUT;
801
802 =item B<skip>
803
804     $Test->skip;
805     $Test->skip($why);
806
807 Skips the current test, reporting $why.
808
809 =cut
810
811 sub skip {
812     my( $self, $why ) = @_;
813     $why ||= '';
814     $self->_unoverload_str( \$why );
815
816     $self->_plan_check;
817
818     lock( $self->{Curr_Test} );
819     $self->{Curr_Test}++;
820
821     $self->{Test_Results}[ $self->{Curr_Test} - 1 ] = &share(
822         {
823             'ok'      => 1,
824             actual_ok => 1,
825             name      => '',
826             type      => 'skip',
827             reason    => $why,
828         }
829     );
830
831     my $out = "ok";
832     $out .= " $self->{Curr_Test}" if $self->use_numbers;
833     $out .= " # skip";
834     $out .= " $why"               if length $why;
835     $out .= "\n";
836
837     $self->_print($out);
838
839     return 1;
840 }
841
842 =item B<todo_skip>
843
844   $Test->todo_skip;
845   $Test->todo_skip($why);
846
847 Like skip(), only it will declare the test as failing and TODO.  Similar
848 to
849
850     print "not ok $tnum # TODO $why\n";
851
852 =cut
853
854 sub todo_skip {
855     my( $self, $why ) = @_;
856     $why ||= '';
857
858     $self->_plan_check;
859
860     lock( $self->{Curr_Test} );
861     $self->{Curr_Test}++;
862
863     $self->{Test_Results}[ $self->{Curr_Test} - 1 ] = &share(
864         {
865             'ok'      => 1,
866             actual_ok => 0,
867             name      => '',
868             type      => 'todo_skip',
869             reason    => $why,
870         }
871     );
872
873     my $out = "not ok";
874     $out .= " $self->{Curr_Test}" if $self->use_numbers;
875     $out .= " # TODO & SKIP $why\n";
876
877     $self->_print($out);
878
879     return 1;
880 }
881
882 =begin _unimplemented
883
884 =item B<skip_rest>
885
886   $Test->skip_rest;
887   $Test->skip_rest($reason);
888
889 Like skip(), only it skips all the rest of the tests you plan to run
890 and terminates the test.
891
892 If you're running under no_plan, it skips once and terminates the
893 test.
894
895 =end _unimplemented
896
897 =back
898
899
900 =head2 Test building utility methods
901
902 These methods are useful when writing your own test methods.
903
904 =over 4
905
906 =item B<maybe_regex>
907
908   $Test->maybe_regex(qr/$regex/);
909   $Test->maybe_regex('/$regex/');
910
911 Convenience method for building testing functions that take regular
912 expressions as arguments, but need to work before perl 5.005.
913
914 Takes a quoted regular expression produced by qr//, or a string
915 representing a regular expression.
916
917 Returns a Perl value which may be used instead of the corresponding
918 regular expression, or undef if its argument is not recognised.
919
920 For example, a version of like(), sans the useful diagnostic messages,
921 could be written as:
922
923   sub laconic_like {
924       my ($self, $this, $regex, $name) = @_;
925       my $usable_regex = $self->maybe_regex($regex);
926       die "expecting regex, found '$regex'\n"
927           unless $usable_regex;
928       $self->ok($this =~ m/$usable_regex/, $name);
929   }
930
931 =cut
932
933 sub maybe_regex {
934     my( $self, $regex ) = @_;
935     my $usable_regex = undef;
936
937     return $usable_regex unless defined $regex;
938
939     my( $re, $opts );
940
941     # Check for qr/foo/
942     if( _is_qr($regex) ) {
943         $usable_regex = $regex;
944     }
945     # Check for '/foo/' or 'm,foo,'
946     elsif(( $re, $opts )        = $regex =~ m{^ /(.*)/ (\w*) $ }sx              or
947           ( undef, $re, $opts ) = $regex =~ m,^ m([^\w\s]) (.+) \1 (\w*) $,sx
948     )
949     {
950         $usable_regex = length $opts ? "(?$opts)$re" : $re;
951     }
952
953     return $usable_regex;
954 }
955
956 sub _is_qr {
957     my $regex = shift;
958
959     # is_regexp() checks for regexes in a robust manner, say if they're
960     # blessed.
961     return re::is_regexp($regex) if defined &re::is_regexp;
962     return ref $regex eq 'Regexp';
963 }
964
965 sub _regex_ok {
966     my( $self, $this, $regex, $cmp, $name ) = @_;
967
968     my $ok           = 0;
969     my $usable_regex = $self->maybe_regex($regex);
970     unless( defined $usable_regex ) {
971         local $Level = $Level + 1;
972         $ok = $self->ok( 0, $name );
973         $self->diag("    '$regex' doesn't look much like a regex to me.");
974         return $ok;
975     }
976
977     {
978         ## no critic (BuiltinFunctions::ProhibitStringyEval)
979
980         my $test;
981         my $code = $self->_caller_context;
982
983         local( $@, $!, $SIG{__DIE__} );    # isolate eval
984
985         # Yes, it has to look like this or 5.4.5 won't see the #line
986         # directive.
987         # Don't ask me, man, I just work here.
988         $test = eval "
989 $code" . q{$test = $this =~ /$usable_regex/ ? 1 : 0};
990
991         $test = !$test if $cmp eq '!~';
992
993         local $Level = $Level + 1;
994         $ok = $self->ok( $test, $name );
995     }
996
997     unless($ok) {
998         $this = defined $this ? "'$this'" : 'undef';
999         my $match = $cmp eq '=~' ? "doesn't match" : "matches";
1000
1001         local $Level = $Level + 1;
1002         $self->diag( sprintf <<'DIAGNOSTIC', $this, $match, $regex );
1003                   %s
1004     %13s '%s'
1005 DIAGNOSTIC
1006
1007     }
1008
1009     return $ok;
1010 }
1011
1012 # I'm not ready to publish this.  It doesn't deal with array return
1013 # values from the code or context.
1014
1015 =begin private
1016
1017 =item B<_try>
1018
1019     my $return_from_code          = $Test->try(sub { code });
1020     my($return_from_code, $error) = $Test->try(sub { code });
1021
1022 Works like eval BLOCK except it ensures it has no effect on the rest
1023 of the test (ie. $@ is not set) nor is effected by outside
1024 interference (ie. $SIG{__DIE__}) and works around some quirks in older
1025 Perls.
1026
1027 $error is what would normally be in $@.
1028
1029 It is suggested you use this in place of eval BLOCK.
1030
1031 =cut
1032
1033 sub _try {
1034     my( $self, $code ) = @_;
1035
1036     local $!;               # eval can mess up $!
1037     local $@;               # don't set $@ in the test
1038     local $SIG{__DIE__};    # don't trip an outside DIE handler.
1039     my $return = eval { $code->() };
1040
1041     return wantarray ? ( $return, $@ ) : $return;
1042 }
1043
1044 =end private
1045
1046
1047 =item B<is_fh>
1048
1049     my $is_fh = $Test->is_fh($thing);
1050
1051 Determines if the given $thing can be used as a filehandle.
1052
1053 =cut
1054
1055 sub is_fh {
1056     my $self     = shift;
1057     my $maybe_fh = shift;
1058     return 0 unless defined $maybe_fh;
1059
1060     return 1 if ref $maybe_fh  eq 'GLOB';    # its a glob ref
1061     return 1 if ref \$maybe_fh eq 'GLOB';    # its a glob
1062
1063     return eval { $maybe_fh->isa("IO::Handle") } ||
1064            # 5.5.4's tied() and can() doesn't like getting undef
1065            eval { ( tied($maybe_fh) || '' )->can('TIEHANDLE') };
1066 }
1067
1068 =back
1069
1070
1071 =head2 Test style
1072
1073
1074 =over 4
1075
1076 =item B<level>
1077
1078     $Test->level($how_high);
1079
1080 How far up the call stack should $Test look when reporting where the
1081 test failed.
1082
1083 Defaults to 1.
1084
1085 Setting L<$Test::Builder::Level> overrides.  This is typically useful
1086 localized:
1087
1088     sub my_ok {
1089         my $test = shift;
1090
1091         local $Test::Builder::Level = $Test::Builder::Level + 1;
1092         $TB->ok($test);
1093     }
1094
1095 To be polite to other functions wrapping your own you usually want to increment C<$Level> rather than set it to a constant.
1096
1097 =cut
1098
1099 sub level {
1100     my( $self, $level ) = @_;
1101
1102     if( defined $level ) {
1103         $Level = $level;
1104     }
1105     return $Level;
1106 }
1107
1108 =item B<use_numbers>
1109
1110     $Test->use_numbers($on_or_off);
1111
1112 Whether or not the test should output numbers.  That is, this if true:
1113
1114   ok 1
1115   ok 2
1116   ok 3
1117
1118 or this if false
1119
1120   ok
1121   ok
1122   ok
1123
1124 Most useful when you can't depend on the test output order, such as
1125 when threads or forking is involved.
1126
1127 Defaults to on.
1128
1129 =cut
1130
1131 sub use_numbers {
1132     my( $self, $use_nums ) = @_;
1133
1134     if( defined $use_nums ) {
1135         $self->{Use_Nums} = $use_nums;
1136     }
1137     return $self->{Use_Nums};
1138 }
1139
1140 =item B<no_diag>
1141
1142     $Test->no_diag($no_diag);
1143
1144 If set true no diagnostics will be printed.  This includes calls to
1145 diag().
1146
1147 =item B<no_ending>
1148
1149     $Test->no_ending($no_ending);
1150
1151 Normally, Test::Builder does some extra diagnostics when the test
1152 ends.  It also changes the exit code as described below.
1153
1154 If this is true, none of that will be done.
1155
1156 =item B<no_header>
1157
1158     $Test->no_header($no_header);
1159
1160 If set to true, no "1..N" header will be printed.
1161
1162 =cut
1163
1164 foreach my $attribute (qw(No_Header No_Ending No_Diag)) {
1165     my $method = lc $attribute;
1166
1167     my $code = sub {
1168         my( $self, $no ) = @_;
1169
1170         if( defined $no ) {
1171             $self->{$attribute} = $no;
1172         }
1173         return $self->{$attribute};
1174     };
1175
1176     no strict 'refs';    ## no critic
1177     *{ __PACKAGE__ . '::' . $method } = $code;
1178 }
1179
1180 =back
1181
1182 =head2 Output
1183
1184 Controlling where the test output goes.
1185
1186 It's ok for your test to change where STDOUT and STDERR point to,
1187 Test::Builder's default output settings will not be affected.
1188
1189 =over 4
1190
1191 =item B<diag>
1192
1193     $Test->diag(@msgs);
1194
1195 Prints out the given @msgs.  Like C<print>, arguments are simply
1196 appended together.
1197
1198 Normally, it uses the failure_output() handle, but if this is for a
1199 TODO test, the todo_output() handle is used.
1200
1201 Output will be indented and marked with a # so as not to interfere
1202 with test output.  A newline will be put on the end if there isn't one
1203 already.
1204
1205 We encourage using this rather than calling print directly.
1206
1207 Returns false.  Why?  Because diag() is often used in conjunction with
1208 a failing test (C<ok() || diag()>) it "passes through" the failure.
1209
1210     return ok(...) || diag(...);
1211
1212 =for blame transfer
1213 Mark Fowler <mark@twoshortplanks.com>
1214
1215 =cut
1216
1217 sub diag {
1218     my $self = shift;
1219
1220     $self->_print_comment( $self->_diag_fh, @_ );
1221 }
1222
1223 =item B<note>
1224
1225     $Test->note(@msgs);
1226
1227 Like diag(), but it prints to the C<output()> handle so it will not
1228 normally be seen by the user except in verbose mode.
1229
1230 =cut
1231
1232 sub note {
1233     my $self = shift;
1234
1235     $self->_print_comment( $self->output, @_ );
1236 }
1237
1238 sub _diag_fh {
1239     my $self = shift;
1240
1241     local $Level = $Level + 1;
1242     return $self->in_todo ? $self->todo_output : $self->failure_output;
1243 }
1244
1245 sub _print_comment {
1246     my( $self, $fh, @msgs ) = @_;
1247
1248     return if $self->no_diag;
1249     return unless @msgs;
1250
1251     # Prevent printing headers when compiling (i.e. -c)
1252     return if $^C;
1253
1254     # Smash args together like print does.
1255     # Convert undef to 'undef' so its readable.
1256     my $msg = join '', map { defined($_) ? $_ : 'undef' } @msgs;
1257
1258     # Escape the beginning, _print will take care of the rest.
1259     $msg =~ s/^/# /;
1260
1261     local $Level = $Level + 1;
1262     $self->_print_to_fh( $fh, $msg );
1263
1264     return 0;
1265 }
1266
1267 =item B<explain>
1268
1269     my @dump = $Test->explain(@msgs);
1270
1271 Will dump the contents of any references in a human readable format.
1272 Handy for things like...
1273
1274     is_deeply($have, $want) || diag explain $have;
1275
1276 or
1277
1278     is_deeply($have, $want) || note explain $have;
1279
1280 =cut
1281
1282 sub explain {
1283     my $self = shift;
1284
1285     return map {
1286         ref $_
1287           ? do {
1288             require Data::Dumper;
1289
1290             my $dumper = Data::Dumper->new( [$_] );
1291             $dumper->Indent(1)->Terse(1);
1292             $dumper->Sortkeys(1) if $dumper->can("Sortkeys");
1293             $dumper->Dump;
1294           }
1295           : $_
1296     } @_;
1297 }
1298
1299 =begin _private
1300
1301 =item B<_print>
1302
1303     $Test->_print(@msgs);
1304
1305 Prints to the output() filehandle.
1306
1307 =end _private
1308
1309 =cut
1310
1311 sub _print {
1312     my $self = shift;
1313     return $self->_print_to_fh( $self->output, @_ );
1314 }
1315
1316 sub _print_to_fh {
1317     my( $self, $fh, @msgs ) = @_;
1318
1319     # Prevent printing headers when only compiling.  Mostly for when
1320     # tests are deparsed with B::Deparse
1321     return if $^C;
1322
1323     my $msg = join '', @msgs;
1324
1325     local( $\, $", $, ) = ( undef, ' ', '' );
1326
1327     # Escape each line after the first with a # so we don't
1328     # confuse Test::Harness.
1329     $msg =~ s/\n(.)/\n# $1/sg;
1330
1331     # Stick a newline on the end if it needs it.
1332     $msg .= "\n" unless $msg =~ /\n\Z/;
1333
1334     return print $fh $msg;
1335 }
1336
1337 =item B<output>
1338
1339     $Test->output($fh);
1340     $Test->output($file);
1341
1342 Where normal "ok/not ok" test output should go.
1343
1344 Defaults to STDOUT.
1345
1346 =item B<failure_output>
1347
1348     $Test->failure_output($fh);
1349     $Test->failure_output($file);
1350
1351 Where diagnostic output on test failures and diag() should go.
1352
1353 Defaults to STDERR.
1354
1355 =item B<todo_output>
1356
1357     $Test->todo_output($fh);
1358     $Test->todo_output($file);
1359
1360 Where diagnostics about todo test failures and diag() should go.
1361
1362 Defaults to STDOUT.
1363
1364 =cut
1365
1366 sub output {
1367     my( $self, $fh ) = @_;
1368
1369     if( defined $fh ) {
1370         $self->{Out_FH} = $self->_new_fh($fh);
1371     }
1372     return $self->{Out_FH};
1373 }
1374
1375 sub failure_output {
1376     my( $self, $fh ) = @_;
1377
1378     if( defined $fh ) {
1379         $self->{Fail_FH} = $self->_new_fh($fh);
1380     }
1381     return $self->{Fail_FH};
1382 }
1383
1384 sub todo_output {
1385     my( $self, $fh ) = @_;
1386
1387     if( defined $fh ) {
1388         $self->{Todo_FH} = $self->_new_fh($fh);
1389     }
1390     return $self->{Todo_FH};
1391 }
1392
1393 sub _new_fh {
1394     my $self = shift;
1395     my($file_or_fh) = shift;
1396
1397     my $fh;
1398     if( $self->is_fh($file_or_fh) ) {
1399         $fh = $file_or_fh;
1400     }
1401     else {
1402         open $fh, ">", $file_or_fh
1403           or $self->croak("Can't open test output log $file_or_fh: $!");
1404         _autoflush($fh);
1405     }
1406
1407     return $fh;
1408 }
1409
1410 sub _autoflush {
1411     my($fh) = shift;
1412     my $old_fh = select $fh;
1413     $| = 1;
1414     select $old_fh;
1415
1416     return;
1417 }
1418
1419 my( $Testout, $Testerr );
1420
1421 sub _dup_stdhandles {
1422     my $self = shift;
1423
1424     $self->_open_testhandles;
1425
1426     # Set everything to unbuffered else plain prints to STDOUT will
1427     # come out in the wrong order from our own prints.
1428     _autoflush($Testout);
1429     _autoflush( \*STDOUT );
1430     _autoflush($Testerr);
1431     _autoflush( \*STDERR );
1432
1433     $self->reset_outputs;
1434
1435     return;
1436 }
1437
1438 my $Opened_Testhandles = 0;
1439
1440 sub _open_testhandles {
1441     my $self = shift;
1442
1443     return if $Opened_Testhandles;
1444
1445     # We dup STDOUT and STDERR so people can change them in their
1446     # test suites while still getting normal test output.
1447     open( $Testout, ">&STDOUT" ) or die "Can't dup STDOUT:  $!";
1448     open( $Testerr, ">&STDERR" ) or die "Can't dup STDERR:  $!";
1449
1450     #    $self->_copy_io_layers( \*STDOUT, $Testout );
1451     #    $self->_copy_io_layers( \*STDERR, $Testerr );
1452
1453     $Opened_Testhandles = 1;
1454
1455     return;
1456 }
1457
1458 sub _copy_io_layers {
1459     my( $self, $src, $dst ) = @_;
1460
1461     $self->_try(
1462         sub {
1463             require PerlIO;
1464             my @src_layers = PerlIO::get_layers($src);
1465
1466             binmode $dst, join " ", map ":$_", @src_layers if @src_layers;
1467         }
1468     );
1469
1470     return;
1471 }
1472
1473 =item reset_outputs
1474
1475   $tb->reset_outputs;
1476
1477 Resets all the output filehandles back to their defaults.
1478
1479 =cut
1480
1481 sub reset_outputs {
1482     my $self = shift;
1483
1484     $self->output        ($Testout);
1485     $self->failure_output($Testerr);
1486     $self->todo_output   ($Testout);
1487
1488     return;
1489 }
1490
1491 =item carp
1492
1493   $tb->carp(@message);
1494
1495 Warns with C<@message> but the message will appear to come from the
1496 point where the original test function was called (C<$tb->caller>).
1497
1498 =item croak
1499
1500   $tb->croak(@message);
1501
1502 Dies with C<@message> but the message will appear to come from the
1503 point where the original test function was called (C<$tb->caller>).
1504
1505 =cut
1506
1507 sub _message_at_caller {
1508     my $self = shift;
1509
1510     local $Level = $Level + 1;
1511     my( $pack, $file, $line ) = $self->caller;
1512     return join( "", @_ ) . " at $file line $line.\n";
1513 }
1514
1515 sub carp {
1516     my $self = shift;
1517     return warn $self->_message_at_caller(@_);
1518 }
1519
1520 sub croak {
1521     my $self = shift;
1522     return die $self->_message_at_caller(@_);
1523 }
1524
1525 sub _plan_check {
1526     my $self = shift;
1527
1528     unless( $self->{Have_Plan} ) {
1529         local $Level = $Level + 2;
1530         $self->croak("You tried to run a test without a plan");
1531     }
1532
1533     return;
1534 }
1535
1536 =back
1537
1538
1539 =head2 Test Status and Info
1540
1541 =over 4
1542
1543 =item B<current_test>
1544
1545     my $curr_test = $Test->current_test;
1546     $Test->current_test($num);
1547
1548 Gets/sets the current test number we're on.  You usually shouldn't
1549 have to set this.
1550
1551 If set forward, the details of the missing tests are filled in as 'unknown'.
1552 if set backward, the details of the intervening tests are deleted.  You
1553 can erase history if you really want to.
1554
1555 =cut
1556
1557 sub current_test {
1558     my( $self, $num ) = @_;
1559
1560     lock( $self->{Curr_Test} );
1561     if( defined $num ) {
1562         $self->croak("Can't change the current test number without a plan!")
1563           unless $self->{Have_Plan};
1564
1565         $self->{Curr_Test} = $num;
1566
1567         # If the test counter is being pushed forward fill in the details.
1568         my $test_results = $self->{Test_Results};
1569         if( $num > @$test_results ) {
1570             my $start = @$test_results ? @$test_results : 0;
1571             for( $start .. $num - 1 ) {
1572                 $test_results->[$_] = &share(
1573                     {
1574                         'ok'      => 1,
1575                         actual_ok => undef,
1576                         reason    => 'incrementing test number',
1577                         type      => 'unknown',
1578                         name      => undef
1579                     }
1580                 );
1581             }
1582         }
1583         # If backward, wipe history.  Its their funeral.
1584         elsif( $num < @$test_results ) {
1585             $#{$test_results} = $num - 1;
1586         }
1587     }
1588     return $self->{Curr_Test};
1589 }
1590
1591 =item B<summary>
1592
1593     my @tests = $Test->summary;
1594
1595 A simple summary of the tests so far.  True for pass, false for fail.
1596 This is a logical pass/fail, so todos are passes.
1597
1598 Of course, test #1 is $tests[0], etc...
1599
1600 =cut
1601
1602 sub summary {
1603     my($self) = shift;
1604
1605     return map { $_->{'ok'} } @{ $self->{Test_Results} };
1606 }
1607
1608 =item B<details>
1609
1610     my @tests = $Test->details;
1611
1612 Like summary(), but with a lot more detail.
1613
1614     $tests[$test_num - 1] = 
1615             { 'ok'       => is the test considered a pass?
1616               actual_ok  => did it literally say 'ok'?
1617               name       => name of the test (if any)
1618               type       => type of test (if any, see below).
1619               reason     => reason for the above (if any)
1620             };
1621
1622 'ok' is true if Test::Harness will consider the test to be a pass.
1623
1624 'actual_ok' is a reflection of whether or not the test literally
1625 printed 'ok' or 'not ok'.  This is for examining the result of 'todo'
1626 tests.  
1627
1628 'name' is the name of the test.
1629
1630 'type' indicates if it was a special test.  Normal tests have a type
1631 of ''.  Type can be one of the following:
1632
1633     skip        see skip()
1634     todo        see todo()
1635     todo_skip   see todo_skip()
1636     unknown     see below
1637
1638 Sometimes the Test::Builder test counter is incremented without it
1639 printing any test output, for example, when current_test() is changed.
1640 In these cases, Test::Builder doesn't know the result of the test, so
1641 its type is 'unknown'.  These details for these tests are filled in.
1642 They are considered ok, but the name and actual_ok is left undef.
1643
1644 For example "not ok 23 - hole count # TODO insufficient donuts" would
1645 result in this structure:
1646
1647     $tests[22] =    # 23 - 1, since arrays start from 0.
1648       { ok        => 1,   # logically, the test passed since it's todo
1649         actual_ok => 0,   # in absolute terms, it failed
1650         name      => 'hole count',
1651         type      => 'todo',
1652         reason    => 'insufficient donuts'
1653       };
1654
1655 =cut
1656
1657 sub details {
1658     my $self = shift;
1659     return @{ $self->{Test_Results} };
1660 }
1661
1662 =item B<todo>
1663
1664     my $todo_reason = $Test->todo;
1665     my $todo_reason = $Test->todo($pack);
1666
1667 If the current tests are considered "TODO" it will return the reason,
1668 if any.  This reason can come from a $TODO variable or the last call
1669 to C<<todo_start()>>.
1670
1671 Since a TODO test does not need a reason, this function can return an
1672 empty string even when inside a TODO block.  Use C<<$Test->in_todo>>
1673 to determine if you are currently inside a TODO block.
1674
1675 todo() is about finding the right package to look for $TODO in.  It's
1676 pretty good at guessing the right package to look at.  It first looks for
1677 the caller based on C<$Level + 1>, since C<todo()> is usually called inside
1678 a test function.  As a last resort it will use C<exported_to()>.
1679
1680 Sometimes there is some confusion about where todo() should be looking
1681 for the $TODO variable.  If you want to be sure, tell it explicitly
1682 what $pack to use.
1683
1684 =cut
1685
1686 sub todo {
1687     my( $self, $pack ) = @_;
1688
1689     return $self->{Todo} if defined $self->{Todo};
1690
1691     local $Level = $Level + 1;
1692     my $todo = $self->find_TODO($pack);
1693     return $todo if defined $todo;
1694
1695     return '';
1696 }
1697
1698 =item B<find_TODO>
1699
1700     my $todo_reason = $Test->find_TODO();
1701     my $todo_reason = $Test->find_TODO($pack):
1702
1703 Like C<<todo()>> but only returns the value of C<<$TODO>> ignoring
1704 C<<todo_start()>>.
1705
1706 =cut
1707
1708 sub find_TODO {
1709     my( $self, $pack ) = @_;
1710
1711     $pack = $pack || $self->caller(1) || $self->exported_to;
1712     return unless $pack;
1713
1714     no strict 'refs';    ## no critic
1715     return ${ $pack . '::TODO' };
1716 }
1717
1718 =item B<in_todo>
1719
1720     my $in_todo = $Test->in_todo;
1721
1722 Returns true if the test is currently inside a TODO block.
1723
1724 =cut
1725
1726 sub in_todo {
1727     my $self = shift;
1728
1729     local $Level = $Level + 1;
1730     return( defined $self->{Todo} || $self->find_TODO ) ? 1 : 0;
1731 }
1732
1733 =item B<todo_start>
1734
1735     $Test->todo_start();
1736     $Test->todo_start($message);
1737
1738 This method allows you declare all subsequent tests as TODO tests, up until
1739 the C<todo_end> method has been called.
1740
1741 The C<TODO:> and C<$TODO> syntax is generally pretty good about figuring out
1742 whether or not we're in a TODO test.  However, often we find that this is not
1743 possible to determine (such as when we want to use C<$TODO> but
1744 the tests are being executed in other packages which can't be inferred
1745 beforehand).
1746
1747 Note that you can use this to nest "todo" tests
1748
1749  $Test->todo_start('working on this');
1750  # lots of code
1751  $Test->todo_start('working on that');
1752  # more code
1753  $Test->todo_end;
1754  $Test->todo_end;
1755
1756 This is generally not recommended, but large testing systems often have weird
1757 internal needs.
1758
1759 We've tried to make this also work with the TODO: syntax, but it's not
1760 guaranteed and its use is also discouraged:
1761
1762  TODO: {
1763      local $TODO = 'We have work to do!';
1764      $Test->todo_start('working on this');
1765      # lots of code
1766      $Test->todo_start('working on that');
1767      # more code
1768      $Test->todo_end;
1769      $Test->todo_end;
1770  }
1771
1772 Pick one style or another of "TODO" to be on the safe side.
1773
1774 =cut
1775
1776 sub todo_start {
1777     my $self = shift;
1778     my $message = @_ ? shift : '';
1779
1780     $self->{Start_Todo}++;
1781     if( $self->in_todo ) {
1782         push @{ $self->{Todo_Stack} } => $self->todo;
1783     }
1784     $self->{Todo} = $message;
1785
1786     return;
1787 }
1788
1789 =item C<todo_end>
1790
1791  $Test->todo_end;
1792
1793 Stops running tests as "TODO" tests.  This method is fatal if called without a
1794 preceding C<todo_start> method call.
1795
1796 =cut
1797
1798 sub todo_end {
1799     my $self = shift;
1800
1801     if( !$self->{Start_Todo} ) {
1802         $self->croak('todo_end() called without todo_start()');
1803     }
1804
1805     $self->{Start_Todo}--;
1806
1807     if( $self->{Start_Todo} && @{ $self->{Todo_Stack} } ) {
1808         $self->{Todo} = pop @{ $self->{Todo_Stack} };
1809     }
1810     else {
1811         delete $self->{Todo};
1812     }
1813
1814     return;
1815 }
1816
1817 =item B<caller>
1818
1819     my $package = $Test->caller;
1820     my($pack, $file, $line) = $Test->caller;
1821     my($pack, $file, $line) = $Test->caller($height);
1822
1823 Like the normal caller(), except it reports according to your level().
1824
1825 C<$height> will be added to the level().
1826
1827 =cut
1828
1829 sub caller {    ## no critic (Subroutines::ProhibitBuiltinHomonyms)
1830     my( $self, $height ) = @_;
1831     $height ||= 0;
1832
1833     my @caller = CORE::caller( $self->level + $height + 1 );
1834     return wantarray ? @caller : $caller[0];
1835 }
1836
1837 =back
1838
1839 =cut
1840
1841 =begin _private
1842
1843 =over 4
1844
1845 =item B<_sanity_check>
1846
1847   $self->_sanity_check();
1848
1849 Runs a bunch of end of test sanity checks to make sure reality came
1850 through ok.  If anything is wrong it will die with a fairly friendly
1851 error message.
1852
1853 =cut
1854
1855 #'#
1856 sub _sanity_check {
1857     my $self = shift;
1858
1859     $self->_whoa( $self->{Curr_Test} < 0, 'Says here you ran a negative number of tests!' );
1860     $self->_whoa( !$self->{Have_Plan} and $self->{Curr_Test},
1861         'Somehow your tests ran without a plan!' );
1862     $self->_whoa( $self->{Curr_Test} != @{ $self->{Test_Results} },
1863         'Somehow you got a different number of results than tests ran!' );
1864
1865     return;
1866 }
1867
1868 =item B<_whoa>
1869
1870   $self->_whoa($check, $description);
1871
1872 A sanity check, similar to assert().  If the $check is true, something
1873 has gone horribly wrong.  It will die with the given $description and
1874 a note to contact the author.
1875
1876 =cut
1877
1878 sub _whoa {
1879     my( $self, $check, $desc ) = @_;
1880     if($check) {
1881         local $Level = $Level + 1;
1882         $self->croak(<<"WHOA");
1883 WHOA!  $desc
1884 This should never happen!  Please contact the author immediately!
1885 WHOA
1886     }
1887
1888     return;
1889 }
1890
1891 =item B<_my_exit>
1892
1893   _my_exit($exit_num);
1894
1895 Perl seems to have some trouble with exiting inside an END block.  5.005_03
1896 and 5.6.1 both seem to do odd things.  Instead, this function edits $?
1897 directly.  It should ONLY be called from inside an END block.  It
1898 doesn't actually exit, that's your job.
1899
1900 =cut
1901
1902 sub _my_exit {
1903     $? = $_[0];    ## no critic (Variables::RequireLocalizedPunctuationVars)
1904
1905     return 1;
1906 }
1907
1908 =back
1909
1910 =end _private
1911
1912 =cut
1913
1914 sub _ending {
1915     my $self = shift;
1916
1917     my $real_exit_code = $?;
1918     $self->_sanity_check();
1919
1920     # Don't bother with an ending if this is a forked copy.  Only the parent
1921     # should do the ending.
1922     if( $self->{Original_Pid} != $$ ) {
1923         return;
1924     }
1925
1926     # Exit if plan() was never called.  This is so "require Test::Simple"
1927     # doesn't puke.
1928     if( !$self->{Have_Plan} ) {
1929         return;
1930     }
1931
1932     # Don't do an ending if we bailed out.
1933     if( $self->{Bailed_Out} ) {
1934         return;
1935     }
1936
1937     # Figure out if we passed or failed and print helpful messages.
1938     my $test_results = $self->{Test_Results};
1939     if(@$test_results) {
1940         # The plan?  We have no plan.
1941         if( $self->{No_Plan} ) {
1942             $self->_print("1..$self->{Curr_Test}\n") unless $self->no_header;
1943             $self->{Expected_Tests} = $self->{Curr_Test};
1944         }
1945
1946         # Auto-extended arrays and elements which aren't explicitly
1947         # filled in with a shared reference will puke under 5.8.0
1948         # ithreads.  So we have to fill them in by hand. :(
1949         my $empty_result = &share( {} );
1950         for my $idx ( 0 .. $self->{Expected_Tests} - 1 ) {
1951             $test_results->[$idx] = $empty_result
1952               unless defined $test_results->[$idx];
1953         }
1954
1955         my $num_failed = grep !$_->{'ok'}, @{$test_results}[ 0 .. $self->{Curr_Test} - 1 ];
1956
1957         my $num_extra = $self->{Curr_Test} - $self->{Expected_Tests};
1958
1959         if( $num_extra != 0 ) {
1960             my $s = $self->{Expected_Tests} == 1 ? '' : 's';
1961             $self->diag(<<"FAIL");
1962 Looks like you planned $self->{Expected_Tests} test$s but ran $self->{Curr_Test}.
1963 FAIL
1964         }
1965
1966         if($num_failed) {
1967             my $num_tests = $self->{Curr_Test};
1968             my $s = $num_failed == 1 ? '' : 's';
1969
1970             my $qualifier = $num_extra == 0 ? '' : ' run';
1971
1972             $self->diag(<<"FAIL");
1973 Looks like you failed $num_failed test$s of $num_tests$qualifier.
1974 FAIL
1975         }
1976
1977         if($real_exit_code) {
1978             $self->diag(<<"FAIL");
1979 Looks like your test exited with $real_exit_code just after $self->{Curr_Test}.
1980 FAIL
1981
1982             _my_exit($real_exit_code) && return;
1983         }
1984
1985         my $exit_code;
1986         if($num_failed) {
1987             $exit_code = $num_failed <= 254 ? $num_failed : 254;
1988         }
1989         elsif( $num_extra != 0 ) {
1990             $exit_code = 255;
1991         }
1992         else {
1993             $exit_code = 0;
1994         }
1995
1996         _my_exit($exit_code) && return;
1997     }
1998     elsif( $self->{Skip_All} ) {
1999         _my_exit(0) && return;
2000     }
2001     elsif($real_exit_code) {
2002         $self->diag(<<"FAIL");
2003 Looks like your test exited with $real_exit_code before it could output anything.
2004 FAIL
2005         _my_exit($real_exit_code) && return;
2006     }
2007     else {
2008         $self->diag("No tests run!\n");
2009         _my_exit(255) && return;
2010     }
2011
2012     $self->_whoa( 1, "We fell off the end of _ending()" );
2013 }
2014
2015 END {
2016     $Test->_ending if defined $Test and !$Test->no_ending;
2017 }
2018
2019 =head1 EXIT CODES
2020
2021 If all your tests passed, Test::Builder will exit with zero (which is
2022 normal).  If anything failed it will exit with how many failed.  If
2023 you run less (or more) tests than you planned, the missing (or extras)
2024 will be considered failures.  If no tests were ever run Test::Builder
2025 will throw a warning and exit with 255.  If the test died, even after
2026 having successfully completed all its tests, it will still be
2027 considered a failure and will exit with 255.
2028
2029 So the exit codes are...
2030
2031     0                   all tests successful
2032     255                 test died or all passed but wrong # of tests run
2033     any other number    how many failed (including missing or extras)
2034
2035 If you fail more than 254 tests, it will be reported as 254.
2036
2037
2038 =head1 THREADS
2039
2040 In perl 5.8.1 and later, Test::Builder is thread-safe.  The test
2041 number is shared amongst all threads.  This means if one thread sets
2042 the test number using current_test() they will all be effected.
2043
2044 While versions earlier than 5.8.1 had threads they contain too many
2045 bugs to support.
2046
2047 Test::Builder is only thread-aware if threads.pm is loaded I<before>
2048 Test::Builder.
2049
2050 =head1 EXAMPLES
2051
2052 CPAN can provide the best examples.  Test::Simple, Test::More,
2053 Test::Exception and Test::Differences all use Test::Builder.
2054
2055 =head1 SEE ALSO
2056
2057 Test::Simple, Test::More, Test::Harness
2058
2059 =head1 AUTHORS
2060
2061 Original code by chromatic, maintained by Michael G Schwern
2062 E<lt>schwern@pobox.comE<gt>
2063
2064 =head1 COPYRIGHT
2065
2066 Copyright 2002-2008 by chromatic E<lt>chromatic@wgz.orgE<gt> and
2067                        Michael G Schwern E<lt>schwern@pobox.comE<gt>.
2068
2069 This program is free software; you can redistribute it and/or 
2070 modify it under the same terms as Perl itself.
2071
2072 See F<http://www.perl.com/perl/misc/Artistic.html>
2073
2074 =cut
2075
2076 1;
2077