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