Silence a warning in Test::Builder that was causing lib/constant.t
[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_01';
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     no warnings 'numeric';
491     for my $val (@_) {
492         next unless $self->_is_dualvar($$val);
493         $$val = $$val + 0;
494     }
495
496     return;
497 }
498
499 # This is a hack to detect a dualvar such as $!
500 sub _is_dualvar {
501     my( $self, $val ) = @_;
502
503     no warnings 'numeric';
504     my $numval = $val + 0;
505     return $numval != 0 and $numval ne $val ? 1 : 0;
506 }
507
508 =item B<is_eq>
509
510   $Test->is_eq($got, $expected, $name);
511
512 Like Test::More's is().  Checks if $got eq $expected.  This is the
513 string version.
514
515 =item B<is_num>
516
517   $Test->is_num($got, $expected, $name);
518
519 Like Test::More's is().  Checks if $got == $expected.  This is the
520 numeric version.
521
522 =cut
523
524 sub is_eq {
525     my( $self, $got, $expect, $name ) = @_;
526     local $Level = $Level + 1;
527
528     $self->_unoverload_str( \$got, \$expect );
529
530     if( !defined $got || !defined $expect ) {
531         # undef only matches undef and nothing else
532         my $test = !defined $got && !defined $expect;
533
534         $self->ok( $test, $name );
535         $self->_is_diag( $got, 'eq', $expect ) unless $test;
536         return $test;
537     }
538
539     return $self->cmp_ok( $got, 'eq', $expect, $name );
540 }
541
542 sub is_num {
543     my( $self, $got, $expect, $name ) = @_;
544     local $Level = $Level + 1;
545
546     $self->_unoverload_num( \$got, \$expect );
547
548     if( !defined $got || !defined $expect ) {
549         # undef only matches undef and nothing else
550         my $test = !defined $got && !defined $expect;
551
552         $self->ok( $test, $name );
553         $self->_is_diag( $got, '==', $expect ) unless $test;
554         return $test;
555     }
556
557     return $self->cmp_ok( $got, '==', $expect, $name );
558 }
559
560 sub _diag_fmt {
561     my( $self, $type, $val ) = @_;
562
563     if( defined $$val ) {
564         if( $type eq 'eq' or $type eq 'ne' ) {
565             # quote and force string context
566             $$val = "'$$val'";
567         }
568         else {
569             # force numeric context
570             $self->_unoverload_num($val);
571         }
572     }
573     else {
574         $$val = 'undef';
575     }
576
577     return;
578 }
579
580 sub _is_diag {
581     my( $self, $got, $type, $expect ) = @_;
582
583     $self->_diag_fmt( $type, $_ ) for \$got, \$expect;
584
585     local $Level = $Level + 1;
586     return $self->diag(<<"DIAGNOSTIC");
587          got: $got
588     expected: $expect
589 DIAGNOSTIC
590
591 }
592
593 sub _isnt_diag {
594     my( $self, $got, $type ) = @_;
595
596     $self->_diag_fmt( $type, \$got );
597
598     local $Level = $Level + 1;
599     return $self->diag(<<"DIAGNOSTIC");
600          got: $got
601     expected: anything else
602 DIAGNOSTIC
603 }
604
605 =item B<isnt_eq>
606
607   $Test->isnt_eq($got, $dont_expect, $name);
608
609 Like Test::More's isnt().  Checks if $got ne $dont_expect.  This is
610 the string version.
611
612 =item B<isnt_num>
613
614   $Test->isnt_num($got, $dont_expect, $name);
615
616 Like Test::More's isnt().  Checks if $got ne $dont_expect.  This is
617 the numeric version.
618
619 =cut
620
621 sub isnt_eq {
622     my( $self, $got, $dont_expect, $name ) = @_;
623     local $Level = $Level + 1;
624
625     if( !defined $got || !defined $dont_expect ) {
626         # undef only matches undef and nothing else
627         my $test = defined $got || defined $dont_expect;
628
629         $self->ok( $test, $name );
630         $self->_isnt_diag( $got, 'ne' ) unless $test;
631         return $test;
632     }
633
634     return $self->cmp_ok( $got, 'ne', $dont_expect, $name );
635 }
636
637 sub isnt_num {
638     my( $self, $got, $dont_expect, $name ) = @_;
639     local $Level = $Level + 1;
640
641     if( !defined $got || !defined $dont_expect ) {
642         # undef only matches undef and nothing else
643         my $test = defined $got || defined $dont_expect;
644
645         $self->ok( $test, $name );
646         $self->_isnt_diag( $got, '!=' ) unless $test;
647         return $test;
648     }
649
650     return $self->cmp_ok( $got, '!=', $dont_expect, $name );
651 }
652
653 =item B<like>
654
655   $Test->like($this, qr/$regex/, $name);
656   $Test->like($this, '/$regex/', $name);
657
658 Like Test::More's like().  Checks if $this matches the given $regex.
659
660 You'll want to avoid qr// if you want your tests to work before 5.005.
661
662 =item B<unlike>
663
664   $Test->unlike($this, qr/$regex/, $name);
665   $Test->unlike($this, '/$regex/', $name);
666
667 Like Test::More's unlike().  Checks if $this B<does not match> the
668 given $regex.
669
670 =cut
671
672 sub like {
673     my( $self, $this, $regex, $name ) = @_;
674
675     local $Level = $Level + 1;
676     return $self->_regex_ok( $this, $regex, '=~', $name );
677 }
678
679 sub unlike {
680     my( $self, $this, $regex, $name ) = @_;
681
682     local $Level = $Level + 1;
683     return $self->_regex_ok( $this, $regex, '!~', $name );
684 }
685
686 =item B<cmp_ok>
687
688   $Test->cmp_ok($this, $type, $that, $name);
689
690 Works just like Test::More's cmp_ok().
691
692     $Test->cmp_ok($big_num, '!=', $other_big_num);
693
694 =cut
695
696 my %numeric_cmps = map { ( $_, 1 ) } ( "<", "<=", ">", ">=", "==", "!=", "<=>" );
697
698 sub cmp_ok {
699     my( $self, $got, $type, $expect, $name ) = @_;
700
701     # Treat overloaded objects as numbers if we're asked to do a
702     # numeric comparison.
703     my $unoverload
704       = $numeric_cmps{$type}
705       ? '_unoverload_num'
706       : '_unoverload_str';
707
708     $self->$unoverload( \$got, \$expect );
709
710     my $test;
711     {
712         ## no critic (BuiltinFunctions::ProhibitStringyEval)
713
714         local( $@, $!, $SIG{__DIE__} );    # isolate eval
715
716         my $code = $self->_caller_context;
717
718         # Yes, it has to look like this or 5.4.5 won't see the #line
719         # directive.
720         # Don't ask me, man, I just work here.
721         $test = eval "
722 $code" . "\$got $type \$expect;";
723
724     }
725     local $Level = $Level + 1;
726     my $ok = $self->ok( $test, $name );
727
728     unless($ok) {
729         if( $type =~ /^(eq|==)$/ ) {
730             $self->_is_diag( $got, $type, $expect );
731         }
732         elsif( $type =~ /^(ne|!=)$/ ) {
733             $self->_isnt_diag( $got, $type );
734         }
735         else {
736             $self->_cmp_diag( $got, $type, $expect );
737         }
738     }
739     return $ok;
740 }
741
742 sub _cmp_diag {
743     my( $self, $got, $type, $expect ) = @_;
744
745     $got    = defined $got    ? "'$got'"    : 'undef';
746     $expect = defined $expect ? "'$expect'" : 'undef';
747
748     local $Level = $Level + 1;
749     return $self->diag(<<"DIAGNOSTIC");
750     $got
751         $type
752     $expect
753 DIAGNOSTIC
754 }
755
756 sub _caller_context {
757     my $self = shift;
758
759     my( $pack, $file, $line ) = $self->caller(1);
760
761     my $code = '';
762     $code .= "#line $line $file\n" if defined $file and defined $line;
763
764     return $code;
765 }
766
767 =back
768
769
770 =head2 Other Testing Methods
771
772 These are methods which are used in the course of writing a test but are not themselves tests.
773
774 =over 4
775
776 =item B<BAIL_OUT>
777
778     $Test->BAIL_OUT($reason);
779
780 Indicates to the Test::Harness that things are going so badly all
781 testing should terminate.  This includes running any additional test
782 scripts.
783
784 It will exit with 255.
785
786 =cut
787
788 sub BAIL_OUT {
789     my( $self, $reason ) = @_;
790
791     $self->{Bailed_Out} = 1;
792     $self->_print("Bail out!  $reason");
793     exit 255;
794 }
795
796 =for deprecated
797 BAIL_OUT() used to be BAILOUT()
798
799 =cut
800
801 *BAILOUT = \&BAIL_OUT;
802
803 =item B<skip>
804
805     $Test->skip;
806     $Test->skip($why);
807
808 Skips the current test, reporting $why.
809
810 =cut
811
812 sub skip {
813     my( $self, $why ) = @_;
814     $why ||= '';
815     $self->_unoverload_str( \$why );
816
817     $self->_plan_check;
818
819     lock( $self->{Curr_Test} );
820     $self->{Curr_Test}++;
821
822     $self->{Test_Results}[ $self->{Curr_Test} - 1 ] = &share(
823         {
824             'ok'      => 1,
825             actual_ok => 1,
826             name      => '',
827             type      => 'skip',
828             reason    => $why,
829         }
830     );
831
832     my $out = "ok";
833     $out .= " $self->{Curr_Test}" if $self->use_numbers;
834     $out .= " # skip";
835     $out .= " $why"               if length $why;
836     $out .= "\n";
837
838     $self->_print($out);
839
840     return 1;
841 }
842
843 =item B<todo_skip>
844
845   $Test->todo_skip;
846   $Test->todo_skip($why);
847
848 Like skip(), only it will declare the test as failing and TODO.  Similar
849 to
850
851     print "not ok $tnum # TODO $why\n";
852
853 =cut
854
855 sub todo_skip {
856     my( $self, $why ) = @_;
857     $why ||= '';
858
859     $self->_plan_check;
860
861     lock( $self->{Curr_Test} );
862     $self->{Curr_Test}++;
863
864     $self->{Test_Results}[ $self->{Curr_Test} - 1 ] = &share(
865         {
866             'ok'      => 1,
867             actual_ok => 0,
868             name      => '',
869             type      => 'todo_skip',
870             reason    => $why,
871         }
872     );
873
874     my $out = "not ok";
875     $out .= " $self->{Curr_Test}" if $self->use_numbers;
876     $out .= " # TODO & SKIP $why\n";
877
878     $self->_print($out);
879
880     return 1;
881 }
882
883 =begin _unimplemented
884
885 =item B<skip_rest>
886
887   $Test->skip_rest;
888   $Test->skip_rest($reason);
889
890 Like skip(), only it skips all the rest of the tests you plan to run
891 and terminates the test.
892
893 If you're running under no_plan, it skips once and terminates the
894 test.
895
896 =end _unimplemented
897
898 =back
899
900
901 =head2 Test building utility methods
902
903 These methods are useful when writing your own test methods.
904
905 =over 4
906
907 =item B<maybe_regex>
908
909   $Test->maybe_regex(qr/$regex/);
910   $Test->maybe_regex('/$regex/');
911
912 Convenience method for building testing functions that take regular
913 expressions as arguments, but need to work before perl 5.005.
914
915 Takes a quoted regular expression produced by qr//, or a string
916 representing a regular expression.
917
918 Returns a Perl value which may be used instead of the corresponding
919 regular expression, or undef if its argument is not recognised.
920
921 For example, a version of like(), sans the useful diagnostic messages,
922 could be written as:
923
924   sub laconic_like {
925       my ($self, $this, $regex, $name) = @_;
926       my $usable_regex = $self->maybe_regex($regex);
927       die "expecting regex, found '$regex'\n"
928           unless $usable_regex;
929       $self->ok($this =~ m/$usable_regex/, $name);
930   }
931
932 =cut
933
934 sub maybe_regex {
935     my( $self, $regex ) = @_;
936     my $usable_regex = undef;
937
938     return $usable_regex unless defined $regex;
939
940     my( $re, $opts );
941
942     # Check for qr/foo/
943     if( _is_qr($regex) ) {
944         $usable_regex = $regex;
945     }
946     # Check for '/foo/' or 'm,foo,'
947     elsif(( $re, $opts )        = $regex =~ m{^ /(.*)/ (\w*) $ }sx              or
948           ( undef, $re, $opts ) = $regex =~ m,^ m([^\w\s]) (.+) \1 (\w*) $,sx
949     )
950     {
951         $usable_regex = length $opts ? "(?$opts)$re" : $re;
952     }
953
954     return $usable_regex;
955 }
956
957 sub _is_qr {
958     my $regex = shift;
959
960     # is_regexp() checks for regexes in a robust manner, say if they're
961     # blessed.
962     return re::is_regexp($regex) if defined &re::is_regexp;
963     return ref $regex eq 'Regexp';
964 }
965
966 sub _regex_ok {
967     my( $self, $this, $regex, $cmp, $name ) = @_;
968
969     my $ok           = 0;
970     my $usable_regex = $self->maybe_regex($regex);
971     unless( defined $usable_regex ) {
972         local $Level = $Level + 1;
973         $ok = $self->ok( 0, $name );
974         $self->diag("    '$regex' doesn't look much like a regex to me.");
975         return $ok;
976     }
977
978     {
979         ## no critic (BuiltinFunctions::ProhibitStringyEval)
980
981         my $test;
982         my $code = $self->_caller_context;
983
984         local( $@, $!, $SIG{__DIE__} );    # isolate eval
985
986         # Yes, it has to look like this or 5.4.5 won't see the #line
987         # directive.
988         # Don't ask me, man, I just work here.
989         $test = eval "
990 $code" . q{$test = $this =~ /$usable_regex/ ? 1 : 0};
991
992         $test = !$test if $cmp eq '!~';
993
994         local $Level = $Level + 1;
995         $ok = $self->ok( $test, $name );
996     }
997
998     unless($ok) {
999         $this = defined $this ? "'$this'" : 'undef';
1000         my $match = $cmp eq '=~' ? "doesn't match" : "matches";
1001
1002         local $Level = $Level + 1;
1003         $self->diag( sprintf <<'DIAGNOSTIC', $this, $match, $regex );
1004                   %s
1005     %13s '%s'
1006 DIAGNOSTIC
1007
1008     }
1009
1010     return $ok;
1011 }
1012
1013 # I'm not ready to publish this.  It doesn't deal with array return
1014 # values from the code or context.
1015
1016 =begin private
1017
1018 =item B<_try>
1019
1020     my $return_from_code          = $Test->try(sub { code });
1021     my($return_from_code, $error) = $Test->try(sub { code });
1022
1023 Works like eval BLOCK except it ensures it has no effect on the rest
1024 of the test (ie. $@ is not set) nor is effected by outside
1025 interference (ie. $SIG{__DIE__}) and works around some quirks in older
1026 Perls.
1027
1028 $error is what would normally be in $@.
1029
1030 It is suggested you use this in place of eval BLOCK.
1031
1032 =cut
1033
1034 sub _try {
1035     my( $self, $code ) = @_;
1036
1037     local $!;               # eval can mess up $!
1038     local $@;               # don't set $@ in the test
1039     local $SIG{__DIE__};    # don't trip an outside DIE handler.
1040     my $return = eval { $code->() };
1041
1042     return wantarray ? ( $return, $@ ) : $return;
1043 }
1044
1045 =end private
1046
1047
1048 =item B<is_fh>
1049
1050     my $is_fh = $Test->is_fh($thing);
1051
1052 Determines if the given $thing can be used as a filehandle.
1053
1054 =cut
1055
1056 sub is_fh {
1057     my $self     = shift;
1058     my $maybe_fh = shift;
1059     return 0 unless defined $maybe_fh;
1060
1061     return 1 if ref $maybe_fh  eq 'GLOB';    # its a glob ref
1062     return 1 if ref \$maybe_fh eq 'GLOB';    # its a glob
1063
1064     return eval { $maybe_fh->isa("IO::Handle") } ||
1065            # 5.5.4's tied() and can() doesn't like getting undef
1066            eval { ( tied($maybe_fh) || '' )->can('TIEHANDLE') };
1067 }
1068
1069 =back
1070
1071
1072 =head2 Test style
1073
1074
1075 =over 4
1076
1077 =item B<level>
1078
1079     $Test->level($how_high);
1080
1081 How far up the call stack should $Test look when reporting where the
1082 test failed.
1083
1084 Defaults to 1.
1085
1086 Setting L<$Test::Builder::Level> overrides.  This is typically useful
1087 localized:
1088
1089     sub my_ok {
1090         my $test = shift;
1091
1092         local $Test::Builder::Level = $Test::Builder::Level + 1;
1093         $TB->ok($test);
1094     }
1095
1096 To be polite to other functions wrapping your own you usually want to increment C<$Level> rather than set it to a constant.
1097
1098 =cut
1099
1100 sub level {
1101     my( $self, $level ) = @_;
1102
1103     if( defined $level ) {
1104         $Level = $level;
1105     }
1106     return $Level;
1107 }
1108
1109 =item B<use_numbers>
1110
1111     $Test->use_numbers($on_or_off);
1112
1113 Whether or not the test should output numbers.  That is, this if true:
1114
1115   ok 1
1116   ok 2
1117   ok 3
1118
1119 or this if false
1120
1121   ok
1122   ok
1123   ok
1124
1125 Most useful when you can't depend on the test output order, such as
1126 when threads or forking is involved.
1127
1128 Defaults to on.
1129
1130 =cut
1131
1132 sub use_numbers {
1133     my( $self, $use_nums ) = @_;
1134
1135     if( defined $use_nums ) {
1136         $self->{Use_Nums} = $use_nums;
1137     }
1138     return $self->{Use_Nums};
1139 }
1140
1141 =item B<no_diag>
1142
1143     $Test->no_diag($no_diag);
1144
1145 If set true no diagnostics will be printed.  This includes calls to
1146 diag().
1147
1148 =item B<no_ending>
1149
1150     $Test->no_ending($no_ending);
1151
1152 Normally, Test::Builder does some extra diagnostics when the test
1153 ends.  It also changes the exit code as described below.
1154
1155 If this is true, none of that will be done.
1156
1157 =item B<no_header>
1158
1159     $Test->no_header($no_header);
1160
1161 If set to true, no "1..N" header will be printed.
1162
1163 =cut
1164
1165 foreach my $attribute (qw(No_Header No_Ending No_Diag)) {
1166     my $method = lc $attribute;
1167
1168     my $code = sub {
1169         my( $self, $no ) = @_;
1170
1171         if( defined $no ) {
1172             $self->{$attribute} = $no;
1173         }
1174         return $self->{$attribute};
1175     };
1176
1177     no strict 'refs';    ## no critic
1178     *{ __PACKAGE__ . '::' . $method } = $code;
1179 }
1180
1181 =back
1182
1183 =head2 Output
1184
1185 Controlling where the test output goes.
1186
1187 It's ok for your test to change where STDOUT and STDERR point to,
1188 Test::Builder's default output settings will not be affected.
1189
1190 =over 4
1191
1192 =item B<diag>
1193
1194     $Test->diag(@msgs);
1195
1196 Prints out the given @msgs.  Like C<print>, arguments are simply
1197 appended together.
1198
1199 Normally, it uses the failure_output() handle, but if this is for a
1200 TODO test, the todo_output() handle is used.
1201
1202 Output will be indented and marked with a # so as not to interfere
1203 with test output.  A newline will be put on the end if there isn't one
1204 already.
1205
1206 We encourage using this rather than calling print directly.
1207
1208 Returns false.  Why?  Because diag() is often used in conjunction with
1209 a failing test (C<ok() || diag()>) it "passes through" the failure.
1210
1211     return ok(...) || diag(...);
1212
1213 =for blame transfer
1214 Mark Fowler <mark@twoshortplanks.com>
1215
1216 =cut
1217
1218 sub diag {
1219     my $self = shift;
1220
1221     $self->_print_comment( $self->_diag_fh, @_ );
1222 }
1223
1224 =item B<note>
1225
1226     $Test->note(@msgs);
1227
1228 Like diag(), but it prints to the C<output()> handle so it will not
1229 normally be seen by the user except in verbose mode.
1230
1231 =cut
1232
1233 sub note {
1234     my $self = shift;
1235
1236     $self->_print_comment( $self->output, @_ );
1237 }
1238
1239 sub _diag_fh {
1240     my $self = shift;
1241
1242     local $Level = $Level + 1;
1243     return $self->in_todo ? $self->todo_output : $self->failure_output;
1244 }
1245
1246 sub _print_comment {
1247     my( $self, $fh, @msgs ) = @_;
1248
1249     return if $self->no_diag;
1250     return unless @msgs;
1251
1252     # Prevent printing headers when compiling (i.e. -c)
1253     return if $^C;
1254
1255     # Smash args together like print does.
1256     # Convert undef to 'undef' so its readable.
1257     my $msg = join '', map { defined($_) ? $_ : 'undef' } @msgs;
1258
1259     # Escape the beginning, _print will take care of the rest.
1260     $msg =~ s/^/# /;
1261
1262     local $Level = $Level + 1;
1263     $self->_print_to_fh( $fh, $msg );
1264
1265     return 0;
1266 }
1267
1268 =item B<explain>
1269
1270     my @dump = $Test->explain(@msgs);
1271
1272 Will dump the contents of any references in a human readable format.
1273 Handy for things like...
1274
1275     is_deeply($have, $want) || diag explain $have;
1276
1277 or
1278
1279     is_deeply($have, $want) || note explain $have;
1280
1281 =cut
1282
1283 sub explain {
1284     my $self = shift;
1285
1286     return map {
1287         ref $_
1288           ? do {
1289             require Data::Dumper;
1290
1291             my $dumper = Data::Dumper->new( [$_] );
1292             $dumper->Indent(1)->Terse(1);
1293             $dumper->Sortkeys(1) if $dumper->can("Sortkeys");
1294             $dumper->Dump;
1295           }
1296           : $_
1297     } @_;
1298 }
1299
1300 =begin _private
1301
1302 =item B<_print>
1303
1304     $Test->_print(@msgs);
1305
1306 Prints to the output() filehandle.
1307
1308 =end _private
1309
1310 =cut
1311
1312 sub _print {
1313     my $self = shift;
1314     return $self->_print_to_fh( $self->output, @_ );
1315 }
1316
1317 sub _print_to_fh {
1318     my( $self, $fh, @msgs ) = @_;
1319
1320     # Prevent printing headers when only compiling.  Mostly for when
1321     # tests are deparsed with B::Deparse
1322     return if $^C;
1323
1324     my $msg = join '', @msgs;
1325
1326     local( $\, $", $, ) = ( undef, ' ', '' );
1327
1328     # Escape each line after the first with a # so we don't
1329     # confuse Test::Harness.
1330     $msg =~ s/\n(.)/\n# $1/sg;
1331
1332     # Stick a newline on the end if it needs it.
1333     $msg .= "\n" unless $msg =~ /\n\Z/;
1334
1335     return print $fh $msg;
1336 }
1337
1338 =item B<output>
1339
1340     $Test->output($fh);
1341     $Test->output($file);
1342
1343 Where normal "ok/not ok" test output should go.
1344
1345 Defaults to STDOUT.
1346
1347 =item B<failure_output>
1348
1349     $Test->failure_output($fh);
1350     $Test->failure_output($file);
1351
1352 Where diagnostic output on test failures and diag() should go.
1353
1354 Defaults to STDERR.
1355
1356 =item B<todo_output>
1357
1358     $Test->todo_output($fh);
1359     $Test->todo_output($file);
1360
1361 Where diagnostics about todo test failures and diag() should go.
1362
1363 Defaults to STDOUT.
1364
1365 =cut
1366
1367 sub output {
1368     my( $self, $fh ) = @_;
1369
1370     if( defined $fh ) {
1371         $self->{Out_FH} = $self->_new_fh($fh);
1372     }
1373     return $self->{Out_FH};
1374 }
1375
1376 sub failure_output {
1377     my( $self, $fh ) = @_;
1378
1379     if( defined $fh ) {
1380         $self->{Fail_FH} = $self->_new_fh($fh);
1381     }
1382     return $self->{Fail_FH};
1383 }
1384
1385 sub todo_output {
1386     my( $self, $fh ) = @_;
1387
1388     if( defined $fh ) {
1389         $self->{Todo_FH} = $self->_new_fh($fh);
1390     }
1391     return $self->{Todo_FH};
1392 }
1393
1394 sub _new_fh {
1395     my $self = shift;
1396     my($file_or_fh) = shift;
1397
1398     my $fh;
1399     if( $self->is_fh($file_or_fh) ) {
1400         $fh = $file_or_fh;
1401     }
1402     else {
1403         open $fh, ">", $file_or_fh
1404           or $self->croak("Can't open test output log $file_or_fh: $!");
1405         _autoflush($fh);
1406     }
1407
1408     return $fh;
1409 }
1410
1411 sub _autoflush {
1412     my($fh) = shift;
1413     my $old_fh = select $fh;
1414     $| = 1;
1415     select $old_fh;
1416
1417     return;
1418 }
1419
1420 my( $Testout, $Testerr );
1421
1422 sub _dup_stdhandles {
1423     my $self = shift;
1424
1425     $self->_open_testhandles;
1426
1427     # Set everything to unbuffered else plain prints to STDOUT will
1428     # come out in the wrong order from our own prints.
1429     _autoflush($Testout);
1430     _autoflush( \*STDOUT );
1431     _autoflush($Testerr);
1432     _autoflush( \*STDERR );
1433
1434     $self->reset_outputs;
1435
1436     return;
1437 }
1438
1439 my $Opened_Testhandles = 0;
1440
1441 sub _open_testhandles {
1442     my $self = shift;
1443
1444     return if $Opened_Testhandles;
1445
1446     # We dup STDOUT and STDERR so people can change them in their
1447     # test suites while still getting normal test output.
1448     open( $Testout, ">&STDOUT" ) or die "Can't dup STDOUT:  $!";
1449     open( $Testerr, ">&STDERR" ) or die "Can't dup STDERR:  $!";
1450
1451     #    $self->_copy_io_layers( \*STDOUT, $Testout );
1452     #    $self->_copy_io_layers( \*STDERR, $Testerr );
1453
1454     $Opened_Testhandles = 1;
1455
1456     return;
1457 }
1458
1459 sub _copy_io_layers {
1460     my( $self, $src, $dst ) = @_;
1461
1462     $self->_try(
1463         sub {
1464             require PerlIO;
1465             my @src_layers = PerlIO::get_layers($src);
1466
1467             binmode $dst, join " ", map ":$_", @src_layers if @src_layers;
1468         }
1469     );
1470
1471     return;
1472 }
1473
1474 =item reset_outputs
1475
1476   $tb->reset_outputs;
1477
1478 Resets all the output filehandles back to their defaults.
1479
1480 =cut
1481
1482 sub reset_outputs {
1483     my $self = shift;
1484
1485     $self->output        ($Testout);
1486     $self->failure_output($Testerr);
1487     $self->todo_output   ($Testout);
1488
1489     return;
1490 }
1491
1492 =item carp
1493
1494   $tb->carp(@message);
1495
1496 Warns with C<@message> but the message will appear to come from the
1497 point where the original test function was called (C<$tb->caller>).
1498
1499 =item croak
1500
1501   $tb->croak(@message);
1502
1503 Dies with C<@message> but the message will appear to come from the
1504 point where the original test function was called (C<$tb->caller>).
1505
1506 =cut
1507
1508 sub _message_at_caller {
1509     my $self = shift;
1510
1511     local $Level = $Level + 1;
1512     my( $pack, $file, $line ) = $self->caller;
1513     return join( "", @_ ) . " at $file line $line.\n";
1514 }
1515
1516 sub carp {
1517     my $self = shift;
1518     return warn $self->_message_at_caller(@_);
1519 }
1520
1521 sub croak {
1522     my $self = shift;
1523     return die $self->_message_at_caller(@_);
1524 }
1525
1526 sub _plan_check {
1527     my $self = shift;
1528
1529     unless( $self->{Have_Plan} ) {
1530         local $Level = $Level + 2;
1531         $self->croak("You tried to run a test without a plan");
1532     }
1533
1534     return;
1535 }
1536
1537 =back
1538
1539
1540 =head2 Test Status and Info
1541
1542 =over 4
1543
1544 =item B<current_test>
1545
1546     my $curr_test = $Test->current_test;
1547     $Test->current_test($num);
1548
1549 Gets/sets the current test number we're on.  You usually shouldn't
1550 have to set this.
1551
1552 If set forward, the details of the missing tests are filled in as 'unknown'.
1553 if set backward, the details of the intervening tests are deleted.  You
1554 can erase history if you really want to.
1555
1556 =cut
1557
1558 sub current_test {
1559     my( $self, $num ) = @_;
1560
1561     lock( $self->{Curr_Test} );
1562     if( defined $num ) {
1563         $self->croak("Can't change the current test number without a plan!")
1564           unless $self->{Have_Plan};
1565
1566         $self->{Curr_Test} = $num;
1567
1568         # If the test counter is being pushed forward fill in the details.
1569         my $test_results = $self->{Test_Results};
1570         if( $num > @$test_results ) {
1571             my $start = @$test_results ? @$test_results : 0;
1572             for( $start .. $num - 1 ) {
1573                 $test_results->[$_] = &share(
1574                     {
1575                         'ok'      => 1,
1576                         actual_ok => undef,
1577                         reason    => 'incrementing test number',
1578                         type      => 'unknown',
1579                         name      => undef
1580                     }
1581                 );
1582             }
1583         }
1584         # If backward, wipe history.  Its their funeral.
1585         elsif( $num < @$test_results ) {
1586             $#{$test_results} = $num - 1;
1587         }
1588     }
1589     return $self->{Curr_Test};
1590 }
1591
1592 =item B<summary>
1593
1594     my @tests = $Test->summary;
1595
1596 A simple summary of the tests so far.  True for pass, false for fail.
1597 This is a logical pass/fail, so todos are passes.
1598
1599 Of course, test #1 is $tests[0], etc...
1600
1601 =cut
1602
1603 sub summary {
1604     my($self) = shift;
1605
1606     return map { $_->{'ok'} } @{ $self->{Test_Results} };
1607 }
1608
1609 =item B<details>
1610
1611     my @tests = $Test->details;
1612
1613 Like summary(), but with a lot more detail.
1614
1615     $tests[$test_num - 1] = 
1616             { 'ok'       => is the test considered a pass?
1617               actual_ok  => did it literally say 'ok'?
1618               name       => name of the test (if any)
1619               type       => type of test (if any, see below).
1620               reason     => reason for the above (if any)
1621             };
1622
1623 'ok' is true if Test::Harness will consider the test to be a pass.
1624
1625 'actual_ok' is a reflection of whether or not the test literally
1626 printed 'ok' or 'not ok'.  This is for examining the result of 'todo'
1627 tests.  
1628
1629 'name' is the name of the test.
1630
1631 'type' indicates if it was a special test.  Normal tests have a type
1632 of ''.  Type can be one of the following:
1633
1634     skip        see skip()
1635     todo        see todo()
1636     todo_skip   see todo_skip()
1637     unknown     see below
1638
1639 Sometimes the Test::Builder test counter is incremented without it
1640 printing any test output, for example, when current_test() is changed.
1641 In these cases, Test::Builder doesn't know the result of the test, so
1642 its type is 'unknown'.  These details for these tests are filled in.
1643 They are considered ok, but the name and actual_ok is left undef.
1644
1645 For example "not ok 23 - hole count # TODO insufficient donuts" would
1646 result in this structure:
1647
1648     $tests[22] =    # 23 - 1, since arrays start from 0.
1649       { ok        => 1,   # logically, the test passed since it's todo
1650         actual_ok => 0,   # in absolute terms, it failed
1651         name      => 'hole count',
1652         type      => 'todo',
1653         reason    => 'insufficient donuts'
1654       };
1655
1656 =cut
1657
1658 sub details {
1659     my $self = shift;
1660     return @{ $self->{Test_Results} };
1661 }
1662
1663 =item B<todo>
1664
1665     my $todo_reason = $Test->todo;
1666     my $todo_reason = $Test->todo($pack);
1667
1668 If the current tests are considered "TODO" it will return the reason,
1669 if any.  This reason can come from a $TODO variable or the last call
1670 to C<<todo_start()>>.
1671
1672 Since a TODO test does not need a reason, this function can return an
1673 empty string even when inside a TODO block.  Use C<<$Test->in_todo>>
1674 to determine if you are currently inside a TODO block.
1675
1676 todo() is about finding the right package to look for $TODO in.  It's
1677 pretty good at guessing the right package to look at.  It first looks for
1678 the caller based on C<$Level + 1>, since C<todo()> is usually called inside
1679 a test function.  As a last resort it will use C<exported_to()>.
1680
1681 Sometimes there is some confusion about where todo() should be looking
1682 for the $TODO variable.  If you want to be sure, tell it explicitly
1683 what $pack to use.
1684
1685 =cut
1686
1687 sub todo {
1688     my( $self, $pack ) = @_;
1689
1690     return $self->{Todo} if defined $self->{Todo};
1691
1692     local $Level = $Level + 1;
1693     my $todo = $self->find_TODO($pack);
1694     return $todo if defined $todo;
1695
1696     return '';
1697 }
1698
1699 =item B<find_TODO>
1700
1701     my $todo_reason = $Test->find_TODO();
1702     my $todo_reason = $Test->find_TODO($pack):
1703
1704 Like C<<todo()>> but only returns the value of C<<$TODO>> ignoring
1705 C<<todo_start()>>.
1706
1707 =cut
1708
1709 sub find_TODO {
1710     my( $self, $pack ) = @_;
1711
1712     $pack = $pack || $self->caller(1) || $self->exported_to;
1713     return unless $pack;
1714
1715     no strict 'refs';    ## no critic
1716     return ${ $pack . '::TODO' };
1717 }
1718
1719 =item B<in_todo>
1720
1721     my $in_todo = $Test->in_todo;
1722
1723 Returns true if the test is currently inside a TODO block.
1724
1725 =cut
1726
1727 sub in_todo {
1728     my $self = shift;
1729
1730     local $Level = $Level + 1;
1731     return( defined $self->{Todo} || $self->find_TODO ) ? 1 : 0;
1732 }
1733
1734 =item B<todo_start>
1735
1736     $Test->todo_start();
1737     $Test->todo_start($message);
1738
1739 This method allows you declare all subsequent tests as TODO tests, up until
1740 the C<todo_end> method has been called.
1741
1742 The C<TODO:> and C<$TODO> syntax is generally pretty good about figuring out
1743 whether or not we're in a TODO test.  However, often we find that this is not
1744 possible to determine (such as when we want to use C<$TODO> but
1745 the tests are being executed in other packages which can't be inferred
1746 beforehand).
1747
1748 Note that you can use this to nest "todo" tests
1749
1750  $Test->todo_start('working on this');
1751  # lots of code
1752  $Test->todo_start('working on that');
1753  # more code
1754  $Test->todo_end;
1755  $Test->todo_end;
1756
1757 This is generally not recommended, but large testing systems often have weird
1758 internal needs.
1759
1760 We've tried to make this also work with the TODO: syntax, but it's not
1761 guaranteed and its use is also discouraged:
1762
1763  TODO: {
1764      local $TODO = 'We have work to do!';
1765      $Test->todo_start('working on this');
1766      # lots of code
1767      $Test->todo_start('working on that');
1768      # more code
1769      $Test->todo_end;
1770      $Test->todo_end;
1771  }
1772
1773 Pick one style or another of "TODO" to be on the safe side.
1774
1775 =cut
1776
1777 sub todo_start {
1778     my $self = shift;
1779     my $message = @_ ? shift : '';
1780
1781     $self->{Start_Todo}++;
1782     if( $self->in_todo ) {
1783         push @{ $self->{Todo_Stack} } => $self->todo;
1784     }
1785     $self->{Todo} = $message;
1786
1787     return;
1788 }
1789
1790 =item C<todo_end>
1791
1792  $Test->todo_end;
1793
1794 Stops running tests as "TODO" tests.  This method is fatal if called without a
1795 preceding C<todo_start> method call.
1796
1797 =cut
1798
1799 sub todo_end {
1800     my $self = shift;
1801
1802     if( !$self->{Start_Todo} ) {
1803         $self->croak('todo_end() called without todo_start()');
1804     }
1805
1806     $self->{Start_Todo}--;
1807
1808     if( $self->{Start_Todo} && @{ $self->{Todo_Stack} } ) {
1809         $self->{Todo} = pop @{ $self->{Todo_Stack} };
1810     }
1811     else {
1812         delete $self->{Todo};
1813     }
1814
1815     return;
1816 }
1817
1818 =item B<caller>
1819
1820     my $package = $Test->caller;
1821     my($pack, $file, $line) = $Test->caller;
1822     my($pack, $file, $line) = $Test->caller($height);
1823
1824 Like the normal caller(), except it reports according to your level().
1825
1826 C<$height> will be added to the level().
1827
1828 =cut
1829
1830 sub caller {    ## no critic (Subroutines::ProhibitBuiltinHomonyms)
1831     my( $self, $height ) = @_;
1832     $height ||= 0;
1833
1834     my @caller = CORE::caller( $self->level + $height + 1 );
1835     return wantarray ? @caller : $caller[0];
1836 }
1837
1838 =back
1839
1840 =cut
1841
1842 =begin _private
1843
1844 =over 4
1845
1846 =item B<_sanity_check>
1847
1848   $self->_sanity_check();
1849
1850 Runs a bunch of end of test sanity checks to make sure reality came
1851 through ok.  If anything is wrong it will die with a fairly friendly
1852 error message.
1853
1854 =cut
1855
1856 #'#
1857 sub _sanity_check {
1858     my $self = shift;
1859
1860     $self->_whoa( $self->{Curr_Test} < 0, 'Says here you ran a negative number of tests!' );
1861     $self->_whoa( !$self->{Have_Plan} and $self->{Curr_Test},
1862         'Somehow your tests ran without a plan!' );
1863     $self->_whoa( $self->{Curr_Test} != @{ $self->{Test_Results} },
1864         'Somehow you got a different number of results than tests ran!' );
1865
1866     return;
1867 }
1868
1869 =item B<_whoa>
1870
1871   $self->_whoa($check, $description);
1872
1873 A sanity check, similar to assert().  If the $check is true, something
1874 has gone horribly wrong.  It will die with the given $description and
1875 a note to contact the author.
1876
1877 =cut
1878
1879 sub _whoa {
1880     my( $self, $check, $desc ) = @_;
1881     if($check) {
1882         local $Level = $Level + 1;
1883         $self->croak(<<"WHOA");
1884 WHOA!  $desc
1885 This should never happen!  Please contact the author immediately!
1886 WHOA
1887     }
1888
1889     return;
1890 }
1891
1892 =item B<_my_exit>
1893
1894   _my_exit($exit_num);
1895
1896 Perl seems to have some trouble with exiting inside an END block.  5.005_03
1897 and 5.6.1 both seem to do odd things.  Instead, this function edits $?
1898 directly.  It should ONLY be called from inside an END block.  It
1899 doesn't actually exit, that's your job.
1900
1901 =cut
1902
1903 sub _my_exit {
1904     $? = $_[0];    ## no critic (Variables::RequireLocalizedPunctuationVars)
1905
1906     return 1;
1907 }
1908
1909 =back
1910
1911 =end _private
1912
1913 =cut
1914
1915 sub _ending {
1916     my $self = shift;
1917
1918     my $real_exit_code = $?;
1919     $self->_sanity_check();
1920
1921     # Don't bother with an ending if this is a forked copy.  Only the parent
1922     # should do the ending.
1923     if( $self->{Original_Pid} != $$ ) {
1924         return;
1925     }
1926
1927     # Exit if plan() was never called.  This is so "require Test::Simple"
1928     # doesn't puke.
1929     if( !$self->{Have_Plan} ) {
1930         return;
1931     }
1932
1933     # Don't do an ending if we bailed out.
1934     if( $self->{Bailed_Out} ) {
1935         return;
1936     }
1937
1938     # Figure out if we passed or failed and print helpful messages.
1939     my $test_results = $self->{Test_Results};
1940     if(@$test_results) {
1941         # The plan?  We have no plan.
1942         if( $self->{No_Plan} ) {
1943             $self->_print("1..$self->{Curr_Test}\n") unless $self->no_header;
1944             $self->{Expected_Tests} = $self->{Curr_Test};
1945         }
1946
1947         # Auto-extended arrays and elements which aren't explicitly
1948         # filled in with a shared reference will puke under 5.8.0
1949         # ithreads.  So we have to fill them in by hand. :(
1950         my $empty_result = &share( {} );
1951         for my $idx ( 0 .. $self->{Expected_Tests} - 1 ) {
1952             $test_results->[$idx] = $empty_result
1953               unless defined $test_results->[$idx];
1954         }
1955
1956         my $num_failed = grep !$_->{'ok'}, @{$test_results}[ 0 .. $self->{Curr_Test} - 1 ];
1957
1958         my $num_extra = $self->{Curr_Test} - $self->{Expected_Tests};
1959
1960         if( $num_extra != 0 ) {
1961             my $s = $self->{Expected_Tests} == 1 ? '' : 's';
1962             $self->diag(<<"FAIL");
1963 Looks like you planned $self->{Expected_Tests} test$s but ran $self->{Curr_Test}.
1964 FAIL
1965         }
1966
1967         if($num_failed) {
1968             my $num_tests = $self->{Curr_Test};
1969             my $s = $num_failed == 1 ? '' : 's';
1970
1971             my $qualifier = $num_extra == 0 ? '' : ' run';
1972
1973             $self->diag(<<"FAIL");
1974 Looks like you failed $num_failed test$s of $num_tests$qualifier.
1975 FAIL
1976         }
1977
1978         if($real_exit_code) {
1979             $self->diag(<<"FAIL");
1980 Looks like your test exited with $real_exit_code just after $self->{Curr_Test}.
1981 FAIL
1982
1983             _my_exit($real_exit_code) && return;
1984         }
1985
1986         my $exit_code;
1987         if($num_failed) {
1988             $exit_code = $num_failed <= 254 ? $num_failed : 254;
1989         }
1990         elsif( $num_extra != 0 ) {
1991             $exit_code = 255;
1992         }
1993         else {
1994             $exit_code = 0;
1995         }
1996
1997         _my_exit($exit_code) && return;
1998     }
1999     elsif( $self->{Skip_All} ) {
2000         _my_exit(0) && return;
2001     }
2002     elsif($real_exit_code) {
2003         $self->diag(<<"FAIL");
2004 Looks like your test exited with $real_exit_code before it could output anything.
2005 FAIL
2006         _my_exit($real_exit_code) && return;
2007     }
2008     else {
2009         $self->diag("No tests run!\n");
2010         _my_exit(255) && return;
2011     }
2012
2013     $self->_whoa( 1, "We fell off the end of _ending()" );
2014 }
2015
2016 END {
2017     $Test->_ending if defined $Test and !$Test->no_ending;
2018 }
2019
2020 =head1 EXIT CODES
2021
2022 If all your tests passed, Test::Builder will exit with zero (which is
2023 normal).  If anything failed it will exit with how many failed.  If
2024 you run less (or more) tests than you planned, the missing (or extras)
2025 will be considered failures.  If no tests were ever run Test::Builder
2026 will throw a warning and exit with 255.  If the test died, even after
2027 having successfully completed all its tests, it will still be
2028 considered a failure and will exit with 255.
2029
2030 So the exit codes are...
2031
2032     0                   all tests successful
2033     255                 test died or all passed but wrong # of tests run
2034     any other number    how many failed (including missing or extras)
2035
2036 If you fail more than 254 tests, it will be reported as 254.
2037
2038
2039 =head1 THREADS
2040
2041 In perl 5.8.1 and later, Test::Builder is thread-safe.  The test
2042 number is shared amongst all threads.  This means if one thread sets
2043 the test number using current_test() they will all be effected.
2044
2045 While versions earlier than 5.8.1 had threads they contain too many
2046 bugs to support.
2047
2048 Test::Builder is only thread-aware if threads.pm is loaded I<before>
2049 Test::Builder.
2050
2051 =head1 EXAMPLES
2052
2053 CPAN can provide the best examples.  Test::Simple, Test::More,
2054 Test::Exception and Test::Differences all use Test::Builder.
2055
2056 =head1 SEE ALSO
2057
2058 Test::Simple, Test::More, Test::Harness
2059
2060 =head1 AUTHORS
2061
2062 Original code by chromatic, maintained by Michael G Schwern
2063 E<lt>schwern@pobox.comE<gt>
2064
2065 =head1 COPYRIGHT
2066
2067 Copyright 2002-2008 by chromatic E<lt>chromatic@wgz.orgE<gt> and
2068                        Michael G Schwern E<lt>schwern@pobox.comE<gt>.
2069
2070 This program is free software; you can redistribute it and/or 
2071 modify it under the same terms as Perl itself.
2072
2073 See F<http://www.perl.com/perl/misc/Artistic.html>
2074
2075 =cut
2076
2077 1;
2078