This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Upgrade Test::Simple from version 1.302111 to 1.302113
[perl5.git] / cpan / Test-Simple / lib / Test / Builder.pm
1 package Test::Builder;
2
3 use 5.006;
4 use strict;
5 use warnings;
6
7 our $VERSION = '1.302113';
8
9 BEGIN {
10     if( $] < 5.008 ) {
11         require Test::Builder::IO::Scalar;
12     }
13 }
14
15 use Scalar::Util qw/blessed reftype weaken/;
16
17 use Test2::Util qw/USE_THREADS try get_tid/;
18 use Test2::API qw/context release/;
19 # Make Test::Builder thread-safe for ithreads.
20 BEGIN {
21     warn "Test::Builder was loaded after Test2 initialization, this is not recommended."
22         if Test2::API::test2_init_done() || Test2::API::test2_load_done();
23
24     if (USE_THREADS) {
25         require Test2::IPC;
26         require Test2::IPC::Driver::Files;
27         Test2::IPC::Driver::Files->import;
28         Test2::API::test2_ipc_enable_polling();
29         Test2::API::test2_no_wait(1);
30         Test2::API::test2_ipc_enable_shm();
31     }
32 }
33
34 use Test2::Event::Subtest;
35 use Test2::Hub::Subtest;
36
37 use Test::Builder::Formatter;
38 use Test::Builder::TodoDiag;
39
40 our $Level = 1;
41 our $Test = $ENV{TB_NO_EARLY_INIT} ? undef : Test::Builder->new;
42
43 sub _add_ts_hooks {
44     my $self = shift;
45
46     my $hub = $self->{Stack}->top;
47
48     # Take a reference to the hash key, we do this to avoid closing over $self
49     # which is the singleton. We use a reference because the value could change
50     # in rare cases.
51     my $epkgr = \$self->{Exported_To};
52
53     #$hub->add_context_aquire(sub {$_[0]->{level} += $Level - 1});
54
55     $hub->pre_filter(sub {
56         my ($active_hub, $e) = @_;
57
58         my $epkg = $$epkgr;
59         my $cpkg = $e->{trace} ? $e->{trace}->{frame}->[0] : undef;
60
61         no strict 'refs';
62         no warnings 'once';
63         my $todo;
64         $todo = ${"$cpkg\::TODO"} if $cpkg;
65         $todo = ${"$epkg\::TODO"} if $epkg && !$todo;
66
67         return $e unless $todo;
68
69         # Turn a diag into a todo diag
70         return Test::Builder::TodoDiag->new(%$e) if ref($e) eq 'Test2::Event::Diag';
71
72         if ($active_hub == $hub) {
73             $e->set_todo($todo) if $e->can('set_todo');
74             $e->add_amnesty({tag => 'TODO', details => $todo});
75         }
76         else {
77             $e->add_amnesty({tag => 'TODO', details => $todo, inherited => 1});
78         }
79
80         # Set todo on ok's
81         if ($e->isa('Test2::Event::Ok')) {
82             $e->set_effective_pass(1);
83
84             if (my $result = $e->get_meta(__PACKAGE__)) {
85                 $result->{reason} ||= $todo;
86                 $result->{type}   ||= 'todo';
87                 $result->{ok}       = 1;
88             }
89         }
90
91         return $e;
92     }, inherit => 1);
93 }
94
95 {
96     no warnings;
97     INIT {
98         use warnings;
99         Test2::API::test2_load() unless Test2::API::test2_in_preload();
100     }
101 }
102
103 sub new {
104     my($class) = shift;
105     unless($Test) {
106         $Test = $class->create(singleton => 1);
107
108         Test2::API::test2_add_callback_post_load(
109             sub {
110                 $Test->{Original_Pid} = $$ if !$Test->{Original_Pid} || $Test->{Original_Pid} == 0;
111                 $Test->reset(singleton => 1);
112                 $Test->_add_ts_hooks;
113             }
114         );
115
116         # Non-TB tools normally expect 0 added to the level. $Level is normally 1. So
117         # we only want the level to change if $Level != 1.
118         # TB->ctx compensates for this later.
119         Test2::API::test2_add_callback_context_aquire(sub { $_[0]->{level} += $Level - 1 });
120
121         Test2::API::test2_add_callback_exit(sub { $Test->_ending(@_) });
122
123         Test2::API::test2_ipc()->set_no_fatal(1) if USE_THREADS;
124     }
125     return $Test;
126 }
127
128 sub create {
129     my $class = shift;
130     my %params = @_;
131
132     my $self = bless {}, $class;
133     if ($params{singleton}) {
134         $self->{Stack} = Test2::API::test2_stack();
135     }
136     else {
137         $self->{Stack} = Test2::API::Stack->new;
138         $self->{Stack}->new_hub(
139             formatter => Test::Builder::Formatter->new,
140             ipc       => Test2::API::test2_ipc(),
141         );
142
143         $self->reset(%params);
144         $self->_add_ts_hooks;
145     }
146
147     return $self;
148 }
149
150 sub ctx {
151     my $self = shift;
152     context(
153         # 1 for our frame, another for the -1 off of $Level in our hook at the top.
154         level   => 2,
155         fudge   => 1,
156         stack   => $self->{Stack},
157         hub     => $self->{Hub},
158         wrapped => 1,
159         @_
160     );
161 }
162
163 sub parent {
164     my $self = shift;
165     my $ctx = $self->ctx;
166     my $chub = $self->{Hub} || $ctx->hub;
167     $ctx->release;
168
169     my $meta = $chub->meta(__PACKAGE__, {});
170     my $parent = $meta->{parent};
171
172     return undef unless $parent;
173
174     return bless {
175         Original_Pid => $$,
176         Stack => $self->{Stack},
177         Hub => $parent,
178     }, blessed($self);
179 }
180
181 sub child {
182     my( $self, $name ) = @_;
183
184     $name ||= "Child of " . $self->name;
185     my $ctx = $self->ctx;
186
187     my $parent = $ctx->hub;
188     my $pmeta = $parent->meta(__PACKAGE__, {});
189     $self->croak("You already have a child named ($pmeta->{child}) running")
190         if $pmeta->{child};
191
192     $pmeta->{child} = $name;
193
194     # Clear $TODO for the child.
195     my $orig_TODO = $self->find_TODO(undef, 1, undef);
196
197     my $subevents = [];
198
199     my $hub = $ctx->stack->new_hub(
200         class => 'Test2::Hub::Subtest',
201     );
202
203     $hub->pre_filter(sub {
204         my ($active_hub, $e) = @_;
205
206         # Turn a diag into a todo diag
207         return Test::Builder::TodoDiag->new(%$e) if ref($e) eq 'Test2::Event::Diag';
208
209         return $e;
210     }, inherit => 1) if $orig_TODO;
211
212     $hub->listen(sub { push @$subevents => $_[1] });
213
214     $hub->set_nested( $parent->nested + 1 );
215
216     my $meta = $hub->meta(__PACKAGE__, {});
217     $meta->{Name} = $name;
218     $meta->{TODO} = $orig_TODO;
219     $meta->{TODO_PKG} = $ctx->trace->package;
220     $meta->{parent} = $parent;
221     $meta->{Test_Results} = [];
222     $meta->{subevents} = $subevents;
223     $meta->{subtest_id} = $hub->id;
224     $meta->{subtest_buffered} = $parent->format ? 0 : 1;
225
226     $self->_add_ts_hooks;
227
228     $ctx->release;
229     return bless { Original_Pid => $$, Stack => $self->{Stack}, Hub => $hub, no_log_results => $self->{no_log_results} }, blessed($self);
230 }
231
232 sub finalize {
233     my $self = shift;
234     my $ok = 1;
235     ($ok) = @_ if @_;
236
237     my $st_ctx = $self->ctx;
238     my $chub = $self->{Hub} || return $st_ctx->release;
239
240     my $meta = $chub->meta(__PACKAGE__, {});
241     if ($meta->{child}) {
242         $self->croak("Can't call finalize() with child ($meta->{child}) active");
243     }
244
245     local $? = 0;     # don't fail if $subtests happened to set $? nonzero
246
247     $self->{Stack}->pop($chub);
248
249     $self->find_TODO($meta->{TODO_PKG}, 1, $meta->{TODO});
250
251     my $parent = $self->parent;
252     my $ctx = $parent->ctx;
253     my $trace = $ctx->trace;
254     delete $ctx->hub->meta(__PACKAGE__, {})->{child};
255
256     $chub->finalize($trace->snapshot(hid => $chub->hid, nested => $chub->nested), 1)
257         if $ok
258         && $chub->count
259         && !$chub->no_ending
260         && !$chub->ended;
261
262     my $plan   = $chub->plan || 0;
263     my $count  = $chub->count;
264     my $failed = $chub->failed;
265     my $passed = $chub->is_passing;
266
267     my $num_extra = $plan =~ m/\D/ ? 0 : $count - $plan;
268     if ($count && $num_extra != 0) {
269         my $s = $plan == 1 ? '' : 's';
270         $st_ctx->diag(<<"FAIL");
271 Looks like you planned $plan test$s but ran $count.
272 FAIL
273     }
274
275     if ($failed) {
276         my $s = $failed == 1 ? '' : 's';
277
278         my $qualifier = $num_extra == 0 ? '' : ' run';
279
280         $st_ctx->diag(<<"FAIL");
281 Looks like you failed $failed test$s of $count$qualifier.
282 FAIL
283     }
284
285     if (!$passed && !$failed && $count && !$num_extra) {
286         $st_ctx->diag(<<"FAIL");
287 All assertions inside the subtest passed, but errors were encountered.
288 FAIL
289     }
290
291     $st_ctx->release;
292
293     unless ($chub->bailed_out) {
294         my $plan = $chub->plan;
295         if ( $plan && $plan eq 'SKIP' ) {
296             $parent->skip($chub->skip_reason, $meta->{Name});
297         }
298         elsif ( !$chub->count ) {
299             $parent->ok( 0, sprintf q[No tests run for subtest "%s"], $meta->{Name} );
300         }
301         else {
302             $parent->{subevents}  = $meta->{subevents};
303             $parent->{subtest_id} = $meta->{subtest_id};
304             $parent->{subtest_buffered} = $meta->{subtest_buffered};
305             $parent->ok( $chub->is_passing, $meta->{Name} );
306         }
307     }
308
309     $ctx->release;
310     return $chub->is_passing;
311 }
312
313 sub subtest {
314     my $self = shift;
315     my ($name, $code, @args) = @_;
316     my $ctx = $self->ctx;
317     $ctx->throw("subtest()'s second argument must be a code ref")
318         unless $code && reftype($code) eq 'CODE';
319
320     $name ||= "Child of " . $self->name;
321
322     $ctx->note("Subtest: $name");
323
324     my $child = $self->child($name);
325
326     my $start_pid = $$;
327     my $st_ctx;
328     my ($ok, $err, $finished, $child_error);
329     T2_SUBTEST_WRAPPER: {
330         my $ctx = $self->ctx;
331         $st_ctx = $ctx->snapshot;
332         $ctx->release;
333         $ok = eval { local $Level = 1; $code->(@args); 1 };
334         ($err, $child_error) = ($@, $?);
335
336         # They might have done 'BEGIN { skip_all => "whatever" }'
337         if (!$ok && $err =~ m/Label not found for "last T2_SUBTEST_WRAPPER"/ || (blessed($err) && blessed($err) eq 'Test::Builder::Exception')) {
338             $ok  = undef;
339             $err = undef;
340         }
341         else {
342             $finished = 1;
343         }
344     }
345
346     if ($start_pid != $$ && !$INC{'Test2/IPC.pm'}) {
347         warn $ok ? "Forked inside subtest, but subtest never finished!\n" : $err;
348         exit 255;
349     }
350
351     my $trace = $ctx->trace;
352
353     if (!$finished) {
354         if(my $bailed = $st_ctx->hub->bailed_out) {
355             my $chub = $child->{Hub};
356             $self->{Stack}->pop($chub);
357             $ctx->bail($bailed->reason);
358         }
359         my $code = $st_ctx->hub->exit_code;
360         $ok = !$code;
361         $err = "Subtest ended with exit code $code" if $code;
362     }
363
364     my $st_hub  = $st_ctx->hub;
365     my $plan  = $st_hub->plan;
366     my $count = $st_hub->count;
367
368     if (!$count && (!defined($plan) || "$plan" ne 'SKIP')) {
369         $st_ctx->plan(0) unless defined $plan;
370         $st_ctx->diag('No tests run!');
371     }
372
373     $child->finalize($st_ctx->trace);
374
375     $ctx->release;
376
377     die $err unless $ok;
378
379     $? = $child_error if defined $child_error;
380
381     return $st_hub->is_passing;
382 }
383
384 sub name {
385     my $self = shift;
386     my $ctx = $self->ctx;
387     release $ctx, $ctx->hub->meta(__PACKAGE__, {})->{Name};
388 }
389
390 sub reset {    ## no critic (Subroutines::ProhibitBuiltinHomonyms)
391     my ($self, %params) = @_;
392
393     Test2::API::test2_set_is_end(0);
394
395     # We leave this a global because it has to be localized and localizing
396     # hash keys is just asking for pain.  Also, it was documented.
397     $Level = 1;
398
399     $self->{no_log_results} = $ENV{TEST_NO_LOG_RESULTS} ? 1 : 0
400         unless $params{singleton};
401
402     $self->{Original_Pid} = Test2::API::test2_in_preload() ? -1 : $$;
403
404     my $ctx = $self->ctx;
405     my $hub = $ctx->hub;
406     $ctx->release;
407     unless ($params{singleton}) {
408         $hub->reset_state();
409         $hub->_tb_reset();
410     }
411
412     $ctx = $self->ctx;
413
414     my $meta = $ctx->hub->meta(__PACKAGE__, {});
415     %$meta = (
416         Name         => $0,
417         Ending       => 0,
418         Done_Testing => undef,
419         Skip_All     => 0,
420         Test_Results => [],
421         parent       => $meta->{parent},
422     );
423
424     $self->{Exported_To} = undef unless $params{singleton};
425
426     $self->{Orig_Handles} ||= do {
427         my $format = $ctx->hub->format;
428         my $out;
429         if ($format && $format->isa('Test2::Formatter::TAP')) {
430             $out = $format->handles;
431         }
432         $out ? [@$out] : [];
433     };
434
435     $self->use_numbers(1);
436     $self->no_header(0) unless $params{singleton};
437     $self->no_ending(0) unless $params{singleton};
438     $self->reset_outputs;
439
440     $ctx->release;
441
442     return;
443 }
444
445
446 my %plan_cmds = (
447     no_plan  => \&no_plan,
448     skip_all => \&skip_all,
449     tests    => \&_plan_tests,
450 );
451
452 sub plan {
453     my( $self, $cmd, $arg ) = @_;
454
455     return unless $cmd;
456
457     my $ctx = $self->ctx;
458     my $hub = $ctx->hub;
459
460     $ctx->throw("You tried to plan twice") if $hub->plan;
461
462     local $Level = $Level + 1;
463
464     if( my $method = $plan_cmds{$cmd} ) {
465         local $Level = $Level + 1;
466         $self->$method($arg);
467     }
468     else {
469         my @args = grep { defined } ( $cmd, $arg );
470         $ctx->throw("plan() doesn't understand @args");
471     }
472
473     release $ctx, 1;
474 }
475
476
477 sub _plan_tests {
478     my($self, $arg) = @_;
479
480     my $ctx = $self->ctx;
481
482     if($arg) {
483         local $Level = $Level + 1;
484         $self->expected_tests($arg);
485     }
486     elsif( !defined $arg ) {
487         $ctx->throw("Got an undefined number of tests");
488     }
489     else {
490         $ctx->throw("You said to run 0 tests");
491     }
492
493     $ctx->release;
494 }
495
496
497 sub expected_tests {
498     my $self = shift;
499     my($max) = @_;
500
501     my $ctx = $self->ctx;
502
503     if(@_) {
504         $self->croak("Number of tests must be a positive integer.  You gave it '$max'")
505           unless $max =~ /^\+?\d+$/;
506
507         $ctx->plan($max);
508     }
509
510     my $hub = $ctx->hub;
511
512     $ctx->release;
513
514     my $plan = $hub->plan;
515     return 0 unless $plan;
516     return 0 if $plan =~ m/\D/;
517     return $plan;
518 }
519
520
521 sub no_plan {
522     my($self, $arg) = @_;
523
524     my $ctx = $self->ctx;
525
526     if (defined $ctx->hub->plan) {
527         warn "Plan already set, no_plan() is a no-op, this will change to a hard failure in the future.";
528         $ctx->release;
529         return;
530     }
531
532     $ctx->alert("no_plan takes no arguments") if $arg;
533
534     $ctx->hub->plan('NO PLAN');
535
536     release $ctx, 1;
537 }
538
539
540 sub done_testing {
541     my($self, $num_tests) = @_;
542
543     my $ctx = $self->ctx;
544
545     my $meta = $ctx->hub->meta(__PACKAGE__, {});
546
547     if ($meta->{Done_Testing}) {
548         my ($file, $line) = @{$meta->{Done_Testing}}[1,2];
549         local $ctx->hub->{ended}; # OMG This is awful.
550         $self->ok(0, "done_testing() was already called at $file line $line");
551         $ctx->release;
552         return;
553     }
554     $meta->{Done_Testing} = [$ctx->trace->call];
555
556     my $plan = $ctx->hub->plan;
557     my $count = $ctx->hub->count;
558
559     # If done_testing() specified the number of tests, shut off no_plan
560     if( defined $num_tests ) {
561         $ctx->plan($num_tests) if !$plan || $plan eq 'NO PLAN';
562     }
563     elsif ($count && defined $num_tests && $count != $num_tests) {
564         $self->ok(0, "planned to run @{[ $self->expected_tests ]} but done_testing() expects $num_tests");
565     }
566     else {
567         $num_tests = $self->current_test;
568     }
569
570     if( $self->expected_tests && $num_tests != $self->expected_tests ) {
571         $self->ok(0, "planned to run @{[ $self->expected_tests ]} ".
572                      "but done_testing() expects $num_tests");
573     }
574
575     $ctx->plan($num_tests) if $ctx->hub->plan && $ctx->hub->plan eq 'NO PLAN';
576
577     $ctx->hub->finalize($ctx->trace, 1);
578
579     release $ctx, 1;
580 }
581
582
583 sub has_plan {
584     my $self = shift;
585
586     my $ctx = $self->ctx;
587     my $plan = $ctx->hub->plan;
588     $ctx->release;
589
590     return( $plan ) if $plan && $plan !~ m/\D/;
591     return('no_plan') if $plan && $plan eq 'NO PLAN';
592     return(undef);
593 }
594
595
596 sub skip_all {
597     my( $self, $reason ) = @_;
598
599     my $ctx = $self->ctx;
600
601     $ctx->hub->meta(__PACKAGE__, {})->{Skip_All} = $reason || 1;
602
603     # Work around old perl bug
604     if ($] < 5.020000) {
605         my $begin = 0;
606         my $level = 0;
607         while (my @call = caller($level++)) {
608             last unless @call && $call[0];
609             next unless $call[3] =~ m/::BEGIN$/;
610             $begin++;
611             last;
612         }
613         # HACK!
614         die 'Label not found for "last T2_SUBTEST_WRAPPER"' if $begin && $ctx->hub->meta(__PACKAGE__, {})->{parent};
615     }
616
617     $ctx->plan(0, SKIP => $reason);
618 }
619
620
621 sub exported_to {
622     my( $self, $pack ) = @_;
623
624     if( defined $pack ) {
625         $self->{Exported_To} = $pack;
626     }
627     return $self->{Exported_To};
628 }
629
630
631 sub ok {
632     my( $self, $test, $name ) = @_;
633
634     my $ctx = $self->ctx;
635
636     # $test might contain an object which we don't want to accidentally
637     # store, so we turn it into a boolean.
638     $test = $test ? 1 : 0;
639
640     # In case $name is a string overloaded object, force it to stringify.
641     no  warnings qw/uninitialized numeric/;
642     $name = "$name" if defined $name;
643
644     # Profiling showed that the regex here was a huge time waster, doing the
645     # numeric addition first cuts our profile time from ~300ms to ~50ms
646     $self->diag(<<"    ERR") if 0 + $name && $name =~ /^[\d\s]+$/;
647     You named your test '$name'.  You shouldn't use numbers for your test names.
648     Very confusing.
649     ERR
650     use warnings qw/uninitialized numeric/;
651
652     my $trace = $ctx->{trace};
653     my $hub   = $ctx->{hub};
654
655     my $result = {
656         ok => $test,
657         actual_ok => $test,
658         reason => '',
659         type => '',
660         (name => defined($name) ? $name : ''),
661     };
662
663     $hub->{_meta}->{+__PACKAGE__}->{Test_Results}[ $hub->{count} ] = $result unless $self->{no_log_results};
664
665     my $orig_name = $name;
666
667     my @attrs;
668     my $subevents  = delete $self->{subevents};
669     my $subtest_id = delete $self->{subtest_id};
670     my $subtest_buffered = delete $self->{subtest_buffered};
671     my $epkg = 'Test2::Event::Ok';
672     if ($subevents) {
673         $epkg = 'Test2::Event::Subtest';
674         push @attrs => (subevents => $subevents, subtest_id => $subtest_id, buffered => $subtest_buffered);
675     }
676
677     my $e = bless {
678         trace => bless( {%$trace}, 'Test2::EventFacet::Trace'),
679         pass  => $test,
680         name  => $name,
681         _meta => {'Test::Builder' => $result},
682         effective_pass => $test,
683         @attrs,
684     }, $epkg;
685     $hub->send($e);
686
687     $self->_ok_debug($trace, $orig_name) unless($test);
688
689     $ctx->release;
690     return $test;
691 }
692
693 sub _ok_debug {
694     my $self = shift;
695     my ($trace, $orig_name) = @_;
696
697     my $is_todo = defined($self->todo);
698
699     my $msg = $is_todo ? "Failed (TODO)" : "Failed";
700
701     my (undef, $file, $line) = $trace->call;
702     if (defined $orig_name) {
703         $self->diag(qq[  $msg test '$orig_name'\n  at $file line $line.\n]);
704     }
705     else {
706         $self->diag(qq[  $msg test at $file line $line.\n]);
707     }
708 }
709
710 sub _diag_fh {
711     my $self = shift;
712     local $Level = $Level + 1;
713     return $self->in_todo ? $self->todo_output : $self->failure_output;
714 }
715
716 sub _unoverload {
717     my ($self, $type, $thing) = @_;
718
719     return unless ref $$thing;
720     return unless blessed($$thing) || scalar $self->_try(sub{ $$thing->isa('UNIVERSAL') });
721     {
722         local ($!, $@);
723         require overload;
724     }
725     my $string_meth = overload::Method( $$thing, $type ) || return;
726     $$thing = $$thing->$string_meth();
727 }
728
729 sub _unoverload_str {
730     my $self = shift;
731
732     $self->_unoverload( q[""], $_ ) for @_;
733 }
734
735 sub _unoverload_num {
736     my $self = shift;
737
738     $self->_unoverload( '0+', $_ ) for @_;
739
740     for my $val (@_) {
741         next unless $self->_is_dualvar($$val);
742         $$val = $$val + 0;
743     }
744 }
745
746 # This is a hack to detect a dualvar such as $!
747 sub _is_dualvar {
748     my( $self, $val ) = @_;
749
750     # Objects are not dualvars.
751     return 0 if ref $val;
752
753     no warnings 'numeric';
754     my $numval = $val + 0;
755     return ($numval != 0 and $numval ne $val ? 1 : 0);
756 }
757
758
759 sub is_eq {
760     my( $self, $got, $expect, $name ) = @_;
761
762     my $ctx = $self->ctx;
763
764     local $Level = $Level + 1;
765
766     if( !defined $got || !defined $expect ) {
767         # undef only matches undef and nothing else
768         my $test = !defined $got && !defined $expect;
769
770         $self->ok( $test, $name );
771         $self->_is_diag( $got, 'eq', $expect ) unless $test;
772         $ctx->release;
773         return $test;
774     }
775
776     release $ctx, $self->cmp_ok( $got, 'eq', $expect, $name );
777 }
778
779
780 sub is_num {
781     my( $self, $got, $expect, $name ) = @_;
782     my $ctx = $self->ctx;
783     local $Level = $Level + 1;
784
785     if( !defined $got || !defined $expect ) {
786         # undef only matches undef and nothing else
787         my $test = !defined $got && !defined $expect;
788
789         $self->ok( $test, $name );
790         $self->_is_diag( $got, '==', $expect ) unless $test;
791         $ctx->release;
792         return $test;
793     }
794
795     release $ctx, $self->cmp_ok( $got, '==', $expect, $name );
796 }
797
798
799 sub _diag_fmt {
800     my( $self, $type, $val ) = @_;
801
802     if( defined $$val ) {
803         if( $type eq 'eq' or $type eq 'ne' ) {
804             # quote and force string context
805             $$val = "'$$val'";
806         }
807         else {
808             # force numeric context
809             $self->_unoverload_num($val);
810         }
811     }
812     else {
813         $$val = 'undef';
814     }
815
816     return;
817 }
818
819
820 sub _is_diag {
821     my( $self, $got, $type, $expect ) = @_;
822
823     $self->_diag_fmt( $type, $_ ) for \$got, \$expect;
824
825     local $Level = $Level + 1;
826     return $self->diag(<<"DIAGNOSTIC");
827          got: $got
828     expected: $expect
829 DIAGNOSTIC
830
831 }
832
833 sub _isnt_diag {
834     my( $self, $got, $type ) = @_;
835
836     $self->_diag_fmt( $type, \$got );
837
838     local $Level = $Level + 1;
839     return $self->diag(<<"DIAGNOSTIC");
840          got: $got
841     expected: anything else
842 DIAGNOSTIC
843 }
844
845
846 sub isnt_eq {
847     my( $self, $got, $dont_expect, $name ) = @_;
848     my $ctx = $self->ctx;
849     local $Level = $Level + 1;
850
851     if( !defined $got || !defined $dont_expect ) {
852         # undef only matches undef and nothing else
853         my $test = defined $got || defined $dont_expect;
854
855         $self->ok( $test, $name );
856         $self->_isnt_diag( $got, 'ne' ) unless $test;
857         $ctx->release;
858         return $test;
859     }
860
861     release $ctx, $self->cmp_ok( $got, 'ne', $dont_expect, $name );
862 }
863
864 sub isnt_num {
865     my( $self, $got, $dont_expect, $name ) = @_;
866     my $ctx = $self->ctx;
867     local $Level = $Level + 1;
868
869     if( !defined $got || !defined $dont_expect ) {
870         # undef only matches undef and nothing else
871         my $test = defined $got || defined $dont_expect;
872
873         $self->ok( $test, $name );
874         $self->_isnt_diag( $got, '!=' ) unless $test;
875         $ctx->release;
876         return $test;
877     }
878
879     release $ctx, $self->cmp_ok( $got, '!=', $dont_expect, $name );
880 }
881
882
883 sub like {
884     my( $self, $thing, $regex, $name ) = @_;
885     my $ctx = $self->ctx;
886
887     local $Level = $Level + 1;
888
889     release $ctx, $self->_regex_ok( $thing, $regex, '=~', $name );
890 }
891
892 sub unlike {
893     my( $self, $thing, $regex, $name ) = @_;
894     my $ctx = $self->ctx;
895
896     local $Level = $Level + 1;
897
898     release $ctx, $self->_regex_ok( $thing, $regex, '!~', $name );
899 }
900
901
902 my %numeric_cmps = map { ( $_, 1 ) } ( "<", "<=", ">", ">=", "==", "!=", "<=>" );
903
904 # Bad, these are not comparison operators. Should we include more?
905 my %cmp_ok_bl = map { ( $_, 1 ) } ( "=", "+=", ".=", "x=", "^=", "|=", "||=", "&&=", "...");
906
907 sub cmp_ok {
908     my( $self, $got, $type, $expect, $name ) = @_;
909     my $ctx = $self->ctx;
910
911     if ($cmp_ok_bl{$type}) {
912         $ctx->throw("$type is not a valid comparison operator in cmp_ok()");
913     }
914
915     my ($test, $succ);
916     my $error;
917     {
918         ## no critic (BuiltinFunctions::ProhibitStringyEval)
919
920         local( $@, $!, $SIG{__DIE__} );    # isolate eval
921
922         my($pack, $file, $line) = $ctx->trace->call();
923
924         # This is so that warnings come out at the caller's level
925         $succ = eval qq[
926 #line $line "(eval in cmp_ok) $file"
927 \$test = (\$got $type \$expect);
928 1;
929 ];
930         $error = $@;
931     }
932     local $Level = $Level + 1;
933     my $ok = $self->ok( $test, $name );
934
935     # Treat overloaded objects as numbers if we're asked to do a
936     # numeric comparison.
937     my $unoverload
938       = $numeric_cmps{$type}
939       ? '_unoverload_num'
940       : '_unoverload_str';
941
942     $self->diag(<<"END") unless $succ;
943 An error occurred while using $type:
944 ------------------------------------
945 $error
946 ------------------------------------
947 END
948
949     unless($ok) {
950         $self->$unoverload( \$got, \$expect );
951
952         if( $type =~ /^(eq|==)$/ ) {
953             $self->_is_diag( $got, $type, $expect );
954         }
955         elsif( $type =~ /^(ne|!=)$/ ) {
956             no warnings;
957             my $eq = ($got eq $expect || $got == $expect)
958                 && (
959                     (defined($got) xor defined($expect))
960                  || (length($got)  !=  length($expect))
961                 );
962             use warnings;
963
964             if ($eq) {
965                 $self->_cmp_diag( $got, $type, $expect );
966             }
967             else {
968                 $self->_isnt_diag( $got, $type );
969             }
970         }
971         else {
972             $self->_cmp_diag( $got, $type, $expect );
973         }
974     }
975     return release $ctx, $ok;
976 }
977
978 sub _cmp_diag {
979     my( $self, $got, $type, $expect ) = @_;
980
981     $got    = defined $got    ? "'$got'"    : 'undef';
982     $expect = defined $expect ? "'$expect'" : 'undef';
983
984     local $Level = $Level + 1;
985     return $self->diag(<<"DIAGNOSTIC");
986     $got
987         $type
988     $expect
989 DIAGNOSTIC
990 }
991
992 sub _caller_context {
993     my $self = shift;
994
995     my( $pack, $file, $line ) = $self->caller(1);
996
997     my $code = '';
998     $code .= "#line $line $file\n" if defined $file and defined $line;
999
1000     return $code;
1001 }
1002
1003
1004 sub BAIL_OUT {
1005     my( $self, $reason ) = @_;
1006
1007     my $ctx = $self->ctx;
1008
1009     $self->{Bailed_Out} = 1;
1010
1011     $ctx->bail($reason);
1012 }
1013
1014
1015 {
1016     no warnings 'once';
1017     *BAILOUT = \&BAIL_OUT;
1018 }
1019
1020 sub skip {
1021     my( $self, $why, $name ) = @_;
1022     $why ||= '';
1023     $name = '' unless defined $name;
1024     $self->_unoverload_str( \$why );
1025
1026     my $ctx = $self->ctx;
1027
1028     $ctx->hub->meta(__PACKAGE__, {})->{Test_Results}[ $ctx->hub->count ] = {
1029         'ok'      => 1,
1030         actual_ok => 1,
1031         name      => $name,
1032         type      => 'skip',
1033         reason    => $why,
1034     } unless $self->{no_log_results};
1035
1036     $name =~ s|#|\\#|g;    # # in a name can confuse Test::Harness.
1037     $name =~ s{\n}{\n# }sg;
1038     $why =~ s{\n}{\n# }sg;
1039
1040     my $tctx = $ctx->snapshot;
1041     $tctx->skip('', $why);
1042
1043     return release $ctx, 1;
1044 }
1045
1046
1047 sub todo_skip {
1048     my( $self, $why ) = @_;
1049     $why ||= '';
1050
1051     my $ctx = $self->ctx;
1052
1053     $ctx->hub->meta(__PACKAGE__, {})->{Test_Results}[ $ctx->hub->count ] = {
1054         'ok'      => 1,
1055         actual_ok => 0,
1056         name      => '',
1057         type      => 'todo_skip',
1058         reason    => $why,
1059     } unless $self->{no_log_results};
1060
1061     $why =~ s{\n}{\n# }sg;
1062     my $tctx = $ctx->snapshot;
1063     $tctx->send_event( 'Skip', todo => $why, todo_diag => 1, reason => $why, pass => 0);
1064
1065     return release $ctx, 1;
1066 }
1067
1068
1069 sub maybe_regex {
1070     my( $self, $regex ) = @_;
1071     my $usable_regex = undef;
1072
1073     return $usable_regex unless defined $regex;
1074
1075     my( $re, $opts );
1076
1077     # Check for qr/foo/
1078     if( _is_qr($regex) ) {
1079         $usable_regex = $regex;
1080     }
1081     # Check for '/foo/' or 'm,foo,'
1082     elsif(( $re, $opts )        = $regex =~ m{^ /(.*)/ (\w*) $ }sx              or
1083           ( undef, $re, $opts ) = $regex =~ m,^ m([^\w\s]) (.+) \1 (\w*) $,sx
1084     )
1085     {
1086         $usable_regex = length $opts ? "(?$opts)$re" : $re;
1087     }
1088
1089     return $usable_regex;
1090 }
1091
1092 sub _is_qr {
1093     my $regex = shift;
1094
1095     # is_regexp() checks for regexes in a robust manner, say if they're
1096     # blessed.
1097     return re::is_regexp($regex) if defined &re::is_regexp;
1098     return ref $regex eq 'Regexp';
1099 }
1100
1101 sub _regex_ok {
1102     my( $self, $thing, $regex, $cmp, $name ) = @_;
1103
1104     my $ok           = 0;
1105     my $usable_regex = $self->maybe_regex($regex);
1106     unless( defined $usable_regex ) {
1107         local $Level = $Level + 1;
1108         $ok = $self->ok( 0, $name );
1109         $self->diag("    '$regex' doesn't look much like a regex to me.");
1110         return $ok;
1111     }
1112
1113     {
1114         my $test;
1115         my $context = $self->_caller_context;
1116
1117         {
1118             ## no critic (BuiltinFunctions::ProhibitStringyEval)
1119
1120             local( $@, $!, $SIG{__DIE__} );    # isolate eval
1121
1122             # No point in issuing an uninit warning, they'll see it in the diagnostics
1123             no warnings 'uninitialized';
1124
1125             $test = eval $context . q{$test = $thing =~ /$usable_regex/ ? 1 : 0};
1126         }
1127
1128         $test = !$test if $cmp eq '!~';
1129
1130         local $Level = $Level + 1;
1131         $ok = $self->ok( $test, $name );
1132     }
1133
1134     unless($ok) {
1135         $thing = defined $thing ? "'$thing'" : 'undef';
1136         my $match = $cmp eq '=~' ? "doesn't match" : "matches";
1137
1138         local $Level = $Level + 1;
1139         $self->diag( sprintf <<'DIAGNOSTIC', $thing, $match, $regex );
1140                   %s
1141     %13s '%s'
1142 DIAGNOSTIC
1143
1144     }
1145
1146     return $ok;
1147 }
1148
1149
1150 sub is_fh {
1151     my $self     = shift;
1152     my $maybe_fh = shift;
1153     return 0 unless defined $maybe_fh;
1154
1155     return 1 if ref $maybe_fh  eq 'GLOB';    # its a glob ref
1156     return 1 if ref \$maybe_fh eq 'GLOB';    # its a glob
1157
1158     return eval { $maybe_fh->isa("IO::Handle") } ||
1159            eval { tied($maybe_fh)->can('TIEHANDLE') };
1160 }
1161
1162
1163 sub level {
1164     my( $self, $level ) = @_;
1165
1166     if( defined $level ) {
1167         $Level = $level;
1168     }
1169     return $Level;
1170 }
1171
1172
1173 sub use_numbers {
1174     my( $self, $use_nums ) = @_;
1175
1176     my $ctx = $self->ctx;
1177     my $format = $ctx->hub->format;
1178     unless ($format && $format->can('no_numbers') && $format->can('set_no_numbers')) {
1179         warn "The current formatter does not support 'use_numbers'" if $format;
1180         return release $ctx, 0;
1181     }
1182
1183     $format->set_no_numbers(!$use_nums) if defined $use_nums;
1184
1185     return release $ctx, $format->no_numbers ? 0 : 1;
1186 }
1187
1188 BEGIN {
1189     for my $method (qw(no_header no_diag)) {
1190         my $set = "set_$method";
1191         my $code = sub {
1192             my( $self, $no ) = @_;
1193
1194             my $ctx = $self->ctx;
1195             my $format = $ctx->hub->format;
1196             unless ($format && $format->can($set)) {
1197                 warn "The current formatter does not support '$method'" if $format;
1198                 $ctx->release;
1199                 return
1200             }
1201
1202             $format->$set($no) if defined $no;
1203
1204             return release $ctx, $format->$method ? 1 : 0;
1205         };
1206
1207         no strict 'refs';    ## no critic
1208         *$method = $code;
1209     }
1210 }
1211
1212 sub no_ending {
1213     my( $self, $no ) = @_;
1214
1215     my $ctx = $self->ctx;
1216
1217     $ctx->hub->set_no_ending($no) if defined $no;
1218
1219     return release $ctx, $ctx->hub->no_ending;
1220 }
1221
1222 sub diag {
1223     my $self = shift;
1224     return unless @_;
1225
1226     my $text = join '' => map {defined($_) ? $_ : 'undef'} @_;
1227
1228     if (Test2::API::test2_in_preload()) {
1229         chomp($text);
1230         $text =~ s/^/# /msg;
1231         print STDERR $text, "\n";
1232         return 0;
1233     }
1234
1235     my $ctx = $self->ctx;
1236     $ctx->diag($text);
1237     $ctx->release;
1238     return 0;
1239 }
1240
1241
1242 sub note {
1243     my $self = shift;
1244     return unless @_;
1245
1246     my $text = join '' => map {defined($_) ? $_ : 'undef'} @_;
1247
1248     if (Test2::API::test2_in_preload()) {
1249         chomp($text);
1250         $text =~ s/^/# /msg;
1251         print STDOUT $text, "\n";
1252         return 0;
1253     }
1254
1255     my $ctx = $self->ctx;
1256     $ctx->note($text);
1257     $ctx->release;
1258     return 0;
1259 }
1260
1261
1262 sub explain {
1263     my $self = shift;
1264
1265     local ($@, $!);
1266     require Data::Dumper;
1267
1268     return map {
1269         ref $_
1270           ? do {
1271             my $dumper = Data::Dumper->new( [$_] );
1272             $dumper->Indent(1)->Terse(1);
1273             $dumper->Sortkeys(1) if $dumper->can("Sortkeys");
1274             $dumper->Dump;
1275           }
1276           : $_
1277     } @_;
1278 }
1279
1280
1281 sub output {
1282     my( $self, $fh ) = @_;
1283
1284     my $ctx = $self->ctx;
1285     my $format = $ctx->hub->format;
1286     $ctx->release;
1287     return unless $format && $format->isa('Test2::Formatter::TAP');
1288
1289     $format->handles->[Test2::Formatter::TAP::OUT_STD()] = $self->_new_fh($fh)
1290         if defined $fh;
1291
1292     return $format->handles->[Test2::Formatter::TAP::OUT_STD()];
1293 }
1294
1295 sub failure_output {
1296     my( $self, $fh ) = @_;
1297
1298     my $ctx = $self->ctx;
1299     my $format = $ctx->hub->format;
1300     $ctx->release;
1301     return unless $format && $format->isa('Test2::Formatter::TAP');
1302
1303     $format->handles->[Test2::Formatter::TAP::OUT_ERR()] = $self->_new_fh($fh)
1304         if defined $fh;
1305
1306     return $format->handles->[Test2::Formatter::TAP::OUT_ERR()];
1307 }
1308
1309 sub todo_output {
1310     my( $self, $fh ) = @_;
1311
1312     my $ctx = $self->ctx;
1313     my $format = $ctx->hub->format;
1314     $ctx->release;
1315     return unless $format && $format->isa('Test::Builder::Formatter');
1316
1317     $format->handles->[Test::Builder::Formatter::OUT_TODO()] = $self->_new_fh($fh)
1318         if defined $fh;
1319
1320     return $format->handles->[Test::Builder::Formatter::OUT_TODO()];
1321 }
1322
1323 sub _new_fh {
1324     my $self = shift;
1325     my($file_or_fh) = shift;
1326
1327     my $fh;
1328     if( $self->is_fh($file_or_fh) ) {
1329         $fh = $file_or_fh;
1330     }
1331     elsif( ref $file_or_fh eq 'SCALAR' ) {
1332         # Scalar refs as filehandles was added in 5.8.
1333         if( $] >= 5.008 ) {
1334             open $fh, ">>", $file_or_fh
1335               or $self->croak("Can't open scalar ref $file_or_fh: $!");
1336         }
1337         # Emulate scalar ref filehandles with a tie.
1338         else {
1339             $fh = Test::Builder::IO::Scalar->new($file_or_fh)
1340               or $self->croak("Can't tie scalar ref $file_or_fh");
1341         }
1342     }
1343     else {
1344         open $fh, ">", $file_or_fh
1345           or $self->croak("Can't open test output log $file_or_fh: $!");
1346         _autoflush($fh);
1347     }
1348
1349     return $fh;
1350 }
1351
1352 sub _autoflush {
1353     my($fh) = shift;
1354     my $old_fh = select $fh;
1355     $| = 1;
1356     select $old_fh;
1357
1358     return;
1359 }
1360
1361
1362 sub reset_outputs {
1363     my $self = shift;
1364
1365     my $ctx = $self->ctx;
1366     my $format = $ctx->hub->format;
1367     $ctx->release;
1368     return unless $format && $format->isa('Test2::Formatter::TAP');
1369     $format->set_handles([@{$self->{Orig_Handles}}]) if $self->{Orig_Handles};
1370
1371     return;
1372 }
1373
1374
1375 sub carp {
1376     my $self = shift;
1377     my $ctx = $self->ctx;
1378     $ctx->alert(join "", @_);
1379     $ctx->release;
1380 }
1381
1382 sub croak {
1383     my $self = shift;
1384     my $ctx = $self->ctx;
1385     $ctx->throw(join "", @_);
1386     $ctx->release;
1387 }
1388
1389
1390 sub current_test {
1391     my( $self, $num ) = @_;
1392
1393     my $ctx = $self->ctx;
1394     my $hub = $ctx->hub;
1395
1396     if( defined $num ) {
1397         $hub->set_count($num);
1398
1399         unless ($self->{no_log_results}) {
1400             # If the test counter is being pushed forward fill in the details.
1401             my $test_results = $ctx->hub->meta(__PACKAGE__, {})->{Test_Results};
1402             if ($num > @$test_results) {
1403                 my $start = @$test_results ? @$test_results : 0;
1404                 for ($start .. $num - 1) {
1405                     $test_results->[$_] = {
1406                         'ok'      => 1,
1407                         actual_ok => undef,
1408                         reason    => 'incrementing test number',
1409                         type      => 'unknown',
1410                         name      => undef
1411                     };
1412                 }
1413             }
1414             # If backward, wipe history.  Its their funeral.
1415             elsif ($num < @$test_results) {
1416                 $#{$test_results} = $num - 1;
1417             }
1418         }
1419     }
1420     return release $ctx, $hub->count;
1421 }
1422
1423
1424 sub is_passing {
1425     my $self = shift;
1426
1427     my $ctx = $self->ctx;
1428     my $hub = $ctx->hub;
1429
1430     if( @_ ) {
1431         my ($bool) = @_;
1432         $hub->set_failed(0) if $bool;
1433         $hub->is_passing($bool);
1434     }
1435
1436     return release $ctx, $hub->is_passing;
1437 }
1438
1439
1440 sub summary {
1441     my($self) = shift;
1442
1443     return if $self->{no_log_results};
1444
1445     my $ctx = $self->ctx;
1446     my $data = $ctx->hub->meta(__PACKAGE__, {})->{Test_Results};
1447     $ctx->release;
1448     return map { $_ ? $_->{'ok'} : () } @$data;
1449 }
1450
1451
1452 sub details {
1453     my $self = shift;
1454
1455     return if $self->{no_log_results};
1456
1457     my $ctx = $self->ctx;
1458     my $data = $ctx->hub->meta(__PACKAGE__, {})->{Test_Results};
1459     $ctx->release;
1460     return @$data;
1461 }
1462
1463
1464 sub find_TODO {
1465     my( $self, $pack, $set, $new_value ) = @_;
1466
1467     my $ctx = $self->ctx;
1468
1469     $pack ||= $ctx->trace->package || $self->exported_to;
1470     $ctx->release;
1471
1472     return unless $pack;
1473
1474     no strict 'refs';    ## no critic
1475     no warnings 'once';
1476     my $old_value = ${ $pack . '::TODO' };
1477     $set and ${ $pack . '::TODO' } = $new_value;
1478     return $old_value;
1479 }
1480
1481 sub todo {
1482     my( $self, $pack ) = @_;
1483
1484     local $Level = $Level + 1;
1485     my $ctx = $self->ctx;
1486     $ctx->release;
1487
1488     my $meta = $ctx->hub->meta(__PACKAGE__, {todo => []})->{todo};
1489     return $meta->[-1]->[1] if $meta && @$meta;
1490
1491     $pack ||= $ctx->trace->package;
1492
1493     return unless $pack;
1494
1495     no strict 'refs';    ## no critic
1496     no warnings 'once';
1497     return ${ $pack . '::TODO' };
1498 }
1499
1500 sub in_todo {
1501     my $self = shift;
1502
1503     local $Level = $Level + 1;
1504     my $ctx = $self->ctx;
1505     $ctx->release;
1506
1507     my $meta = $ctx->hub->meta(__PACKAGE__, {todo => []})->{todo};
1508     return 1 if $meta && @$meta;
1509
1510     my $pack = $ctx->trace->package || return 0;
1511
1512     no strict 'refs';    ## no critic
1513     no warnings 'once';
1514     my $todo = ${ $pack . '::TODO' };
1515
1516     return 0 unless defined $todo;
1517     return 0 if "$todo" eq '';
1518     return 1;
1519 }
1520
1521 sub todo_start {
1522     my $self = shift;
1523     my $message = @_ ? shift : '';
1524
1525     my $ctx = $self->ctx;
1526
1527     my $hub = $ctx->hub;
1528     my $filter = $hub->pre_filter(sub {
1529         my ($active_hub, $e) = @_;
1530
1531         # Turn a diag into a todo diag
1532         return Test::Builder::TodoDiag->new(%$e) if ref($e) eq 'Test2::Event::Diag';
1533
1534         # Set todo on ok's
1535         if ($hub == $active_hub && $e->isa('Test2::Event::Ok')) {
1536             $e->set_todo($message);
1537             $e->set_effective_pass(1);
1538
1539             if (my $result = $e->get_meta(__PACKAGE__)) {
1540                 $result->{reason} ||= $message;
1541                 $result->{type}   ||= 'todo';
1542                 $result->{ok}       = 1;
1543             }
1544         }
1545
1546         return $e;
1547     }, inherit => 1);
1548
1549     push @{$ctx->hub->meta(__PACKAGE__, {todo => []})->{todo}} => [$filter, $message];
1550
1551     $ctx->release;
1552
1553     return;
1554 }
1555
1556 sub todo_end {
1557     my $self = shift;
1558
1559     my $ctx = $self->ctx;
1560
1561     my $set = pop @{$ctx->hub->meta(__PACKAGE__, {todo => []})->{todo}};
1562
1563     $ctx->throw('todo_end() called without todo_start()') unless $set;
1564
1565     $ctx->hub->pre_unfilter($set->[0]);
1566
1567     $ctx->release;
1568
1569     return;
1570 }
1571
1572
1573 sub caller {    ## no critic (Subroutines::ProhibitBuiltinHomonyms)
1574     my( $self ) = @_;
1575
1576     my $ctx = $self->ctx;
1577
1578     my $trace = $ctx->trace;
1579     $ctx->release;
1580     return wantarray ? $trace->call : $trace->package;
1581 }
1582
1583
1584 sub _try {
1585     my( $self, $code, %opts ) = @_;
1586
1587     my $error;
1588     my $return;
1589     {
1590         local $!;               # eval can mess up $!
1591         local $@;               # don't set $@ in the test
1592         local $SIG{__DIE__};    # don't trip an outside DIE handler.
1593         $return = eval { $code->() };
1594         $error = $@;
1595     }
1596
1597     die $error if $error and $opts{die_on_fail};
1598
1599     return wantarray ? ( $return, $error ) : $return;
1600 }
1601
1602 sub _ending {
1603     my $self = shift;
1604     my ($ctx, $real_exit_code, $new) = @_;
1605
1606     unless ($ctx) {
1607         my $octx = $self->ctx;
1608         $ctx = $octx->snapshot;
1609         $octx->release;
1610     }
1611
1612     return if $ctx->hub->no_ending;
1613     return if $ctx->hub->meta(__PACKAGE__, {})->{Ending}++;
1614
1615     # Don't bother with an ending if this is a forked copy.  Only the parent
1616     # should do the ending.
1617     return unless $self->{Original_Pid} == $$;
1618
1619     my $hub = $ctx->hub;
1620     return if $hub->bailed_out;
1621
1622     my $plan  = $hub->plan;
1623     my $count = $hub->count;
1624     my $failed = $hub->failed;
1625     my $passed = $hub->is_passing;
1626     return unless $plan || $count || $failed;
1627
1628     # Ran tests but never declared a plan or hit done_testing
1629     if( !$hub->plan and $hub->count ) {
1630         $self->diag("Tests were run but no plan was declared and done_testing() was not seen.");
1631
1632         if($real_exit_code) {
1633             $self->diag(<<"FAIL");
1634 Looks like your test exited with $real_exit_code just after $count.
1635 FAIL
1636             $$new ||= $real_exit_code;
1637             return;
1638         }
1639
1640         # But if the tests ran, handle exit code.
1641         if($failed > 0) {
1642             my $exit_code = $failed <= 254 ? $failed : 254;
1643             $$new ||= $exit_code;
1644             return;
1645         }
1646
1647         $$new ||= 254;
1648         return;
1649     }
1650
1651     if ($real_exit_code && !$count) {
1652         $self->diag("Looks like your test exited with $real_exit_code before it could output anything.");
1653         $$new ||= $real_exit_code;
1654         return;
1655     }
1656
1657     return if $plan && "$plan" eq 'SKIP';
1658
1659     if (!$count) {
1660         $self->diag('No tests run!');
1661         $$new ||= 255;
1662         return;
1663     }
1664
1665     if ($real_exit_code) {
1666         $self->diag(<<"FAIL");
1667 Looks like your test exited with $real_exit_code just after $count.
1668 FAIL
1669         $$new ||= $real_exit_code;
1670         return;
1671     }
1672
1673     if ($plan eq 'NO PLAN') {
1674         $ctx->plan( $count );
1675         $plan = $hub->plan;
1676     }
1677
1678     # Figure out if we passed or failed and print helpful messages.
1679     my $num_extra = $count - $plan;
1680
1681     if ($num_extra != 0) {
1682         my $s = $plan == 1 ? '' : 's';
1683         $self->diag(<<"FAIL");
1684 Looks like you planned $plan test$s but ran $count.
1685 FAIL
1686     }
1687
1688     if ($failed) {
1689         my $s = $failed == 1 ? '' : 's';
1690
1691         my $qualifier = $num_extra == 0 ? '' : ' run';
1692
1693         $self->diag(<<"FAIL");
1694 Looks like you failed $failed test$s of $count$qualifier.
1695 FAIL
1696     }
1697
1698     if (!$passed && !$failed && $count && !$num_extra) {
1699         $ctx->diag(<<"FAIL");
1700 All assertions passed, but errors were encountered.
1701 FAIL
1702     }
1703
1704     my $exit_code = 0;
1705     if ($failed) {
1706         $exit_code = $failed <= 254 ? $failed : 254;
1707     }
1708     elsif ($num_extra != 0) {
1709         $exit_code = 255;
1710     }
1711     elsif (!$passed) {
1712         $exit_code = 255;
1713     }
1714
1715     $$new ||= $exit_code;
1716     return;
1717 }
1718
1719 # Some things used this even though it was private... I am looking at you
1720 # Test::Builder::Prefix...
1721 sub _print_comment {
1722     my( $self, $fh, @msgs ) = @_;
1723
1724     return if $self->no_diag;
1725     return unless @msgs;
1726
1727     # Prevent printing headers when compiling (i.e. -c)
1728     return if $^C;
1729
1730     # Smash args together like print does.
1731     # Convert undef to 'undef' so its readable.
1732     my $msg = join '', map { defined($_) ? $_ : 'undef' } @msgs;
1733
1734     # Escape the beginning, _print will take care of the rest.
1735     $msg =~ s/^/# /;
1736
1737     local( $\, $", $, ) = ( undef, ' ', '' );
1738     print $fh $msg;
1739
1740     return 0;
1741 }
1742
1743 # This is used by Test::SharedFork to turn on IPC after the fact. Not
1744 # documenting because I do not want it used. The method name is borrowed from
1745 # Test::Builder 2
1746 # Once Test2 stuff goes stable this method will be removed and Test::SharedFork
1747 # will be made smarter.
1748 sub coordinate_forks {
1749     my $self = shift;
1750
1751     {
1752         local ($@, $!);
1753         require Test2::IPC;
1754     }
1755     Test2::IPC->import;
1756     Test2::API::test2_ipc_enable_polling();
1757     Test2::API::test2_load();
1758     my $ipc = Test2::IPC::apply_ipc($self->{Stack});
1759     $ipc->set_no_fatal(1);
1760     Test2::API::test2_no_wait(1);
1761     Test2::API::test2_ipc_enable_shm();
1762 }
1763
1764 sub no_log_results { $_[0]->{no_log_results} = 1 }
1765
1766 1;
1767
1768 __END__
1769
1770 =head1 NAME
1771
1772 Test::Builder - Backend for building test libraries
1773
1774 =head1 SYNOPSIS
1775
1776   package My::Test::Module;
1777   use base 'Test::Builder::Module';
1778
1779   my $CLASS = __PACKAGE__;
1780
1781   sub ok {
1782       my($test, $name) = @_;
1783       my $tb = $CLASS->builder;
1784
1785       $tb->ok($test, $name);
1786   }
1787
1788
1789 =head1 DESCRIPTION
1790
1791 L<Test::Simple> and L<Test::More> have proven to be popular testing modules,
1792 but they're not always flexible enough.  Test::Builder provides a
1793 building block upon which to write your own test libraries I<which can
1794 work together>.
1795
1796 =head2 Construction
1797
1798 =over 4
1799
1800 =item B<new>
1801
1802   my $Test = Test::Builder->new;
1803
1804 Returns a Test::Builder object representing the current state of the
1805 test.
1806
1807 Since you only run one test per program C<new> always returns the same
1808 Test::Builder object.  No matter how many times you call C<new()>, you're
1809 getting the same object.  This is called a singleton.  This is done so that
1810 multiple modules share such global information as the test counter and
1811 where test output is going.
1812
1813 If you want a completely new Test::Builder object different from the
1814 singleton, use C<create>.
1815
1816 =item B<create>
1817
1818   my $Test = Test::Builder->create;
1819
1820 Ok, so there can be more than one Test::Builder object and this is how
1821 you get it.  You might use this instead of C<new()> if you're testing
1822 a Test::Builder based module, but otherwise you probably want C<new>.
1823
1824 B<NOTE>: the implementation is not complete.  C<level>, for example, is still
1825 shared by B<all> Test::Builder objects, even ones created using this method.
1826 Also, the method name may change in the future.
1827
1828 =item B<subtest>
1829
1830     $builder->subtest($name, \&subtests, @args);
1831
1832 See documentation of C<subtest> in Test::More.
1833
1834 C<subtest> also, and optionally, accepts arguments which will be passed to the
1835 subtests reference.
1836
1837 =item B<name>
1838
1839  diag $builder->name;
1840
1841 Returns the name of the current builder.  Top level builders default to C<$0>
1842 (the name of the executable).  Child builders are named via the C<child>
1843 method.  If no name is supplied, will be named "Child of $parent->name".
1844
1845 =item B<reset>
1846
1847   $Test->reset;
1848
1849 Reinitializes the Test::Builder singleton to its original state.
1850 Mostly useful for tests run in persistent environments where the same
1851 test might be run multiple times in the same process.
1852
1853 =back
1854
1855 =head2 Setting up tests
1856
1857 These methods are for setting up tests and declaring how many there
1858 are.  You usually only want to call one of these methods.
1859
1860 =over 4
1861
1862 =item B<plan>
1863
1864   $Test->plan('no_plan');
1865   $Test->plan( skip_all => $reason );
1866   $Test->plan( tests => $num_tests );
1867
1868 A convenient way to set up your tests.  Call this and Test::Builder
1869 will print the appropriate headers and take the appropriate actions.
1870
1871 If you call C<plan()>, don't call any of the other methods below.
1872
1873 =item B<expected_tests>
1874
1875     my $max = $Test->expected_tests;
1876     $Test->expected_tests($max);
1877
1878 Gets/sets the number of tests we expect this test to run and prints out
1879 the appropriate headers.
1880
1881
1882 =item B<no_plan>
1883
1884   $Test->no_plan;
1885
1886 Declares that this test will run an indeterminate number of tests.
1887
1888
1889 =item B<done_testing>
1890
1891   $Test->done_testing();
1892   $Test->done_testing($num_tests);
1893
1894 Declares that you are done testing, no more tests will be run after this point.
1895
1896 If a plan has not yet been output, it will do so.
1897
1898 $num_tests is the number of tests you planned to run.  If a numbered
1899 plan was already declared, and if this contradicts, a failing test
1900 will be run to reflect the planning mistake.  If C<no_plan> was declared,
1901 this will override.
1902
1903 If C<done_testing()> is called twice, the second call will issue a
1904 failing test.
1905
1906 If C<$num_tests> is omitted, the number of tests run will be used, like
1907 no_plan.
1908
1909 C<done_testing()> is, in effect, used when you'd want to use C<no_plan>, but
1910 safer. You'd use it like so:
1911
1912     $Test->ok($a == $b);
1913     $Test->done_testing();
1914
1915 Or to plan a variable number of tests:
1916
1917     for my $test (@tests) {
1918         $Test->ok($test);
1919     }
1920     $Test->done_testing(scalar @tests);
1921
1922
1923 =item B<has_plan>
1924
1925   $plan = $Test->has_plan
1926
1927 Find out whether a plan has been defined. C<$plan> is either C<undef> (no plan
1928 has been set), C<no_plan> (indeterminate # of tests) or an integer (the number
1929 of expected tests).
1930
1931 =item B<skip_all>
1932
1933   $Test->skip_all;
1934   $Test->skip_all($reason);
1935
1936 Skips all the tests, using the given C<$reason>.  Exits immediately with 0.
1937
1938 =item B<exported_to>
1939
1940   my $pack = $Test->exported_to;
1941   $Test->exported_to($pack);
1942
1943 Tells Test::Builder what package you exported your functions to.
1944
1945 This method isn't terribly useful since modules which share the same
1946 Test::Builder object might get exported to different packages and only
1947 the last one will be honored.
1948
1949 =back
1950
1951 =head2 Running tests
1952
1953 These actually run the tests, analogous to the functions in Test::More.
1954
1955 They all return true if the test passed, false if the test failed.
1956
1957 C<$name> is always optional.
1958
1959 =over 4
1960
1961 =item B<ok>
1962
1963   $Test->ok($test, $name);
1964
1965 Your basic test.  Pass if C<$test> is true, fail if $test is false.  Just
1966 like Test::Simple's C<ok()>.
1967
1968 =item B<is_eq>
1969
1970   $Test->is_eq($got, $expected, $name);
1971
1972 Like Test::More's C<is()>.  Checks if C<$got eq $expected>.  This is the
1973 string version.
1974
1975 C<undef> only ever matches another C<undef>.
1976
1977 =item B<is_num>
1978
1979   $Test->is_num($got, $expected, $name);
1980
1981 Like Test::More's C<is()>.  Checks if C<$got == $expected>.  This is the
1982 numeric version.
1983
1984 C<undef> only ever matches another C<undef>.
1985
1986 =item B<isnt_eq>
1987
1988   $Test->isnt_eq($got, $dont_expect, $name);
1989
1990 Like L<Test::More>'s C<isnt()>.  Checks if C<$got ne $dont_expect>.  This is
1991 the string version.
1992
1993 =item B<isnt_num>
1994
1995   $Test->isnt_num($got, $dont_expect, $name);
1996
1997 Like L<Test::More>'s C<isnt()>.  Checks if C<$got ne $dont_expect>.  This is
1998 the numeric version.
1999
2000 =item B<like>
2001
2002   $Test->like($thing, qr/$regex/, $name);
2003   $Test->like($thing, '/$regex/', $name);
2004
2005 Like L<Test::More>'s C<like()>.  Checks if $thing matches the given C<$regex>.
2006
2007 =item B<unlike>
2008
2009   $Test->unlike($thing, qr/$regex/, $name);
2010   $Test->unlike($thing, '/$regex/', $name);
2011
2012 Like L<Test::More>'s C<unlike()>.  Checks if $thing B<does not match> the
2013 given C<$regex>.
2014
2015 =item B<cmp_ok>
2016
2017   $Test->cmp_ok($thing, $type, $that, $name);
2018
2019 Works just like L<Test::More>'s C<cmp_ok()>.
2020
2021     $Test->cmp_ok($big_num, '!=', $other_big_num);
2022
2023 =back
2024
2025 =head2 Other Testing Methods
2026
2027 These are methods which are used in the course of writing a test but are not themselves tests.
2028
2029 =over 4
2030
2031 =item B<BAIL_OUT>
2032
2033     $Test->BAIL_OUT($reason);
2034
2035 Indicates to the L<Test::Harness> that things are going so badly all
2036 testing should terminate.  This includes running any additional test
2037 scripts.
2038
2039 It will exit with 255.
2040
2041 =for deprecated
2042 BAIL_OUT() used to be BAILOUT()
2043
2044 =item B<skip>
2045
2046     $Test->skip;
2047     $Test->skip($why);
2048
2049 Skips the current test, reporting C<$why>.
2050
2051 =item B<todo_skip>
2052
2053   $Test->todo_skip;
2054   $Test->todo_skip($why);
2055
2056 Like C<skip()>, only it will declare the test as failing and TODO.  Similar
2057 to
2058
2059     print "not ok $tnum # TODO $why\n";
2060
2061 =begin _unimplemented
2062
2063 =item B<skip_rest>
2064
2065   $Test->skip_rest;
2066   $Test->skip_rest($reason);
2067
2068 Like C<skip()>, only it skips all the rest of the tests you plan to run
2069 and terminates the test.
2070
2071 If you're running under C<no_plan>, it skips once and terminates the
2072 test.
2073
2074 =end _unimplemented
2075
2076 =back
2077
2078
2079 =head2 Test building utility methods
2080
2081 These methods are useful when writing your own test methods.
2082
2083 =over 4
2084
2085 =item B<maybe_regex>
2086
2087   $Test->maybe_regex(qr/$regex/);
2088   $Test->maybe_regex('/$regex/');
2089
2090 This method used to be useful back when Test::Builder worked on Perls
2091 before 5.6 which didn't have qr//.  Now its pretty useless.
2092
2093 Convenience method for building testing functions that take regular
2094 expressions as arguments.
2095
2096 Takes a quoted regular expression produced by C<qr//>, or a string
2097 representing a regular expression.
2098
2099 Returns a Perl value which may be used instead of the corresponding
2100 regular expression, or C<undef> if its argument is not recognized.
2101
2102 For example, a version of C<like()>, sans the useful diagnostic messages,
2103 could be written as:
2104
2105   sub laconic_like {
2106       my ($self, $thing, $regex, $name) = @_;
2107       my $usable_regex = $self->maybe_regex($regex);
2108       die "expecting regex, found '$regex'\n"
2109           unless $usable_regex;
2110       $self->ok($thing =~ m/$usable_regex/, $name);
2111   }
2112
2113
2114 =item B<is_fh>
2115
2116     my $is_fh = $Test->is_fh($thing);
2117
2118 Determines if the given C<$thing> can be used as a filehandle.
2119
2120 =cut
2121
2122
2123 =back
2124
2125
2126 =head2 Test style
2127
2128
2129 =over 4
2130
2131 =item B<level>
2132
2133     $Test->level($how_high);
2134
2135 How far up the call stack should C<$Test> look when reporting where the
2136 test failed.
2137
2138 Defaults to 1.
2139
2140 Setting C<$Test::Builder::Level> overrides.  This is typically useful
2141 localized:
2142
2143     sub my_ok {
2144         my $test = shift;
2145
2146         local $Test::Builder::Level = $Test::Builder::Level + 1;
2147         $TB->ok($test);
2148     }
2149
2150 To be polite to other functions wrapping your own you usually want to increment C<$Level> rather than set it to a constant.
2151
2152 =item B<use_numbers>
2153
2154     $Test->use_numbers($on_or_off);
2155
2156 Whether or not the test should output numbers.  That is, this if true:
2157
2158   ok 1
2159   ok 2
2160   ok 3
2161
2162 or this if false
2163
2164   ok
2165   ok
2166   ok
2167
2168 Most useful when you can't depend on the test output order, such as
2169 when threads or forking is involved.
2170
2171 Defaults to on.
2172
2173 =item B<no_diag>
2174
2175     $Test->no_diag($no_diag);
2176
2177 If set true no diagnostics will be printed.  This includes calls to
2178 C<diag()>.
2179
2180 =item B<no_ending>
2181
2182     $Test->no_ending($no_ending);
2183
2184 Normally, Test::Builder does some extra diagnostics when the test
2185 ends.  It also changes the exit code as described below.
2186
2187 If this is true, none of that will be done.
2188
2189 =item B<no_header>
2190
2191     $Test->no_header($no_header);
2192
2193 If set to true, no "1..N" header will be printed.
2194
2195 =back
2196
2197 =head2 Output
2198
2199 Controlling where the test output goes.
2200
2201 It's ok for your test to change where STDOUT and STDERR point to,
2202 Test::Builder's default output settings will not be affected.
2203
2204 =over 4
2205
2206 =item B<diag>
2207
2208     $Test->diag(@msgs);
2209
2210 Prints out the given C<@msgs>.  Like C<print>, arguments are simply
2211 appended together.
2212
2213 Normally, it uses the C<failure_output()> handle, but if this is for a
2214 TODO test, the C<todo_output()> handle is used.
2215
2216 Output will be indented and marked with a # so as not to interfere
2217 with test output.  A newline will be put on the end if there isn't one
2218 already.
2219
2220 We encourage using this rather than calling print directly.
2221
2222 Returns false.  Why?  Because C<diag()> is often used in conjunction with
2223 a failing test (C<ok() || diag()>) it "passes through" the failure.
2224
2225     return ok(...) || diag(...);
2226
2227 =for blame transfer
2228 Mark Fowler <mark@twoshortplanks.com>
2229
2230 =item B<note>
2231
2232     $Test->note(@msgs);
2233
2234 Like C<diag()>, but it prints to the C<output()> handle so it will not
2235 normally be seen by the user except in verbose mode.
2236
2237 =item B<explain>
2238
2239     my @dump = $Test->explain(@msgs);
2240
2241 Will dump the contents of any references in a human readable format.
2242 Handy for things like...
2243
2244     is_deeply($have, $want) || diag explain $have;
2245
2246 or
2247
2248     is_deeply($have, $want) || note explain $have;
2249
2250 =item B<output>
2251
2252 =item B<failure_output>
2253
2254 =item B<todo_output>
2255
2256     my $filehandle = $Test->output;
2257     $Test->output($filehandle);
2258     $Test->output($filename);
2259     $Test->output(\$scalar);
2260
2261 These methods control where Test::Builder will print its output.
2262 They take either an open C<$filehandle>, a C<$filename> to open and write to
2263 or a C<$scalar> reference to append to.  It will always return a C<$filehandle>.
2264
2265 B<output> is where normal "ok/not ok" test output goes.
2266
2267 Defaults to STDOUT.
2268
2269 B<failure_output> is where diagnostic output on test failures and
2270 C<diag()> goes.  It is normally not read by Test::Harness and instead is
2271 displayed to the user.
2272
2273 Defaults to STDERR.
2274
2275 C<todo_output> is used instead of C<failure_output()> for the
2276 diagnostics of a failing TODO test.  These will not be seen by the
2277 user.
2278
2279 Defaults to STDOUT.
2280
2281 =item reset_outputs
2282
2283   $tb->reset_outputs;
2284
2285 Resets all the output filehandles back to their defaults.
2286
2287 =item carp
2288
2289   $tb->carp(@message);
2290
2291 Warns with C<@message> but the message will appear to come from the
2292 point where the original test function was called (C<< $tb->caller >>).
2293
2294 =item croak
2295
2296   $tb->croak(@message);
2297
2298 Dies with C<@message> but the message will appear to come from the
2299 point where the original test function was called (C<< $tb->caller >>).
2300
2301
2302 =back
2303
2304
2305 =head2 Test Status and Info
2306
2307 =over 4
2308
2309 =item B<no_log_results>
2310
2311 This will turn off result long-term storage. Calling this method will make
2312 C<details> and C<summary> useless. You may want to use this if you are running
2313 enough tests to fill up all available memory.
2314
2315     Test::Builder->new->no_log_results();
2316
2317 There is no way to turn it back on.
2318
2319 =item B<current_test>
2320
2321     my $curr_test = $Test->current_test;
2322     $Test->current_test($num);
2323
2324 Gets/sets the current test number we're on.  You usually shouldn't
2325 have to set this.
2326
2327 If set forward, the details of the missing tests are filled in as 'unknown'.
2328 if set backward, the details of the intervening tests are deleted.  You
2329 can erase history if you really want to.
2330
2331
2332 =item B<is_passing>
2333
2334    my $ok = $builder->is_passing;
2335
2336 Indicates if the test suite is currently passing.
2337
2338 More formally, it will be false if anything has happened which makes
2339 it impossible for the test suite to pass.  True otherwise.
2340
2341 For example, if no tests have run C<is_passing()> will be true because
2342 even though a suite with no tests is a failure you can add a passing
2343 test to it and start passing.
2344
2345 Don't think about it too much.
2346
2347
2348 =item B<summary>
2349
2350     my @tests = $Test->summary;
2351
2352 A simple summary of the tests so far.  True for pass, false for fail.
2353 This is a logical pass/fail, so todos are passes.
2354
2355 Of course, test #1 is $tests[0], etc...
2356
2357
2358 =item B<details>
2359
2360     my @tests = $Test->details;
2361
2362 Like C<summary()>, but with a lot more detail.
2363
2364     $tests[$test_num - 1] =
2365             { 'ok'       => is the test considered a pass?
2366               actual_ok  => did it literally say 'ok'?
2367               name       => name of the test (if any)
2368               type       => type of test (if any, see below).
2369               reason     => reason for the above (if any)
2370             };
2371
2372 'ok' is true if Test::Harness will consider the test to be a pass.
2373
2374 'actual_ok' is a reflection of whether or not the test literally
2375 printed 'ok' or 'not ok'.  This is for examining the result of 'todo'
2376 tests.
2377
2378 'name' is the name of the test.
2379
2380 'type' indicates if it was a special test.  Normal tests have a type
2381 of ''.  Type can be one of the following:
2382
2383     skip        see skip()
2384     todo        see todo()
2385     todo_skip   see todo_skip()
2386     unknown     see below
2387
2388 Sometimes the Test::Builder test counter is incremented without it
2389 printing any test output, for example, when C<current_test()> is changed.
2390 In these cases, Test::Builder doesn't know the result of the test, so
2391 its type is 'unknown'.  These details for these tests are filled in.
2392 They are considered ok, but the name and actual_ok is left C<undef>.
2393
2394 For example "not ok 23 - hole count # TODO insufficient donuts" would
2395 result in this structure:
2396
2397     $tests[22] =    # 23 - 1, since arrays start from 0.
2398       { ok        => 1,   # logically, the test passed since its todo
2399         actual_ok => 0,   # in absolute terms, it failed
2400         name      => 'hole count',
2401         type      => 'todo',
2402         reason    => 'insufficient donuts'
2403       };
2404
2405
2406 =item B<todo>
2407
2408     my $todo_reason = $Test->todo;
2409     my $todo_reason = $Test->todo($pack);
2410
2411 If the current tests are considered "TODO" it will return the reason,
2412 if any.  This reason can come from a C<$TODO> variable or the last call
2413 to C<todo_start()>.
2414
2415 Since a TODO test does not need a reason, this function can return an
2416 empty string even when inside a TODO block.  Use C<< $Test->in_todo >>
2417 to determine if you are currently inside a TODO block.
2418
2419 C<todo()> is about finding the right package to look for C<$TODO> in.  It's
2420 pretty good at guessing the right package to look at.  It first looks for
2421 the caller based on C<$Level + 1>, since C<todo()> is usually called inside
2422 a test function.  As a last resort it will use C<exported_to()>.
2423
2424 Sometimes there is some confusion about where C<todo()> should be looking
2425 for the C<$TODO> variable.  If you want to be sure, tell it explicitly
2426 what $pack to use.
2427
2428 =item B<find_TODO>
2429
2430     my $todo_reason = $Test->find_TODO();
2431     my $todo_reason = $Test->find_TODO($pack);
2432
2433 Like C<todo()> but only returns the value of C<$TODO> ignoring
2434 C<todo_start()>.
2435
2436 Can also be used to set C<$TODO> to a new value while returning the
2437 old value:
2438
2439     my $old_reason = $Test->find_TODO($pack, 1, $new_reason);
2440
2441 =item B<in_todo>
2442
2443     my $in_todo = $Test->in_todo;
2444
2445 Returns true if the test is currently inside a TODO block.
2446
2447 =item B<todo_start>
2448
2449     $Test->todo_start();
2450     $Test->todo_start($message);
2451
2452 This method allows you declare all subsequent tests as TODO tests, up until
2453 the C<todo_end> method has been called.
2454
2455 The C<TODO:> and C<$TODO> syntax is generally pretty good about figuring out
2456 whether or not we're in a TODO test.  However, often we find that this is not
2457 possible to determine (such as when we want to use C<$TODO> but
2458 the tests are being executed in other packages which can't be inferred
2459 beforehand).
2460
2461 Note that you can use this to nest "todo" tests
2462
2463  $Test->todo_start('working on this');
2464  # lots of code
2465  $Test->todo_start('working on that');
2466  # more code
2467  $Test->todo_end;
2468  $Test->todo_end;
2469
2470 This is generally not recommended, but large testing systems often have weird
2471 internal needs.
2472
2473 We've tried to make this also work with the TODO: syntax, but it's not
2474 guaranteed and its use is also discouraged:
2475
2476  TODO: {
2477      local $TODO = 'We have work to do!';
2478      $Test->todo_start('working on this');
2479      # lots of code
2480      $Test->todo_start('working on that');
2481      # more code
2482      $Test->todo_end;
2483      $Test->todo_end;
2484  }
2485
2486 Pick one style or another of "TODO" to be on the safe side.
2487
2488
2489 =item C<todo_end>
2490
2491  $Test->todo_end;
2492
2493 Stops running tests as "TODO" tests.  This method is fatal if called without a
2494 preceding C<todo_start> method call.
2495
2496 =item B<caller>
2497
2498     my $package = $Test->caller;
2499     my($pack, $file, $line) = $Test->caller;
2500     my($pack, $file, $line) = $Test->caller($height);
2501
2502 Like the normal C<caller()>, except it reports according to your C<level()>.
2503
2504 C<$height> will be added to the C<level()>.
2505
2506 If C<caller()> winds up off the top of the stack it report the highest context.
2507
2508 =back
2509
2510 =head1 EXIT CODES
2511
2512 If all your tests passed, Test::Builder will exit with zero (which is
2513 normal).  If anything failed it will exit with how many failed.  If
2514 you run less (or more) tests than you planned, the missing (or extras)
2515 will be considered failures.  If no tests were ever run Test::Builder
2516 will throw a warning and exit with 255.  If the test died, even after
2517 having successfully completed all its tests, it will still be
2518 considered a failure and will exit with 255.
2519
2520 So the exit codes are...
2521
2522     0                   all tests successful
2523     255                 test died or all passed but wrong # of tests run
2524     any other number    how many failed (including missing or extras)
2525
2526 If you fail more than 254 tests, it will be reported as 254.
2527
2528 =head1 THREADS
2529
2530 In perl 5.8.1 and later, Test::Builder is thread-safe.  The test number is
2531 shared by all threads.  This means if one thread sets the test number using
2532 C<current_test()> they will all be effected.
2533
2534 While versions earlier than 5.8.1 had threads they contain too many
2535 bugs to support.
2536
2537 Test::Builder is only thread-aware if threads.pm is loaded I<before>
2538 Test::Builder.
2539
2540 =head1 MEMORY
2541
2542 An informative hash, accessible via C<details()>, is stored for each
2543 test you perform.  So memory usage will scale linearly with each test
2544 run. Although this is not a problem for most test suites, it can
2545 become an issue if you do large (hundred thousands to million)
2546 combinatorics tests in the same run.
2547
2548 In such cases, you are advised to either split the test file into smaller
2549 ones, or use a reverse approach, doing "normal" (code) compares and
2550 triggering C<fail()> should anything go unexpected.
2551
2552 Future versions of Test::Builder will have a way to turn history off.
2553
2554
2555 =head1 EXAMPLES
2556
2557 CPAN can provide the best examples.  L<Test::Simple>, L<Test::More>,
2558 L<Test::Exception> and L<Test::Differences> all use Test::Builder.
2559
2560 =head1 SEE ALSO
2561
2562 L<Test::Simple>, L<Test::More>, L<Test::Harness>
2563
2564 =head1 AUTHORS
2565
2566 Original code by chromatic, maintained by Michael G Schwern
2567 E<lt>schwern@pobox.comE<gt>
2568
2569 =head1 MAINTAINERS
2570
2571 =over 4
2572
2573 =item Chad Granum E<lt>exodist@cpan.orgE<gt>
2574
2575 =back
2576
2577 =head1 COPYRIGHT
2578
2579 Copyright 2002-2008 by chromatic E<lt>chromatic@wgz.orgE<gt> and
2580                        Michael G Schwern E<lt>schwern@pobox.comE<gt>.
2581
2582 This program is free software; you can redistribute it and/or
2583 modify it under the same terms as Perl itself.
2584
2585 See F<http://www.perl.com/perl/misc/Artistic.html>