1package Test::Builder;
2
3use 5.006;
4use strict;
5use warnings;
6
7our $VERSION = '1.302199';
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            if (defined($got) xor defined($expect)) {
1006                $self->_cmp_diag( $got, $type, $expect );
1007            }
1008            else {
1009                $self->_isnt_diag( $got, $type );
1010            }
1011        }
1012        else {
1013            $self->_cmp_diag( $got, $type, $expect );
1014        }
1015    }
1016    return release $ctx, $ok;
1017}
1018
1019sub _cmp_diag {
1020    my( $self, $got, $type, $expect ) = @_;
1021
1022    $got    = defined $got    ? "'$got'"    : 'undef';
1023    $expect = defined $expect ? "'$expect'" : 'undef';
1024
1025    local $Level = $Level + 1;
1026    return $self->diag(<<"DIAGNOSTIC");
1027    $got
1028        $type
1029    $expect
1030DIAGNOSTIC
1031}
1032
1033sub _caller_context {
1034    my $self = shift;
1035
1036    my( $pack, $file, $line ) = $self->caller(1);
1037
1038    my $code = '';
1039    $code .= "#line $line $file\n" if defined $file and defined $line;
1040
1041    return $code;
1042}
1043
1044
1045sub BAIL_OUT {
1046    my( $self, $reason ) = @_;
1047
1048    my $ctx = $self->ctx;
1049
1050    $self->{Bailed_Out} = 1;
1051
1052    $ctx->bail($reason);
1053}
1054
1055
1056{
1057    no warnings 'once';
1058    *BAILOUT = \&BAIL_OUT;
1059}
1060
1061sub skip {
1062    my( $self, $why, $name ) = @_;
1063    $why ||= '';
1064    $name = '' unless defined $name;
1065    $self->_unoverload_str( \$why );
1066
1067    my $ctx = $self->ctx;
1068
1069    $name = "$name";
1070    $why  = "$why";
1071
1072    $name =~ s|#|\\#|g;    # # in a name can confuse Test::Harness.
1073    $name =~ s{\n}{\n# }sg;
1074    $why =~ s{\n}{\n# }sg;
1075
1076    $ctx->hub->meta(__PACKAGE__, {})->{Test_Results}[ $ctx->hub->count ] = {
1077        'ok'      => 1,
1078        actual_ok => 1,
1079        name      => $name,
1080        type      => 'skip',
1081        reason    => $why,
1082    } unless $self->{no_log_results};
1083
1084    my $tctx = $ctx->snapshot;
1085    $tctx->skip('', $why);
1086
1087    return release $ctx, 1;
1088}
1089
1090
1091sub todo_skip {
1092    my( $self, $why ) = @_;
1093    $why ||= '';
1094
1095    my $ctx = $self->ctx;
1096
1097    $ctx->hub->meta(__PACKAGE__, {})->{Test_Results}[ $ctx->hub->count ] = {
1098        'ok'      => 1,
1099        actual_ok => 0,
1100        name      => '',
1101        type      => 'todo_skip',
1102        reason    => $why,
1103    } unless $self->{no_log_results};
1104
1105    $why =~ s{\n}{\n# }sg;
1106    my $tctx = $ctx->snapshot;
1107    $tctx->send_event( 'Skip', todo => $why, todo_diag => 1, reason => $why, pass => 0);
1108
1109    return release $ctx, 1;
1110}
1111
1112
1113sub maybe_regex {
1114    my( $self, $regex ) = @_;
1115    my $usable_regex = undef;
1116
1117    return $usable_regex unless defined $regex;
1118
1119    my( $re, $opts );
1120
1121    # Check for qr/foo/
1122    if( _is_qr($regex) ) {
1123        $usable_regex = $regex;
1124    }
1125    # Check for '/foo/' or 'm,foo,'
1126    elsif(( $re, $opts )        = $regex =~ m{^ /(.*)/ (\w*) $ }sx              or
1127          ( undef, $re, $opts ) = $regex =~ m,^ m([^\w\s]) (.+) \1 (\w*) $,sx
1128    )
1129    {
1130        $usable_regex = length $opts ? "(?$opts)$re" : $re;
1131    }
1132
1133    return $usable_regex;
1134}
1135
1136sub _is_qr {
1137    my $regex = shift;
1138
1139    # is_regexp() checks for regexes in a robust manner, say if they're
1140    # blessed.
1141    return re::is_regexp($regex) if defined &re::is_regexp;
1142    return ref $regex eq 'Regexp';
1143}
1144
1145sub _regex_ok {
1146    my( $self, $thing, $regex, $cmp, $name ) = @_;
1147
1148    my $ok           = 0;
1149    my $usable_regex = $self->maybe_regex($regex);
1150    unless( defined $usable_regex ) {
1151        local $Level = $Level + 1;
1152        $ok = $self->ok( 0, $name );
1153        $self->diag("    '$regex' doesn't look much like a regex to me.");
1154        return $ok;
1155    }
1156
1157    {
1158        my $test;
1159        my $context = $self->_caller_context;
1160
1161        {
1162            ## no critic (BuiltinFunctions::ProhibitStringyEval)
1163
1164            local( $@, $!, $SIG{__DIE__} );    # isolate eval
1165
1166            # No point in issuing an uninit warning, they'll see it in the diagnostics
1167            no warnings 'uninitialized';
1168
1169            $test = eval $context . q{$test = $thing =~ /$usable_regex/ ? 1 : 0};
1170        }
1171
1172        $test = !$test if $cmp eq '!~';
1173
1174        local $Level = $Level + 1;
1175        $ok = $self->ok( $test, $name );
1176    }
1177
1178    unless($ok) {
1179        $thing = defined $thing ? "'$thing'" : 'undef';
1180        my $match = $cmp eq '=~' ? "doesn't match" : "matches";
1181
1182        local $Level = $Level + 1;
1183        $self->diag( sprintf <<'DIAGNOSTIC', $thing, $match, $regex );
1184                  %s
1185    %13s '%s'
1186DIAGNOSTIC
1187
1188    }
1189
1190    return $ok;
1191}
1192
1193
1194sub is_fh {
1195    my $self     = shift;
1196    my $maybe_fh = shift;
1197    return 0 unless defined $maybe_fh;
1198
1199    return 1 if ref $maybe_fh  eq 'GLOB';    # its a glob ref
1200    return 1 if ref \$maybe_fh eq 'GLOB';    # its a glob
1201
1202    return eval { $maybe_fh->isa("IO::Handle") } ||
1203           eval { tied($maybe_fh)->can('TIEHANDLE') };
1204}
1205
1206
1207sub level {
1208    my( $self, $level ) = @_;
1209
1210    if( defined $level ) {
1211        $Level = $level;
1212    }
1213    return $Level;
1214}
1215
1216
1217sub use_numbers {
1218    my( $self, $use_nums ) = @_;
1219
1220    my $ctx = $self->ctx;
1221    my $format = $ctx->hub->format;
1222    unless ($format && $format->can('no_numbers') && $format->can('set_no_numbers')) {
1223        warn "The current formatter does not support 'use_numbers'" if $format;
1224        return release $ctx, 0;
1225    }
1226
1227    $format->set_no_numbers(!$use_nums) if defined $use_nums;
1228
1229    return release $ctx, $format->no_numbers ? 0 : 1;
1230}
1231
1232BEGIN {
1233    for my $method (qw(no_header no_diag)) {
1234        my $set = "set_$method";
1235        my $code = sub {
1236            my( $self, $no ) = @_;
1237
1238            my $ctx = $self->ctx;
1239            my $format = $ctx->hub->format;
1240            unless ($format && $format->can($set)) {
1241                warn "The current formatter does not support '$method'" if $format;
1242                $ctx->release;
1243                return
1244            }
1245
1246            $format->$set($no) if defined $no;
1247
1248            return release $ctx, $format->$method ? 1 : 0;
1249        };
1250
1251        no strict 'refs';    ## no critic
1252        *$method = $code;
1253    }
1254}
1255
1256sub no_ending {
1257    my( $self, $no ) = @_;
1258
1259    my $ctx = $self->ctx;
1260
1261    $ctx->hub->set_no_ending($no) if defined $no;
1262
1263    return release $ctx, $ctx->hub->no_ending;
1264}
1265
1266sub diag {
1267    my $self = shift;
1268    return unless @_;
1269
1270    my $text = join '' => map {defined($_) ? $_ : 'undef'} @_;
1271
1272    if (Test2::API::test2_in_preload()) {
1273        chomp($text);
1274        $text =~ s/^/# /msg;
1275        print STDERR $text, "\n";
1276        return 0;
1277    }
1278
1279    my $ctx = $self->ctx;
1280    $ctx->diag($text);
1281    $ctx->release;
1282    return 0;
1283}
1284
1285
1286sub note {
1287    my $self = shift;
1288    return unless @_;
1289
1290    my $text = join '' => map {defined($_) ? $_ : 'undef'} @_;
1291
1292    if (Test2::API::test2_in_preload()) {
1293        chomp($text);
1294        $text =~ s/^/# /msg;
1295        print STDOUT $text, "\n";
1296        return 0;
1297    }
1298
1299    my $ctx = $self->ctx;
1300    $ctx->note($text);
1301    $ctx->release;
1302    return 0;
1303}
1304
1305
1306sub explain {
1307    my $self = shift;
1308
1309    local ($@, $!);
1310    require Data::Dumper;
1311
1312    return map {
1313        ref $_
1314          ? do {
1315            my $dumper = Data::Dumper->new( [$_] );
1316            $dumper->Indent(1)->Terse(1);
1317            $dumper->Sortkeys(1) if $dumper->can("Sortkeys");
1318            $dumper->Dump;
1319          }
1320          : $_
1321    } @_;
1322}
1323
1324
1325sub output {
1326    my( $self, $fh ) = @_;
1327
1328    my $ctx = $self->ctx;
1329    my $format = $ctx->hub->format;
1330    $ctx->release;
1331    return unless $format && $format->isa('Test2::Formatter::TAP');
1332
1333    $format->handles->[Test2::Formatter::TAP::OUT_STD()] = $self->_new_fh($fh)
1334        if defined $fh;
1335
1336    return $format->handles->[Test2::Formatter::TAP::OUT_STD()];
1337}
1338
1339sub failure_output {
1340    my( $self, $fh ) = @_;
1341
1342    my $ctx = $self->ctx;
1343    my $format = $ctx->hub->format;
1344    $ctx->release;
1345    return unless $format && $format->isa('Test2::Formatter::TAP');
1346
1347    $format->handles->[Test2::Formatter::TAP::OUT_ERR()] = $self->_new_fh($fh)
1348        if defined $fh;
1349
1350    return $format->handles->[Test2::Formatter::TAP::OUT_ERR()];
1351}
1352
1353sub todo_output {
1354    my( $self, $fh ) = @_;
1355
1356    my $ctx = $self->ctx;
1357    my $format = $ctx->hub->format;
1358    $ctx->release;
1359    return unless $format && $format->isa('Test::Builder::Formatter');
1360
1361    $format->handles->[Test::Builder::Formatter::OUT_TODO()] = $self->_new_fh($fh)
1362        if defined $fh;
1363
1364    return $format->handles->[Test::Builder::Formatter::OUT_TODO()];
1365}
1366
1367sub _new_fh {
1368    my $self = shift;
1369    my($file_or_fh) = shift;
1370
1371    my $fh;
1372    if( $self->is_fh($file_or_fh) ) {
1373        $fh = $file_or_fh;
1374    }
1375    elsif( ref $file_or_fh eq 'SCALAR' ) {
1376        # Scalar refs as filehandles was added in 5.8.
1377        if( $] >= 5.008 ) {
1378            open $fh, ">>", $file_or_fh
1379              or $self->croak("Can't open scalar ref $file_or_fh: $!");
1380        }
1381        # Emulate scalar ref filehandles with a tie.
1382        else {
1383            $fh = Test::Builder::IO::Scalar->new($file_or_fh)
1384              or $self->croak("Can't tie scalar ref $file_or_fh");
1385        }
1386    }
1387    else {
1388        open $fh, ">", $file_or_fh
1389          or $self->croak("Can't open test output log $file_or_fh: $!");
1390        _autoflush($fh);
1391    }
1392
1393    return $fh;
1394}
1395
1396sub _autoflush {
1397    my($fh) = shift;
1398    my $old_fh = select $fh;
1399    $| = 1;
1400    select $old_fh;
1401
1402    return;
1403}
1404
1405
1406sub reset_outputs {
1407    my $self = shift;
1408
1409    my $ctx = $self->ctx;
1410    my $format = $ctx->hub->format;
1411    $ctx->release;
1412    return unless $format && $format->isa('Test2::Formatter::TAP');
1413    $format->set_handles([@{$self->{Orig_Handles}}]) if $self->{Orig_Handles};
1414
1415    return;
1416}
1417
1418
1419sub carp {
1420    my $self = shift;
1421    my $ctx = $self->ctx;
1422    $ctx->alert(join "", @_);
1423    $ctx->release;
1424}
1425
1426sub croak {
1427    my $self = shift;
1428    my $ctx = $self->ctx;
1429    $ctx->throw(join "", @_);
1430    $ctx->release;
1431}
1432
1433
1434sub current_test {
1435    my( $self, $num ) = @_;
1436
1437    my $ctx = $self->ctx;
1438    my $hub = $ctx->hub;
1439
1440    if( defined $num ) {
1441        $hub->set_count($num);
1442
1443        unless ($self->{no_log_results}) {
1444            # If the test counter is being pushed forward fill in the details.
1445            my $test_results = $ctx->hub->meta(__PACKAGE__, {})->{Test_Results};
1446            if ($num > @$test_results) {
1447                my $start = @$test_results ? @$test_results : 0;
1448                for ($start .. $num - 1) {
1449                    $test_results->[$_] = {
1450                        'ok'      => 1,
1451                        actual_ok => undef,
1452                        reason    => 'incrementing test number',
1453                        type      => 'unknown',
1454                        name      => undef
1455                    };
1456                }
1457            }
1458            # If backward, wipe history.  Its their funeral.
1459            elsif ($num < @$test_results) {
1460                $#{$test_results} = $num - 1;
1461            }
1462        }
1463    }
1464    return release $ctx, $hub->count;
1465}
1466
1467
1468sub is_passing {
1469    my $self = shift;
1470
1471    my $ctx = $self->ctx;
1472    my $hub = $ctx->hub;
1473
1474    if( @_ ) {
1475        my ($bool) = @_;
1476        $hub->set_failed(0) if $bool;
1477        $hub->is_passing($bool);
1478    }
1479
1480    return release $ctx, $hub->is_passing;
1481}
1482
1483
1484sub summary {
1485    my($self) = shift;
1486
1487    return if $self->{no_log_results};
1488
1489    my $ctx = $self->ctx;
1490    my $data = $ctx->hub->meta(__PACKAGE__, {})->{Test_Results};
1491    $ctx->release;
1492    return map { $_ ? $_->{'ok'} : () } @$data;
1493}
1494
1495
1496sub details {
1497    my $self = shift;
1498
1499    return if $self->{no_log_results};
1500
1501    my $ctx = $self->ctx;
1502    my $data = $ctx->hub->meta(__PACKAGE__, {})->{Test_Results};
1503    $ctx->release;
1504    return @$data;
1505}
1506
1507
1508sub find_TODO {
1509    my( $self, $pack, $set, $new_value ) = @_;
1510
1511    my $ctx = $self->ctx;
1512
1513    $pack ||= $ctx->trace->package || $self->exported_to;
1514    $ctx->release;
1515
1516    return unless $pack;
1517
1518    no strict 'refs';    ## no critic
1519    no warnings 'once';
1520    my $old_value = ${ $pack . '::TODO' };
1521    $set and ${ $pack . '::TODO' } = $new_value;
1522    return $old_value;
1523}
1524
1525sub todo {
1526    my( $self, $pack ) = @_;
1527
1528    local $Level = $Level + 1;
1529    my $ctx = $self->ctx;
1530    $ctx->release;
1531
1532    my $meta = $ctx->hub->meta(__PACKAGE__, {todo => []})->{todo};
1533    return $meta->[-1]->[1] if $meta && @$meta;
1534
1535    $pack ||= $ctx->trace->package;
1536
1537    return unless $pack;
1538
1539    no strict 'refs';    ## no critic
1540    no warnings 'once';
1541    return ${ $pack . '::TODO' };
1542}
1543
1544sub in_todo {
1545    my $self = shift;
1546
1547    local $Level = $Level + 1;
1548    my $ctx = $self->ctx;
1549    $ctx->release;
1550
1551    my $meta = $ctx->hub->meta(__PACKAGE__, {todo => []})->{todo};
1552    return 1 if $meta && @$meta;
1553
1554    my $pack = $ctx->trace->package || return 0;
1555
1556    no strict 'refs';    ## no critic
1557    no warnings 'once';
1558    my $todo = ${ $pack . '::TODO' };
1559
1560    return 0 unless defined $todo;
1561    return 0 if "$todo" eq '';
1562    return 1;
1563}
1564
1565sub todo_start {
1566    my $self = shift;
1567    my $message = @_ ? shift : '';
1568
1569    my $ctx = $self->ctx;
1570
1571    my $hub = $ctx->hub;
1572    my $filter = $hub->pre_filter(sub {
1573        my ($active_hub, $e) = @_;
1574
1575        # Turn a diag into a todo diag
1576        return Test::Builder::TodoDiag->new(%$e) if ref($e) eq 'Test2::Event::Diag';
1577
1578        # Set todo on ok's
1579        if ($hub == $active_hub && $e->isa('Test2::Event::Ok')) {
1580            $e->set_todo($message);
1581            $e->set_effective_pass(1);
1582
1583            if (my $result = $e->get_meta(__PACKAGE__)) {
1584                $result->{reason} ||= $message;
1585                $result->{type}   ||= 'todo';
1586                $result->{ok}       = 1;
1587            }
1588        }
1589
1590        return $e;
1591    }, inherit => 1);
1592
1593    push @{$ctx->hub->meta(__PACKAGE__, {todo => []})->{todo}} => [$filter, $message];
1594
1595    $ctx->release;
1596
1597    return;
1598}
1599
1600sub todo_end {
1601    my $self = shift;
1602
1603    my $ctx = $self->ctx;
1604
1605    my $set = pop @{$ctx->hub->meta(__PACKAGE__, {todo => []})->{todo}};
1606
1607    $ctx->throw('todo_end() called without todo_start()') unless $set;
1608
1609    $ctx->hub->pre_unfilter($set->[0]);
1610
1611    $ctx->release;
1612
1613    return;
1614}
1615
1616
1617sub caller {    ## no critic (Subroutines::ProhibitBuiltinHomonyms)
1618    my( $self ) = @_;
1619
1620    my $ctx = $self->ctx;
1621
1622    my $trace = $ctx->trace;
1623    $ctx->release;
1624    return wantarray ? $trace->call : $trace->package;
1625}
1626
1627
1628sub _try {
1629    my( $self, $code, %opts ) = @_;
1630
1631    my $error;
1632    my $return;
1633    {
1634        local $!;               # eval can mess up $!
1635        local $@;               # don't set $@ in the test
1636        local $SIG{__DIE__};    # don't trip an outside DIE handler.
1637        $return = eval { $code->() };
1638        $error = $@;
1639    }
1640
1641    die $error if $error and $opts{die_on_fail};
1642
1643    return wantarray ? ( $return, $error ) : $return;
1644}
1645
1646sub _ending {
1647    my $self = shift;
1648    my ($ctx, $real_exit_code, $new) = @_;
1649
1650    unless ($ctx) {
1651        my $octx = $self->ctx;
1652        $ctx = $octx->snapshot;
1653        $octx->release;
1654    }
1655
1656    return if $ctx->hub->no_ending;
1657    return if $ctx->hub->meta(__PACKAGE__, {})->{Ending}++;
1658
1659    # Don't bother with an ending if this is a forked copy.  Only the parent
1660    # should do the ending.
1661    return unless $self->{Original_Pid} == $$;
1662
1663    my $hub = $ctx->hub;
1664    return if $hub->bailed_out;
1665
1666    my $plan  = $hub->plan;
1667    my $count = $hub->count;
1668    my $failed = $hub->failed;
1669    my $passed = $hub->is_passing;
1670    return unless $plan || $count || $failed;
1671
1672    # Ran tests but never declared a plan or hit done_testing
1673    if( !defined($hub->plan) and $hub->count ) {
1674        $self->diag("Tests were run but no plan was declared and done_testing() was not seen.");
1675
1676        if($real_exit_code) {
1677            $self->diag(<<"FAIL");
1678Looks like your test exited with $real_exit_code just after $count.
1679FAIL
1680            $$new ||= $real_exit_code;
1681            return;
1682        }
1683
1684        # But if the tests ran, handle exit code.
1685        if($failed > 0) {
1686            my $exit_code = $failed <= 254 ? $failed : 254;
1687            $$new ||= $exit_code;
1688            return;
1689        }
1690
1691        $$new ||= 254;
1692        return;
1693    }
1694
1695    if ($real_exit_code && !$count) {
1696        $self->diag("Looks like your test exited with $real_exit_code before it could output anything.");
1697        $$new ||= $real_exit_code;
1698        return;
1699    }
1700
1701    return if $plan && "$plan" eq 'SKIP';
1702
1703    if (!$count) {
1704        $self->diag('No tests run!');
1705        $$new ||= 255;
1706        return;
1707    }
1708
1709    if ($real_exit_code) {
1710        $self->diag(<<"FAIL");
1711Looks like your test exited with $real_exit_code just after $count.
1712FAIL
1713        $$new ||= $real_exit_code;
1714        return;
1715    }
1716
1717    if ($plan eq 'NO PLAN') {
1718        $ctx->plan( $count );
1719        $plan = $hub->plan;
1720    }
1721
1722    # Figure out if we passed or failed and print helpful messages.
1723    my $num_extra = $count - $plan;
1724
1725    if ($num_extra != 0) {
1726        my $s = $plan == 1 ? '' : 's';
1727        $self->diag(<<"FAIL");
1728Looks like you planned $plan test$s but ran $count.
1729FAIL
1730    }
1731
1732    if ($failed) {
1733        my $s = $failed == 1 ? '' : 's';
1734
1735        my $qualifier = $num_extra == 0 ? '' : ' run';
1736
1737        $self->diag(<<"FAIL");
1738Looks like you failed $failed test$s of $count$qualifier.
1739FAIL
1740    }
1741
1742    if (!$passed && !$failed && $count && !$num_extra) {
1743        $ctx->diag(<<"FAIL");
1744All assertions passed, but errors were encountered.
1745FAIL
1746    }
1747
1748    my $exit_code = 0;
1749    if ($failed) {
1750        $exit_code = $failed <= 254 ? $failed : 254;
1751    }
1752    elsif ($num_extra != 0) {
1753        $exit_code = 255;
1754    }
1755    elsif (!$passed) {
1756        $exit_code = 255;
1757    }
1758
1759    $$new ||= $exit_code;
1760    return;
1761}
1762
1763# Some things used this even though it was private... I am looking at you
1764# Test::Builder::Prefix...
1765sub _print_comment {
1766    my( $self, $fh, @msgs ) = @_;
1767
1768    return if $self->no_diag;
1769    return unless @msgs;
1770
1771    # Prevent printing headers when compiling (i.e. -c)
1772    return if $^C;
1773
1774    # Smash args together like print does.
1775    # Convert undef to 'undef' so its readable.
1776    my $msg = join '', map { defined($_) ? $_ : 'undef' } @msgs;
1777
1778    # Escape the beginning, _print will take care of the rest.
1779    $msg =~ s/^/# /;
1780
1781    local( $\, $", $, ) = ( undef, ' ', '' );
1782    print $fh $msg;
1783
1784    return 0;
1785}
1786
1787# This is used by Test::SharedFork to turn on IPC after the fact. Not
1788# documenting because I do not want it used. The method name is borrowed from
1789# Test::Builder 2
1790# Once Test2 stuff goes stable this method will be removed and Test::SharedFork
1791# will be made smarter.
1792sub coordinate_forks {
1793    my $self = shift;
1794
1795    {
1796        local ($@, $!);
1797        require Test2::IPC;
1798    }
1799    Test2::IPC->import;
1800    Test2::API::test2_ipc_enable_polling();
1801    Test2::API::test2_load();
1802    my $ipc = Test2::IPC::apply_ipc($self->{Stack});
1803    $ipc->set_no_fatal(1);
1804    Test2::API::test2_no_wait(1);
1805}
1806
1807sub no_log_results { $_[0]->{no_log_results} = 1 }
1808
18091;
1810
1811__END__
1812
1813=head1 NAME
1814
1815Test::Builder - Backend for building test libraries
1816
1817=head1 SYNOPSIS
1818
1819  package My::Test::Module;
1820  use base 'Test::Builder::Module';
1821
1822  my $CLASS = __PACKAGE__;
1823
1824  sub ok {
1825      my($test, $name) = @_;
1826      my $tb = $CLASS->builder;
1827
1828      $tb->ok($test, $name);
1829  }
1830
1831
1832=head1 DESCRIPTION
1833
1834L<Test::Simple> and L<Test::More> have proven to be popular testing modules,
1835but they're not always flexible enough.  Test::Builder provides a
1836building block upon which to write your own test libraries I<which can
1837work together>.
1838
1839=head2 Construction
1840
1841=over 4
1842
1843=item B<new>
1844
1845  my $Test = Test::Builder->new;
1846
1847Returns a Test::Builder object representing the current state of the
1848test.
1849
1850Since you only run one test per program C<new> always returns the same
1851Test::Builder object.  No matter how many times you call C<new()>, you're
1852getting the same object.  This is called a singleton.  This is done so that
1853multiple modules share such global information as the test counter and
1854where test output is going.
1855
1856If you want a completely new Test::Builder object different from the
1857singleton, use C<create>.
1858
1859=item B<create>
1860
1861  my $Test = Test::Builder->create;
1862
1863Ok, so there can be more than one Test::Builder object and this is how
1864you get it.  You might use this instead of C<new()> if you're testing
1865a Test::Builder based module, but otherwise you probably want C<new>.
1866
1867B<NOTE>: the implementation is not complete.  C<level>, for example, is still
1868shared by B<all> Test::Builder objects, even ones created using this method.
1869Also, the method name may change in the future.
1870
1871=item B<subtest>
1872
1873    $builder->subtest($name, \&subtests, @args);
1874
1875See documentation of C<subtest> in Test::More.
1876
1877C<subtest> also, and optionally, accepts arguments which will be passed to the
1878subtests reference.
1879
1880=item B<name>
1881
1882 diag $builder->name;
1883
1884Returns the name of the current builder.  Top level builders default to C<$0>
1885(the name of the executable).  Child builders are named via the C<child>
1886method.  If no name is supplied, will be named "Child of $parent->name".
1887
1888=item B<reset>
1889
1890  $Test->reset;
1891
1892Reinitializes the Test::Builder singleton to its original state.
1893Mostly useful for tests run in persistent environments where the same
1894test might be run multiple times in the same process.
1895
1896=back
1897
1898=head2 Setting up tests
1899
1900These methods are for setting up tests and declaring how many there
1901are.  You usually only want to call one of these methods.
1902
1903=over 4
1904
1905=item B<plan>
1906
1907  $Test->plan('no_plan');
1908  $Test->plan( skip_all => $reason );
1909  $Test->plan( tests => $num_tests );
1910
1911A convenient way to set up your tests.  Call this and Test::Builder
1912will print the appropriate headers and take the appropriate actions.
1913
1914If you call C<plan()>, don't call any of the other methods below.
1915
1916=item B<expected_tests>
1917
1918    my $max = $Test->expected_tests;
1919    $Test->expected_tests($max);
1920
1921Gets/sets the number of tests we expect this test to run and prints out
1922the appropriate headers.
1923
1924
1925=item B<no_plan>
1926
1927  $Test->no_plan;
1928
1929Declares that this test will run an indeterminate number of tests.
1930
1931
1932=item B<done_testing>
1933
1934  $Test->done_testing();
1935  $Test->done_testing($num_tests);
1936
1937Declares that you are done testing, no more tests will be run after this point.
1938
1939If a plan has not yet been output, it will do so.
1940
1941$num_tests is the number of tests you planned to run.  If a numbered
1942plan was already declared, and if this contradicts, a failing test
1943will be run to reflect the planning mistake.  If C<no_plan> was declared,
1944this will override.
1945
1946If C<done_testing()> is called twice, the second call will issue a
1947failing test.
1948
1949If C<$num_tests> is omitted, the number of tests run will be used, like
1950no_plan.
1951
1952C<done_testing()> is, in effect, used when you'd want to use C<no_plan>, but
1953safer. You'd use it like so:
1954
1955    $Test->ok($a == $b);
1956    $Test->done_testing();
1957
1958Or to plan a variable number of tests:
1959
1960    for my $test (@tests) {
1961        $Test->ok($test);
1962    }
1963    $Test->done_testing(scalar @tests);
1964
1965
1966=item B<has_plan>
1967
1968  $plan = $Test->has_plan
1969
1970Find out whether a plan has been defined. C<$plan> is either C<undef> (no plan
1971has been set), C<no_plan> (indeterminate # of tests) or an integer (the number
1972of expected tests).
1973
1974=item B<skip_all>
1975
1976  $Test->skip_all;
1977  $Test->skip_all($reason);
1978
1979Skips all the tests, using the given C<$reason>.  Exits immediately with 0.
1980
1981=item B<exported_to>
1982
1983  my $pack = $Test->exported_to;
1984  $Test->exported_to($pack);
1985
1986Tells Test::Builder what package you exported your functions to.
1987
1988This method isn't terribly useful since modules which share the same
1989Test::Builder object might get exported to different packages and only
1990the last one will be honored.
1991
1992=back
1993
1994=head2 Running tests
1995
1996These actually run the tests, analogous to the functions in Test::More.
1997
1998They all return true if the test passed, false if the test failed.
1999
2000C<$name> is always optional.
2001
2002=over 4
2003
2004=item B<ok>
2005
2006  $Test->ok($test, $name);
2007
2008Your basic test.  Pass if C<$test> is true, fail if $test is false.  Just
2009like Test::Simple's C<ok()>.
2010
2011=item B<is_eq>
2012
2013  $Test->is_eq($got, $expected, $name);
2014
2015Like Test::More's C<is()>.  Checks if C<$got eq $expected>.  This is the
2016string version.
2017
2018C<undef> only ever matches another C<undef>.
2019
2020=item B<is_num>
2021
2022  $Test->is_num($got, $expected, $name);
2023
2024Like Test::More's C<is()>.  Checks if C<$got == $expected>.  This is the
2025numeric version.
2026
2027C<undef> only ever matches another C<undef>.
2028
2029=item B<isnt_eq>
2030
2031  $Test->isnt_eq($got, $dont_expect, $name);
2032
2033Like L<Test::More>'s C<isnt()>.  Checks if C<$got ne $dont_expect>.  This is
2034the string version.
2035
2036=item B<isnt_num>
2037
2038  $Test->isnt_num($got, $dont_expect, $name);
2039
2040Like L<Test::More>'s C<isnt()>.  Checks if C<$got ne $dont_expect>.  This is
2041the numeric version.
2042
2043=item B<like>
2044
2045  $Test->like($thing, qr/$regex/, $name);
2046  $Test->like($thing, '/$regex/', $name);
2047
2048Like L<Test::More>'s C<like()>.  Checks if $thing matches the given C<$regex>.
2049
2050=item B<unlike>
2051
2052  $Test->unlike($thing, qr/$regex/, $name);
2053  $Test->unlike($thing, '/$regex/', $name);
2054
2055Like L<Test::More>'s C<unlike()>.  Checks if $thing B<does not match> the
2056given C<$regex>.
2057
2058=item B<cmp_ok>
2059
2060  $Test->cmp_ok($thing, $type, $that, $name);
2061
2062Works just like L<Test::More>'s C<cmp_ok()>.
2063
2064    $Test->cmp_ok($big_num, '!=', $other_big_num);
2065
2066=back
2067
2068=head2 Other Testing Methods
2069
2070These are methods which are used in the course of writing a test but are not themselves tests.
2071
2072=over 4
2073
2074=item B<BAIL_OUT>
2075
2076    $Test->BAIL_OUT($reason);
2077
2078Indicates to the L<Test::Harness> that things are going so badly all
2079testing should terminate.  This includes running any additional test
2080scripts.
2081
2082It will exit with 255.
2083
2084=for deprecated
2085BAIL_OUT() used to be BAILOUT()
2086
2087=item B<skip>
2088
2089    $Test->skip;
2090    $Test->skip($why);
2091
2092Skips the current test, reporting C<$why>.
2093
2094=item B<todo_skip>
2095
2096  $Test->todo_skip;
2097  $Test->todo_skip($why);
2098
2099Like C<skip()>, only it will declare the test as failing and TODO.  Similar
2100to
2101
2102    print "not ok $tnum # TODO $why\n";
2103
2104=begin _unimplemented
2105
2106=item B<skip_rest>
2107
2108  $Test->skip_rest;
2109  $Test->skip_rest($reason);
2110
2111Like C<skip()>, only it skips all the rest of the tests you plan to run
2112and terminates the test.
2113
2114If you're running under C<no_plan>, it skips once and terminates the
2115test.
2116
2117=end _unimplemented
2118
2119=back
2120
2121
2122=head2 Test building utility methods
2123
2124These methods are useful when writing your own test methods.
2125
2126=over 4
2127
2128=item B<maybe_regex>
2129
2130  $Test->maybe_regex(qr/$regex/);
2131  $Test->maybe_regex('/$regex/');
2132
2133This method used to be useful back when Test::Builder worked on Perls
2134before 5.6 which didn't have qr//.  Now its pretty useless.
2135
2136Convenience method for building testing functions that take regular
2137expressions as arguments.
2138
2139Takes a quoted regular expression produced by C<qr//>, or a string
2140representing a regular expression.
2141
2142Returns a Perl value which may be used instead of the corresponding
2143regular expression, or C<undef> if its argument is not recognized.
2144
2145For example, a version of C<like()>, sans the useful diagnostic messages,
2146could be written as:
2147
2148  sub laconic_like {
2149      my ($self, $thing, $regex, $name) = @_;
2150      my $usable_regex = $self->maybe_regex($regex);
2151      die "expecting regex, found '$regex'\n"
2152          unless $usable_regex;
2153      $self->ok($thing =~ m/$usable_regex/, $name);
2154  }
2155
2156
2157=item B<is_fh>
2158
2159    my $is_fh = $Test->is_fh($thing);
2160
2161Determines if the given C<$thing> can be used as a filehandle.
2162
2163=cut
2164
2165
2166=back
2167
2168
2169=head2 Test style
2170
2171
2172=over 4
2173
2174=item B<level>
2175
2176    $Test->level($how_high);
2177
2178How far up the call stack should C<$Test> look when reporting where the
2179test failed.
2180
2181Defaults to 1.
2182
2183Setting C<$Test::Builder::Level> overrides.  This is typically useful
2184localized:
2185
2186    sub my_ok {
2187        my $test = shift;
2188
2189        local $Test::Builder::Level = $Test::Builder::Level + 1;
2190        $TB->ok($test);
2191    }
2192
2193To be polite to other functions wrapping your own you usually want to increment C<$Level> rather than set it to a constant.
2194
2195=item B<use_numbers>
2196
2197    $Test->use_numbers($on_or_off);
2198
2199Whether or not the test should output numbers.  That is, this if true:
2200
2201  ok 1
2202  ok 2
2203  ok 3
2204
2205or this if false
2206
2207  ok
2208  ok
2209  ok
2210
2211Most useful when you can't depend on the test output order, such as
2212when threads or forking is involved.
2213
2214Defaults to on.
2215
2216=item B<no_diag>
2217
2218    $Test->no_diag($no_diag);
2219
2220If set true no diagnostics will be printed.  This includes calls to
2221C<diag()>.
2222
2223=item B<no_ending>
2224
2225    $Test->no_ending($no_ending);
2226
2227Normally, Test::Builder does some extra diagnostics when the test
2228ends.  It also changes the exit code as described below.
2229
2230If this is true, none of that will be done.
2231
2232=item B<no_header>
2233
2234    $Test->no_header($no_header);
2235
2236If set to true, no "1..N" header will be printed.
2237
2238=back
2239
2240=head2 Output
2241
2242Controlling where the test output goes.
2243
2244It's ok for your test to change where STDOUT and STDERR point to,
2245Test::Builder's default output settings will not be affected.
2246
2247=over 4
2248
2249=item B<diag>
2250
2251    $Test->diag(@msgs);
2252
2253Prints out the given C<@msgs>.  Like C<print>, arguments are simply
2254appended together.
2255
2256Normally, it uses the C<failure_output()> handle, but if this is for a
2257TODO test, the C<todo_output()> handle is used.
2258
2259Output will be indented and marked with a # so as not to interfere
2260with test output.  A newline will be put on the end if there isn't one
2261already.
2262
2263We encourage using this rather than calling print directly.
2264
2265Returns false.  Why?  Because C<diag()> is often used in conjunction with
2266a failing test (C<ok() || diag()>) it "passes through" the failure.
2267
2268    return ok(...) || diag(...);
2269
2270=for blame transfer
2271Mark Fowler <mark@twoshortplanks.com>
2272
2273=item B<note>
2274
2275    $Test->note(@msgs);
2276
2277Like C<diag()>, but it prints to the C<output()> handle so it will not
2278normally be seen by the user except in verbose mode.
2279
2280=item B<explain>
2281
2282    my @dump = $Test->explain(@msgs);
2283
2284Will dump the contents of any references in a human readable format.
2285Handy for things like...
2286
2287    is_deeply($have, $want) || diag explain $have;
2288
2289or
2290
2291    is_deeply($have, $want) || note explain $have;
2292
2293=item B<output>
2294
2295=item B<failure_output>
2296
2297=item B<todo_output>
2298
2299    my $filehandle = $Test->output;
2300    $Test->output($filehandle);
2301    $Test->output($filename);
2302    $Test->output(\$scalar);
2303
2304These methods control where Test::Builder will print its output.
2305They take either an open C<$filehandle>, a C<$filename> to open and write to
2306or a C<$scalar> reference to append to.  It will always return a C<$filehandle>.
2307
2308B<output> is where normal "ok/not ok" test output goes.
2309
2310Defaults to STDOUT.
2311
2312B<failure_output> is where diagnostic output on test failures and
2313C<diag()> goes.  It is normally not read by Test::Harness and instead is
2314displayed to the user.
2315
2316Defaults to STDERR.
2317
2318C<todo_output> is used instead of C<failure_output()> for the
2319diagnostics of a failing TODO test.  These will not be seen by the
2320user.
2321
2322Defaults to STDOUT.
2323
2324=item reset_outputs
2325
2326  $tb->reset_outputs;
2327
2328Resets all the output filehandles back to their defaults.
2329
2330=item carp
2331
2332  $tb->carp(@message);
2333
2334Warns with C<@message> but the message will appear to come from the
2335point where the original test function was called (C<< $tb->caller >>).
2336
2337=item croak
2338
2339  $tb->croak(@message);
2340
2341Dies with C<@message> but the message will appear to come from the
2342point where the original test function was called (C<< $tb->caller >>).
2343
2344
2345=back
2346
2347
2348=head2 Test Status and Info
2349
2350=over 4
2351
2352=item B<no_log_results>
2353
2354This will turn off result long-term storage. Calling this method will make
2355C<details> and C<summary> useless. You may want to use this if you are running
2356enough tests to fill up all available memory.
2357
2358    Test::Builder->new->no_log_results();
2359
2360There is no way to turn it back on.
2361
2362=item B<current_test>
2363
2364    my $curr_test = $Test->current_test;
2365    $Test->current_test($num);
2366
2367Gets/sets the current test number we're on.  You usually shouldn't
2368have to set this.
2369
2370If set forward, the details of the missing tests are filled in as 'unknown'.
2371if set backward, the details of the intervening tests are deleted.  You
2372can erase history if you really want to.
2373
2374
2375=item B<is_passing>
2376
2377   my $ok = $builder->is_passing;
2378
2379Indicates if the test suite is currently passing.
2380
2381More formally, it will be false if anything has happened which makes
2382it impossible for the test suite to pass.  True otherwise.
2383
2384For example, if no tests have run C<is_passing()> will be true because
2385even though a suite with no tests is a failure you can add a passing
2386test to it and start passing.
2387
2388Don't think about it too much.
2389
2390
2391=item B<summary>
2392
2393    my @tests = $Test->summary;
2394
2395A simple summary of the tests so far.  True for pass, false for fail.
2396This is a logical pass/fail, so todos are passes.
2397
2398Of course, test #1 is $tests[0], etc...
2399
2400
2401=item B<details>
2402
2403    my @tests = $Test->details;
2404
2405Like C<summary()>, but with a lot more detail.
2406
2407    $tests[$test_num - 1] =
2408            { 'ok'       => is the test considered a pass?
2409              actual_ok  => did it literally say 'ok'?
2410              name       => name of the test (if any)
2411              type       => type of test (if any, see below).
2412              reason     => reason for the above (if any)
2413            };
2414
2415'ok' is true if Test::Harness will consider the test to be a pass.
2416
2417'actual_ok' is a reflection of whether or not the test literally
2418printed 'ok' or 'not ok'.  This is for examining the result of 'todo'
2419tests.
2420
2421'name' is the name of the test.
2422
2423'type' indicates if it was a special test.  Normal tests have a type
2424of ''.  Type can be one of the following:
2425
2426    skip        see skip()
2427    todo        see todo()
2428    todo_skip   see todo_skip()
2429    unknown     see below
2430
2431Sometimes the Test::Builder test counter is incremented without it
2432printing any test output, for example, when C<current_test()> is changed.
2433In these cases, Test::Builder doesn't know the result of the test, so
2434its type is 'unknown'.  These details for these tests are filled in.
2435They are considered ok, but the name and actual_ok is left C<undef>.
2436
2437For example "not ok 23 - hole count # TODO insufficient donuts" would
2438result in this structure:
2439
2440    $tests[22] =    # 23 - 1, since arrays start from 0.
2441      { ok        => 1,   # logically, the test passed since its todo
2442        actual_ok => 0,   # in absolute terms, it failed
2443        name      => 'hole count',
2444        type      => 'todo',
2445        reason    => 'insufficient donuts'
2446      };
2447
2448
2449=item B<todo>
2450
2451    my $todo_reason = $Test->todo;
2452    my $todo_reason = $Test->todo($pack);
2453
2454If the current tests are considered "TODO" it will return the reason,
2455if any.  This reason can come from a C<$TODO> variable or the last call
2456to C<todo_start()>.
2457
2458Since a TODO test does not need a reason, this function can return an
2459empty string even when inside a TODO block.  Use C<< $Test->in_todo >>
2460to determine if you are currently inside a TODO block.
2461
2462C<todo()> is about finding the right package to look for C<$TODO> in.  It's
2463pretty good at guessing the right package to look at.  It first looks for
2464the caller based on C<$Level + 1>, since C<todo()> is usually called inside
2465a test function.  As a last resort it will use C<exported_to()>.
2466
2467Sometimes there is some confusion about where C<todo()> should be looking
2468for the C<$TODO> variable.  If you want to be sure, tell it explicitly
2469what $pack to use.
2470
2471=item B<find_TODO>
2472
2473    my $todo_reason = $Test->find_TODO();
2474    my $todo_reason = $Test->find_TODO($pack);
2475
2476Like C<todo()> but only returns the value of C<$TODO> ignoring
2477C<todo_start()>.
2478
2479Can also be used to set C<$TODO> to a new value while returning the
2480old value:
2481
2482    my $old_reason = $Test->find_TODO($pack, 1, $new_reason);
2483
2484=item B<in_todo>
2485
2486    my $in_todo = $Test->in_todo;
2487
2488Returns true if the test is currently inside a TODO block.
2489
2490=item B<todo_start>
2491
2492    $Test->todo_start();
2493    $Test->todo_start($message);
2494
2495This method allows you declare all subsequent tests as TODO tests, up until
2496the C<todo_end> method has been called.
2497
2498The C<TODO:> and C<$TODO> syntax is generally pretty good about figuring out
2499whether or not we're in a TODO test.  However, often we find that this is not
2500possible to determine (such as when we want to use C<$TODO> but
2501the tests are being executed in other packages which can't be inferred
2502beforehand).
2503
2504Note that you can use this to nest "todo" tests
2505
2506 $Test->todo_start('working on this');
2507 # lots of code
2508 $Test->todo_start('working on that');
2509 # more code
2510 $Test->todo_end;
2511 $Test->todo_end;
2512
2513This is generally not recommended, but large testing systems often have weird
2514internal needs.
2515
2516We've tried to make this also work with the TODO: syntax, but it's not
2517guaranteed and its use is also discouraged:
2518
2519 TODO: {
2520     local $TODO = 'We have work to do!';
2521     $Test->todo_start('working on this');
2522     # lots of code
2523     $Test->todo_start('working on that');
2524     # more code
2525     $Test->todo_end;
2526     $Test->todo_end;
2527 }
2528
2529Pick one style or another of "TODO" to be on the safe side.
2530
2531
2532=item C<todo_end>
2533
2534 $Test->todo_end;
2535
2536Stops running tests as "TODO" tests.  This method is fatal if called without a
2537preceding C<todo_start> method call.
2538
2539=item B<caller>
2540
2541    my $package = $Test->caller;
2542    my($pack, $file, $line) = $Test->caller;
2543    my($pack, $file, $line) = $Test->caller($height);
2544
2545Like the normal C<caller()>, except it reports according to your C<level()>.
2546
2547C<$height> will be added to the C<level()>.
2548
2549If C<caller()> winds up off the top of the stack it report the highest context.
2550
2551=back
2552
2553=head1 EXIT CODES
2554
2555If all your tests passed, Test::Builder will exit with zero (which is
2556normal).  If anything failed it will exit with how many failed.  If
2557you run less (or more) tests than you planned, the missing (or extras)
2558will be considered failures.  If no tests were ever run Test::Builder
2559will throw a warning and exit with 255.  If the test died, even after
2560having successfully completed all its tests, it will still be
2561considered a failure and will exit with 255.
2562
2563So the exit codes are...
2564
2565    0                   all tests successful
2566    255                 test died or all passed but wrong # of tests run
2567    any other number    how many failed (including missing or extras)
2568
2569If you fail more than 254 tests, it will be reported as 254.
2570
2571=head1 THREADS
2572
2573In perl 5.8.1 and later, Test::Builder is thread-safe.  The test number is
2574shared by all threads.  This means if one thread sets the test number using
2575C<current_test()> they will all be effected.
2576
2577While versions earlier than 5.8.1 had threads they contain too many
2578bugs to support.
2579
2580Test::Builder is only thread-aware if threads.pm is loaded I<before>
2581Test::Builder.
2582
2583You can directly disable thread support with one of the following:
2584
2585    $ENV{T2_NO_IPC} = 1
2586
2587or
2588
2589    no Test2::IPC;
2590
2591or
2592
2593    Test2::API::test2_ipc_disable()
2594
2595=head1 MEMORY
2596
2597An informative hash, accessible via C<details()>, is stored for each
2598test you perform.  So memory usage will scale linearly with each test
2599run. Although this is not a problem for most test suites, it can
2600become an issue if you do large (hundred thousands to million)
2601combinatorics tests in the same run.
2602
2603In such cases, you are advised to either split the test file into smaller
2604ones, or use a reverse approach, doing "normal" (code) compares and
2605triggering C<fail()> should anything go unexpected.
2606
2607Future versions of Test::Builder will have a way to turn history off.
2608
2609
2610=head1 EXAMPLES
2611
2612CPAN can provide the best examples.  L<Test::Simple>, L<Test::More>,
2613L<Test::Exception> and L<Test::Differences> all use Test::Builder.
2614
2615=head1 SEE ALSO
2616
2617=head2 INTERNALS
2618
2619L<Test2>, L<Test2::API>
2620
2621=head2 LEGACY
2622
2623L<Test::Simple>, L<Test::More>
2624
2625=head2 EXTERNAL
2626
2627L<Test::Harness>
2628
2629=head1 AUTHORS
2630
2631Original code by chromatic, maintained by Michael G Schwern
2632E<lt>schwern@pobox.comE<gt>
2633
2634=head1 MAINTAINERS
2635
2636=over 4
2637
2638=item Chad Granum E<lt>exodist@cpan.orgE<gt>
2639
2640=back
2641
2642=head1 COPYRIGHT
2643
2644Copyright 2002-2008 by chromatic E<lt>chromatic@wgz.orgE<gt> and
2645                       Michael G Schwern E<lt>schwern@pobox.comE<gt>.
2646
2647This program is free software; you can redistribute it and/or
2648modify it under the same terms as Perl itself.
2649
2650See L<https://dev.perl.org/licenses/>
2651