1package Test2::API;
2use strict;
3use warnings;
4
5use Test2::Util qw/USE_THREADS/;
6
7BEGIN {
8    $ENV{TEST_ACTIVE} ||= 1;
9    $ENV{TEST2_ACTIVE} = 1;
10}
11
12our $VERSION = '1.302183';
13
14
15my $INST;
16my $ENDING = 0;
17sub test2_unset_is_end { $ENDING = 0 }
18sub test2_get_is_end { $ENDING }
19
20sub test2_set_is_end {
21    my $before = $ENDING;
22    ($ENDING) = @_ ? @_ : (1);
23
24    # Only send the event in a transition from false to true
25    return if $before;
26    return unless $ENDING;
27
28    return unless $INST;
29    my $stack = $INST->stack or return;
30    my $root = $stack->root or return;
31
32    return unless $root->count;
33
34    return unless $$ == $INST->pid;
35    return unless get_tid() == $INST->tid;
36
37    my $trace = Test2::EventFacet::Trace->new(
38        frame  => [__PACKAGE__, __FILE__, __LINE__, __PACKAGE__ . '::test2_set_is_end'],
39    );
40    my $ctx = Test2::API::Context->new(
41        trace => $trace,
42        hub   => $root,
43    );
44
45    $ctx->send_ev2(control => { phase => 'END', details => 'Transition to END phase' });
46
47    1;
48}
49
50use Test2::API::Instance(\$INST);
51
52# Set the exit status
53END {
54    test2_set_is_end(); # See gh #16
55    $INST->set_exit();
56}
57
58sub CLONE {
59    my $init = test2_init_done();
60    my $load = test2_load_done();
61
62    return if $init && $load;
63
64    require Carp;
65    Carp::croak "Test2 must be fully loaded before you start a new thread!\n";
66}
67
68# See gh #16
69{
70    no warnings;
71    INIT { eval 'END { test2_set_is_end() }; 1' or die $@ }
72}
73
74BEGIN {
75    no warnings 'once';
76    if($] ge '5.014' || $ENV{T2_CHECK_DEPTH} || $Test2::API::DO_DEPTH_CHECK) {
77        *DO_DEPTH_CHECK = sub() { 1 };
78    }
79    else {
80        *DO_DEPTH_CHECK = sub() { 0 };
81    }
82}
83
84use Test2::EventFacet::Trace();
85use Test2::Util::Trace(); # Legacy
86
87use Test2::Hub::Subtest();
88use Test2::Hub::Interceptor();
89use Test2::Hub::Interceptor::Terminator();
90
91use Test2::Event::Ok();
92use Test2::Event::Diag();
93use Test2::Event::Note();
94use Test2::Event::Plan();
95use Test2::Event::Bail();
96use Test2::Event::Exception();
97use Test2::Event::Waiting();
98use Test2::Event::Skip();
99use Test2::Event::Subtest();
100
101use Carp qw/carp croak confess/;
102use Scalar::Util qw/blessed weaken/;
103use Test2::Util qw/get_tid clone_io pkg_to_file gen_uid/;
104
105our @EXPORT_OK = qw{
106    context release
107    context_do
108    no_context
109    intercept intercept_deep
110    run_subtest
111
112    test2_init_done
113    test2_load_done
114    test2_load
115    test2_start_preload
116    test2_stop_preload
117    test2_in_preload
118    test2_is_testing_done
119
120    test2_set_is_end
121    test2_unset_is_end
122    test2_get_is_end
123
124    test2_pid
125    test2_tid
126    test2_stack
127    test2_no_wait
128    test2_ipc_wait_enable
129    test2_ipc_wait_disable
130    test2_ipc_wait_enabled
131
132    test2_add_uuid_via
133
134    test2_add_callback_testing_done
135
136    test2_add_callback_context_aquire
137    test2_add_callback_context_acquire
138    test2_add_callback_context_init
139    test2_add_callback_context_release
140    test2_add_callback_exit
141    test2_add_callback_post_load
142    test2_add_callback_pre_subtest
143    test2_list_context_aquire_callbacks
144    test2_list_context_acquire_callbacks
145    test2_list_context_init_callbacks
146    test2_list_context_release_callbacks
147    test2_list_exit_callbacks
148    test2_list_post_load_callbacks
149    test2_list_pre_subtest_callbacks
150
151    test2_ipc
152    test2_has_ipc
153    test2_ipc_disable
154    test2_ipc_disabled
155    test2_ipc_drivers
156    test2_ipc_add_driver
157    test2_ipc_polling
158    test2_ipc_disable_polling
159    test2_ipc_enable_polling
160    test2_ipc_get_pending
161    test2_ipc_set_pending
162    test2_ipc_get_timeout
163    test2_ipc_set_timeout
164
165    test2_formatter
166    test2_formatters
167    test2_formatter_add
168    test2_formatter_set
169
170    test2_stdout
171    test2_stderr
172    test2_reset_io
173};
174BEGIN { require Exporter; our @ISA = qw(Exporter) }
175
176my $STACK       = $INST->stack;
177my $CONTEXTS    = $INST->contexts;
178my $INIT_CBS    = $INST->context_init_callbacks;
179my $ACQUIRE_CBS = $INST->context_acquire_callbacks;
180
181my $STDOUT = clone_io(\*STDOUT);
182my $STDERR = clone_io(\*STDERR);
183sub test2_stdout { $STDOUT ||= clone_io(\*STDOUT) }
184sub test2_stderr { $STDERR ||= clone_io(\*STDERR) }
185
186sub test2_post_preload_reset {
187    test2_reset_io();
188    $INST->post_preload_reset;
189}
190
191sub test2_reset_io {
192    $STDOUT = clone_io(\*STDOUT);
193    $STDERR = clone_io(\*STDERR);
194}
195
196sub test2_init_done { $INST->finalized }
197sub test2_load_done { $INST->loaded }
198
199sub test2_load          { $INST->load }
200sub test2_start_preload { $ENV{T2_IN_PRELOAD} = 1; $INST->start_preload }
201sub test2_stop_preload  { $ENV{T2_IN_PRELOAD} = 0; $INST->stop_preload }
202sub test2_in_preload    { $INST->preload }
203
204sub test2_pid              { $INST->pid }
205sub test2_tid              { $INST->tid }
206sub test2_stack            { $INST->stack }
207sub test2_ipc_wait_enable  { $INST->set_no_wait(0) }
208sub test2_ipc_wait_disable { $INST->set_no_wait(1) }
209sub test2_ipc_wait_enabled { !$INST->no_wait }
210
211sub test2_is_testing_done {
212    # No instance? VERY DONE!
213    return 1 unless $INST;
214
215    # No stack? tests must be done, it is created pretty early
216    my $stack = $INST->stack or return 1;
217
218    # Nothing on the stack, no root hub yet, likely have not started testing
219    return 0 unless @$stack;
220
221    # Stack has a slot for the root hub (see above) but it is undefined, likely
222    # garbage collected, test is done
223    my $root_hub = $stack->[0] or return 1;
224
225    # If the root hub is ended than testing is done.
226    return 1 if $root_hub->ended;
227
228    # Looks like we are still testing!
229    return 0;
230}
231
232sub test2_no_wait {
233    $INST->set_no_wait(@_) if @_;
234    $INST->no_wait;
235}
236
237sub test2_add_callback_testing_done {
238    my $cb = shift;
239
240    test2_add_callback_post_load(sub {
241        my $stack = test2_stack();
242        $stack->top; # Insure we have a hub
243        my ($hub) = Test2::API::test2_stack->all;
244
245        $hub->set_active(1);
246
247        $hub->follow_up($cb);
248    });
249
250    return;
251}
252
253sub test2_add_callback_context_acquire   { $INST->add_context_acquire_callback(@_) }
254sub test2_add_callback_context_aquire    { $INST->add_context_acquire_callback(@_) }
255sub test2_add_callback_context_init      { $INST->add_context_init_callback(@_) }
256sub test2_add_callback_context_release   { $INST->add_context_release_callback(@_) }
257sub test2_add_callback_exit              { $INST->add_exit_callback(@_) }
258sub test2_add_callback_post_load         { $INST->add_post_load_callback(@_) }
259sub test2_add_callback_pre_subtest       { $INST->add_pre_subtest_callback(@_) }
260sub test2_list_context_aquire_callbacks  { @{$INST->context_acquire_callbacks} }
261sub test2_list_context_acquire_callbacks { @{$INST->context_acquire_callbacks} }
262sub test2_list_context_init_callbacks    { @{$INST->context_init_callbacks} }
263sub test2_list_context_release_callbacks { @{$INST->context_release_callbacks} }
264sub test2_list_exit_callbacks            { @{$INST->exit_callbacks} }
265sub test2_list_post_load_callbacks       { @{$INST->post_load_callbacks} }
266sub test2_list_pre_subtest_callbacks     { @{$INST->pre_subtest_callbacks} }
267
268sub test2_add_uuid_via {
269    $INST->set_add_uuid_via(@_) if @_;
270    $INST->add_uuid_via();
271}
272
273sub test2_ipc                 { $INST->ipc }
274sub test2_has_ipc             { $INST->has_ipc }
275sub test2_ipc_disable         { $INST->ipc_disable }
276sub test2_ipc_disabled        { $INST->ipc_disabled }
277sub test2_ipc_add_driver      { $INST->add_ipc_driver(@_) }
278sub test2_ipc_drivers         { @{$INST->ipc_drivers} }
279sub test2_ipc_polling         { $INST->ipc_polling }
280sub test2_ipc_enable_polling  { $INST->enable_ipc_polling }
281sub test2_ipc_disable_polling { $INST->disable_ipc_polling }
282sub test2_ipc_get_pending     { $INST->get_ipc_pending }
283sub test2_ipc_set_pending     { $INST->set_ipc_pending(@_) }
284sub test2_ipc_set_timeout     { $INST->set_ipc_timeout(@_) }
285sub test2_ipc_get_timeout     { $INST->ipc_timeout() }
286sub test2_ipc_enable_shm      { 0 }
287
288sub test2_formatter     {
289    if ($ENV{T2_FORMATTER} && $ENV{T2_FORMATTER} =~ m/^(\+)?(.*)$/) {
290        my $formatter = $1 ? $2 : "Test2::Formatter::$2";
291        my $file = pkg_to_file($formatter);
292        require $file;
293        return $formatter;
294    }
295
296    return $INST->formatter;
297}
298
299sub test2_formatters    { @{$INST->formatters} }
300sub test2_formatter_add { $INST->add_formatter(@_) }
301sub test2_formatter_set {
302    my ($formatter) = @_;
303    croak "No formatter specified" unless $formatter;
304    croak "Global Formatter already set" if $INST->formatter_set;
305    $INST->set_formatter($formatter);
306}
307
308# Private, for use in Test2::API::Context
309sub _contexts_ref                  { $INST->contexts }
310sub _context_acquire_callbacks_ref { $INST->context_acquire_callbacks }
311sub _context_init_callbacks_ref    { $INST->context_init_callbacks }
312sub _context_release_callbacks_ref { $INST->context_release_callbacks }
313sub _add_uuid_via_ref              { \($INST->{Test2::API::Instance::ADD_UUID_VIA()}) }
314
315# Private, for use in Test2::IPC
316sub _set_ipc { $INST->set_ipc(@_) }
317
318sub context_do(&;@) {
319    my $code = shift;
320    my @args = @_;
321
322    my $ctx = context(level => 1);
323
324    my $want = wantarray;
325
326    my @out;
327    my $ok = eval {
328        $want          ? @out    = $code->($ctx, @args) :
329        defined($want) ? $out[0] = $code->($ctx, @args) :
330                                   $code->($ctx, @args) ;
331        1;
332    };
333    my $err = $@;
334
335    $ctx->release;
336
337    die $err unless $ok;
338
339    return @out    if $want;
340    return $out[0] if defined $want;
341    return;
342}
343
344sub no_context(&;$) {
345    my ($code, $hid) = @_;
346    $hid ||= $STACK->top->hid;
347
348    my $ctx = $CONTEXTS->{$hid};
349    delete $CONTEXTS->{$hid};
350    my $ok = eval { $code->(); 1 };
351    my $err = $@;
352
353    $CONTEXTS->{$hid} = $ctx;
354    weaken($CONTEXTS->{$hid});
355
356    die $err unless $ok;
357
358    return;
359};
360
361my $UUID_VIA = _add_uuid_via_ref();
362sub context {
363    # We need to grab these before anything else to ensure they are not
364    # changed.
365    my ($errno, $eval_error, $child_error, $extended_error) = (0 + $!, $@, $?, $^E);
366
367    my %params = (level => 0, wrapped => 0, @_);
368
369    # If something is getting a context then the sync system needs to be
370    # considered loaded...
371    $INST->load unless $INST->{loaded};
372
373    croak "context() called, but return value is ignored"
374        unless defined wantarray;
375
376    my $stack   = $params{stack} || $STACK;
377    my $hub     = $params{hub}   || (@$stack ? $stack->[-1] : $stack->top);
378
379    # Catch an edge case where we try to get context after the root hub has
380    # been garbage collected resulting in a stack that has a single undef
381    # hub
382    if (!$hub && !exists($params{hub}) && @$stack) {
383        my $msg = Carp::longmess("Attempt to get Test2 context after testing has completed (did you attempt a testing event after done_testing?)");
384
385        # The error message is usually masked by the global destruction, so we have to print to STDER
386        print STDERR $msg;
387
388        # Make sure this is a failure, we are probably already in END, so set $? to change the exit code
389        $? = 1;
390
391        # Now we actually die to interrupt the program flow and avoid undefined his warnings
392        die $msg;
393    }
394
395    my $hid     = $hub->{hid};
396    my $current = $CONTEXTS->{$hid};
397
398    $_->(\%params) for @$ACQUIRE_CBS;
399    map $_->(\%params), @{$hub->{_context_acquire}} if $hub->{_context_acquire};
400
401    # This is for https://github.com/Test-More/test-more/issues/16
402    # and https://rt.perl.org/Public/Bug/Display.html?id=127774
403    my $phase = ${^GLOBAL_PHASE} || 'NA';
404    my $end_phase = $ENDING || $phase eq 'END' || $phase eq 'DESTRUCT';
405
406    my $level = 1 + $params{level};
407    my ($pkg, $file, $line, $sub, @other) = $end_phase ? caller(0) : caller($level);
408    unless ($pkg || $end_phase) {
409        confess "Could not find context at depth $level" unless $params{fudge};
410        ($pkg, $file, $line, $sub, @other) = caller(--$level) while ($level >= 0 && !$pkg);
411    }
412
413    my $depth = $level;
414    $depth++ while DO_DEPTH_CHECK && !$end_phase && (!$current || $depth <= $current->{_depth} + $params{wrapped}) && caller($depth + 1);
415    $depth -= $params{wrapped};
416    my $depth_ok = !DO_DEPTH_CHECK || $end_phase || !$current || $current->{_depth} < $depth;
417
418    if ($current && $params{on_release} && $depth_ok) {
419        $current->{_on_release} ||= [];
420        push @{$current->{_on_release}} => $params{on_release};
421    }
422
423    # I know this is ugly....
424    ($!, $@, $?, $^E) = ($errno, $eval_error, $child_error, $extended_error) and return bless(
425        {
426            %$current,
427            _is_canon   => undef,
428            errno       => $errno,
429            eval_error  => $eval_error,
430            child_error => $child_error,
431            _is_spawn   => [$pkg, $file, $line, $sub],
432        },
433        'Test2::API::Context'
434    ) if $current && $depth_ok;
435
436    # Handle error condition of bad level
437    if ($current) {
438        unless (${$current->{_aborted}}) {
439            _canon_error($current, [$pkg, $file, $line, $sub, $depth])
440                unless $current->{_is_canon};
441
442            _depth_error($current, [$pkg, $file, $line, $sub, $depth])
443                unless $depth_ok;
444        }
445
446        $current->release if $current->{_is_canon};
447
448        delete $CONTEXTS->{$hid};
449    }
450
451    # Directly bless the object here, calling new is a noticeable performance
452    # hit with how often this needs to be called.
453    my $trace = bless(
454        {
455            frame  => [$pkg, $file, $line, $sub],
456            pid    => $$,
457            tid    => get_tid(),
458            cid    => gen_uid(),
459            hid    => $hid,
460            nested => $hub->{nested},
461            buffered => $hub->{buffered},
462
463            full_caller => [$pkg, $file, $line, $sub, @other],
464
465            $$UUID_VIA ? (
466                huuid => $hub->{uuid},
467                uuid  => ${$UUID_VIA}->('context'),
468            ) : (),
469        },
470        'Test2::EventFacet::Trace'
471    );
472
473    # Directly bless the object here, calling new is a noticeable performance
474    # hit with how often this needs to be called.
475    my $aborted = 0;
476    $current = bless(
477        {
478            _aborted     => \$aborted,
479            stack        => $stack,
480            hub          => $hub,
481            trace        => $trace,
482            _is_canon    => 1,
483            _depth       => $depth,
484            errno        => $errno,
485            eval_error   => $eval_error,
486            child_error  => $child_error,
487            $params{on_release} ? (_on_release => [$params{on_release}]) : (),
488        },
489        'Test2::API::Context'
490    );
491
492    $CONTEXTS->{$hid} = $current;
493    weaken($CONTEXTS->{$hid});
494
495    $_->($current) for @$INIT_CBS;
496    map $_->($current), @{$hub->{_context_init}} if $hub->{_context_init};
497
498    $params{on_init}->($current) if $params{on_init};
499
500    ($!, $@, $?, $^E) = ($errno, $eval_error, $child_error, $extended_error);
501
502    return $current;
503}
504
505sub _depth_error {
506    _existing_error(@_, <<"    EOT");
507context() was called to retrieve an existing context, however the existing
508context was created in a stack frame at the same, or deeper level. This usually
509means that a tool failed to release the context when it was finished.
510    EOT
511}
512
513sub _canon_error {
514    _existing_error(@_, <<"    EOT");
515context() was called to retrieve an existing context, however the existing
516context has an invalid internal state (!_canon_count). This should not normally
517happen unless something is mucking about with internals...
518    EOT
519}
520
521sub _existing_error {
522    my ($ctx, $details, $msg) = @_;
523    my ($pkg, $file, $line, $sub, $depth) = @$details;
524
525    my $oldframe = $ctx->{trace}->frame;
526    my $olddepth = $ctx->{_depth};
527
528    # Older versions of Carp do not export longmess() function, so it needs to be called with package name
529    my $mess = Carp::longmess();
530
531    warn <<"    EOT";
532$msg
533Old context details:
534   File: $oldframe->[1]
535   Line: $oldframe->[2]
536   Tool: $oldframe->[3]
537  Depth: $olddepth
538
539New context details:
540   File: $file
541   Line: $line
542   Tool: $sub
543  Depth: $depth
544
545Trace: $mess
546
547Removing the old context and creating a new one...
548    EOT
549}
550
551sub release($;$) {
552    $_[0]->release;
553    return $_[1];
554}
555
556sub intercept(&) {
557    my $code = shift;
558    my $ctx = context();
559
560    my $events = _intercept($code, deep => 0);
561
562    $ctx->release;
563
564    return $events;
565}
566
567sub intercept_deep(&) {
568    my $code = shift;
569    my $ctx = context();
570
571    my $events = _intercept($code, deep => 1);
572
573    $ctx->release;
574
575    return $events;
576}
577
578sub _intercept {
579    my $code = shift;
580    my %params = @_;
581    my $ctx = context();
582
583    my $ipc;
584    if (my $global_ipc = test2_ipc()) {
585        my $driver = blessed($global_ipc);
586        $ipc = $driver->new;
587    }
588
589    my $hub = Test2::Hub::Interceptor->new(
590        ipc => $ipc,
591        no_ending => 1,
592    );
593
594    my @events;
595    $hub->listen(sub { push @events => $_[1] }, inherit => $params{deep});
596
597    $ctx->stack->top; # Make sure there is a top hub before we begin.
598    $ctx->stack->push($hub);
599
600    my $trace = $ctx->trace;
601    my $state = {};
602    $hub->clean_inherited(trace => $trace, state => $state);
603
604    my ($ok, $err) = (1, undef);
605    T2_SUBTEST_WRAPPER: {
606        # Do not use 'try' cause it localizes __DIE__
607        $ok = eval { $code->(hub => $hub, context => $ctx->snapshot); 1 };
608        $err = $@;
609
610        # They might have done 'BEGIN { skip_all => "whatever" }'
611        if (!$ok && $err =~ m/Label not found for "last T2_SUBTEST_WRAPPER"/ || (blessed($err) && $err->isa('Test2::Hub::Interceptor::Terminator'))) {
612            $ok  = 1;
613            $err = undef;
614        }
615    }
616
617    $hub->cull;
618    $ctx->stack->pop($hub);
619
620    $hub->restore_inherited(trace => $trace, state => $state);
621
622    $ctx->release;
623
624    die $err unless $ok;
625
626    $hub->finalize($trace, 1)
627        if $ok
628        && !$hub->no_ending
629        && !$hub->ended;
630
631    require Test2::API::InterceptResult;
632    return Test2::API::InterceptResult->new_from_ref(\@events);
633}
634
635sub run_subtest {
636    my ($name, $code, $params, @args) = @_;
637
638    $_->($name,$code,@args)
639        for Test2::API::test2_list_pre_subtest_callbacks();
640
641    $params = {buffered => $params} unless ref $params;
642    my $inherit_trace = delete $params->{inherit_trace};
643
644    my $ctx = context();
645
646    my $parent = $ctx->hub;
647
648    # If a parent is buffered then the child must be as well.
649    my $buffered = $params->{buffered} || $parent->{buffered};
650
651    $ctx->note($name) unless $buffered;
652
653    my $stack = $ctx->stack || $STACK;
654    my $hub = $stack->new_hub(
655        class => 'Test2::Hub::Subtest',
656        %$params,
657        buffered => $buffered,
658    );
659
660    my @events;
661    $hub->listen(sub { push @events => $_[1] });
662
663    if ($buffered) {
664        if (my $format = $hub->format) {
665            my $hide = $format->can('hide_buffered') ? $format->hide_buffered : 1;
666            $hub->format(undef) if $hide;
667        }
668    }
669
670    if ($inherit_trace) {
671        my $orig = $code;
672        $code = sub {
673            my $base_trace = $ctx->trace;
674            my $trace = $base_trace->snapshot(nested => 1 + $base_trace->nested);
675            my $st_ctx = Test2::API::Context->new(
676                trace  => $trace,
677                hub    => $hub,
678            );
679            $st_ctx->do_in_context($orig, @args);
680        };
681    }
682
683    my ($ok, $err, $finished);
684    T2_SUBTEST_WRAPPER: {
685        # Do not use 'try' cause it localizes __DIE__
686        $ok = eval { $code->(@args); 1 };
687        $err = $@;
688
689        # They might have done 'BEGIN { skip_all => "whatever" }'
690        if (!$ok && $err =~ m/Label not found for "last T2_SUBTEST_WRAPPER"/ || (blessed($err) && blessed($err) eq 'Test::Builder::Exception')) {
691            $ok  = undef;
692            $err = undef;
693        }
694        else {
695            $finished = 1;
696        }
697    }
698
699    if ($params->{no_fork}) {
700        if ($$ != $ctx->trace->pid) {
701            warn $ok ? "Forked inside subtest, but subtest never finished!\n" : $err;
702            exit 255;
703        }
704
705        if (get_tid() != $ctx->trace->tid) {
706            warn $ok ? "Started new thread inside subtest, but thread never finished!\n" : $err;
707            exit 255;
708        }
709    }
710    elsif (!$parent->is_local && !$parent->ipc) {
711        warn $ok ? "A new process or thread was started inside subtest, but IPC is not enabled!\n" : $err;
712        exit 255;
713    }
714
715    $stack->pop($hub);
716
717    my $trace = $ctx->trace;
718
719    my $bailed = $hub->bailed_out;
720
721    if (!$finished) {
722        if ($bailed && !$buffered) {
723            $ctx->bail($bailed->reason);
724        }
725        elsif ($bailed && $buffered) {
726            $ok = 1;
727        }
728        else {
729            my $code = $hub->exit_code;
730            $ok = !$code;
731            $err = "Subtest ended with exit code $code" if $code;
732        }
733    }
734
735    $hub->finalize($trace->snapshot(huuid => $hub->uuid, hid => $hub->hid, nested => $hub->nested, buffered => $buffered), 1)
736        if $ok
737        && !$hub->no_ending
738        && !$hub->ended;
739
740    my $pass = $ok && $hub->is_passing;
741    my $e = $ctx->build_event(
742        'Subtest',
743        pass         => $pass,
744        name         => $name,
745        subtest_id   => $hub->id,
746        subtest_uuid => $hub->uuid,
747        buffered     => $buffered,
748        subevents    => \@events,
749    );
750
751    my $plan_ok = $hub->check_plan;
752
753    $ctx->hub->send($e);
754
755    $ctx->failure_diag($e) unless $e->pass;
756
757    $ctx->diag("Caught exception in subtest: $err") unless $ok;
758
759    $ctx->diag("Bad subtest plan, expected " . $hub->plan . " but ran " . $hub->count)
760        if defined($plan_ok) && !$plan_ok;
761
762    $ctx->bail($bailed->reason) if $bailed && $buffered;
763
764    $ctx->release;
765    return $pass;
766}
767
768# There is a use-cycle between API and API/Context. Context needs to use some
769# API functions as the package is compiling. Test2::API::context() needs
770# Test2::API::Context to be loaded, but we cannot 'require' the module there as
771# it causes a very noticeable performance impact with how often context() is
772# called.
773require Test2::API::Context;
774
7751;
776
777__END__
778
779=pod
780
781=encoding UTF-8
782
783=head1 NAME
784
785Test2::API - Primary interface for writing Test2 based testing tools.
786
787=head1 ***INTERNALS NOTE***
788
789B<The internals of this package are subject to change at any time!> The public
790methods provided will not change in backwards-incompatible ways (once there is
791a stable release), but the underlying implementation details might.
792B<Do not break encapsulation here!>
793
794Currently the implementation is to create a single instance of the
795L<Test2::API::Instance> Object. All class methods defer to the single
796instance. There is no public access to the singleton, and that is intentional.
797The class methods provided by this package provide the only functionality
798publicly exposed.
799
800This is done primarily to avoid the problems Test::Builder had by exposing its
801singleton. We do not want anyone to replace this singleton, rebless it, or
802directly muck with its internals. If you need to do something and cannot
803because of the restrictions placed here, then please report it as an issue. If
804possible, we will create a way for you to implement your functionality without
805exposing things that should not be exposed.
806
807=head1 DESCRIPTION
808
809This package exports all the functions necessary to write and/or verify testing
810tools. Using these building blocks you can begin writing test tools very
811quickly. You are also provided with tools that help you to test the tools you
812write.
813
814=head1 SYNOPSIS
815
816=head2 WRITING A TOOL
817
818The C<context()> method is your primary interface into the Test2 framework.
819
820    package My::Ok;
821    use Test2::API qw/context/;
822
823    our @EXPORT = qw/my_ok/;
824    use base 'Exporter';
825
826    # Just like ok() from Test::More
827    sub my_ok($;$) {
828        my ($bool, $name) = @_;
829        my $ctx = context(); # Get a context
830        $ctx->ok($bool, $name);
831        $ctx->release; # Release the context
832        return $bool;
833    }
834
835See L<Test2::API::Context> for a list of methods available on the context object.
836
837=head2 TESTING YOUR TOOLS
838
839The C<intercept { ... }> tool lets you temporarily intercept all events
840generated by the test system:
841
842    use Test2::API qw/intercept/;
843
844    use My::Ok qw/my_ok/;
845
846    my $events = intercept {
847        # These events are not displayed
848        my_ok(1, "pass");
849        my_ok(0, "fail");
850    };
851
852As of version 1.302178 this now returns an arrayref that is also an instance of
853L<Test2::API::InterceptResult>. See the L<Test2::API::InterceptResult>
854documentation for details on how to best use it.
855
856=head2 OTHER API FUNCTIONS
857
858    use Test2::API qw{
859        test2_init_done
860        test2_stack
861        test2_set_is_end
862        test2_get_is_end
863        test2_ipc
864        test2_formatter_set
865        test2_formatter
866        test2_is_testing_done
867    };
868
869    my $init  = test2_init_done();
870    my $stack = test2_stack();
871    my $ipc   = test2_ipc();
872
873    test2_formatter_set($FORMATTER)
874    my $formatter = test2_formatter();
875
876    ... And others ...
877
878=head1 MAIN API EXPORTS
879
880All exports are optional. You must specify subs to import.
881
882    use Test2::API qw/context intercept run_subtest/;
883
884This is the list of exports that are most commonly needed. If you are simply
885writing a tool, then this is probably all you need. If you need something and
886you cannot find it here, then you can also look at L</OTHER API EXPORTS>.
887
888These exports lack the 'test2_' prefix because of how important/common they
889are. Exports in the L</OTHER API EXPORTS> section have the 'test2_' prefix to
890ensure they stand out.
891
892=head2 context(...)
893
894Usage:
895
896=over 4
897
898=item $ctx = context()
899
900=item $ctx = context(%params)
901
902=back
903
904The C<context()> function will always return the current context. If
905there is already a context active, it will be returned. If there is not an
906active context, one will be generated. When a context is generated it will
907default to using the file and line number where the currently running sub was
908called from.
909
910Please see L<Test2::API::Context/"CRITICAL DETAILS"> for important rules about
911what you can and cannot do with a context once it is obtained.
912
913B<Note> This function will throw an exception if you ignore the context object
914it returns.
915
916B<Note> On perls 5.14+ a depth check is used to insure there are no context
917leaks. This cannot be safely done on older perls due to
918L<https://rt.perl.org/Public/Bug/Display.html?id=127774>
919You can forcefully enable it either by setting C<$ENV{T2_CHECK_DEPTH} = 1> or
920C<$Test2::API::DO_DEPTH_CHECK = 1> B<BEFORE> loading L<Test2::API>.
921
922=head3 OPTIONAL PARAMETERS
923
924All parameters to C<context> are optional.
925
926=over 4
927
928=item level => $int
929
930If you must obtain a context in a sub deeper than your entry point you can use
931this to tell it how many EXTRA stack frames to look back. If this option is not
932provided the default of C<0> is used.
933
934    sub third_party_tool {
935        my $sub = shift;
936        ... # Does not obtain a context
937        $sub->();
938        ...
939    }
940
941    third_party_tool(sub {
942        my $ctx = context(level => 1);
943        ...
944        $ctx->release;
945    });
946
947=item wrapped => $int
948
949Use this if you need to write your own tool that wraps a call to C<context()>
950with the intent that it should return a context object.
951
952    sub my_context {
953        my %params = ( wrapped => 0, @_ );
954        $params{wrapped}++;
955        my $ctx = context(%params);
956        ...
957        return $ctx;
958    }
959
960    sub my_tool {
961        my $ctx = my_context();
962        ...
963        $ctx->release;
964    }
965
966If you do not do this, then tools you call that also check for a context will
967notice that the context they grabbed was created at the same stack depth, which
968will trigger protective measures that warn you and destroy the existing
969context.
970
971=item stack => $stack
972
973Normally C<context()> looks at the global hub stack. If you are maintaining
974your own L<Test2::API::Stack> instance you may pass it in to be used
975instead of the global one.
976
977=item hub => $hub
978
979Use this parameter if you want to obtain the context for a specific hub instead
980of whatever one happens to be at the top of the stack.
981
982=item on_init => sub { ... }
983
984This lets you provide a callback sub that will be called B<ONLY> if your call
985to C<context()> generated a new context. The callback B<WILL NOT> be called if
986C<context()> is returning an existing context. The only argument passed into
987the callback will be the context object itself.
988
989    sub foo {
990        my $ctx = context(on_init => sub { 'will run' });
991
992        my $inner = sub {
993            # This callback is not run since we are getting the existing
994            # context from our parent sub.
995            my $ctx = context(on_init => sub { 'will NOT run' });
996            $ctx->release;
997        }
998        $inner->();
999
1000        $ctx->release;
1001    }
1002
1003=item on_release => sub { ... }
1004
1005This lets you provide a callback sub that will be called when the context
1006instance is released. This callback will be added to the returned context even
1007if an existing context is returned. If multiple calls to context add callbacks,
1008then all will be called in reverse order when the context is finally released.
1009
1010    sub foo {
1011        my $ctx = context(on_release => sub { 'will run second' });
1012
1013        my $inner = sub {
1014            my $ctx = context(on_release => sub { 'will run first' });
1015
1016            # Neither callback runs on this release
1017            $ctx->release;
1018        }
1019        $inner->();
1020
1021        # Both callbacks run here.
1022        $ctx->release;
1023    }
1024
1025=back
1026
1027=head2 release($;$)
1028
1029Usage:
1030
1031=over 4
1032
1033=item release $ctx;
1034
1035=item release $ctx, ...;
1036
1037=back
1038
1039This is intended as a shortcut that lets you release your context and return a
1040value in one statement. This function will get your context, and an optional
1041return value. It will release your context, then return your value. Scalar
1042context is always assumed.
1043
1044    sub tool {
1045        my $ctx = context();
1046        ...
1047
1048        return release $ctx, 1;
1049    }
1050
1051This tool is most useful when you want to return the value you get from calling
1052a function that needs to see the current context:
1053
1054    my $ctx = context();
1055    my $out = some_tool(...);
1056    $ctx->release;
1057    return $out;
1058
1059We can combine the last 3 lines of the above like so:
1060
1061    my $ctx = context();
1062    release $ctx, some_tool(...);
1063
1064=head2 context_do(&;@)
1065
1066Usage:
1067
1068    sub my_tool {
1069        context_do {
1070            my $ctx = shift;
1071
1072            my (@args) = @_;
1073
1074            $ctx->ok(1, "pass");
1075
1076            ...
1077
1078            # No need to call $ctx->release, done for you on scope exit.
1079        } @_;
1080    }
1081
1082Using this inside your test tool takes care of a lot of boilerplate for you. It
1083will ensure a context is acquired. It will capture and rethrow any exception. It
1084will insure the context is released when you are done. It preserves the
1085subroutine call context (array, scalar, void).
1086
1087This is the safest way to write a test tool. The only two downsides to this are a
1088slight performance decrease, and some extra indentation in your source. If the
1089indentation is a problem for you then you can take a peek at the next section.
1090
1091=head2 no_context(&;$)
1092
1093Usage:
1094
1095=over 4
1096
1097=item no_context { ... };
1098
1099=item no_context { ... } $hid;
1100
1101    sub my_tool(&) {
1102        my $code = shift;
1103        my $ctx = context();
1104        ...
1105
1106        no_context {
1107            # Things in here will not see our current context, they get a new
1108            # one.
1109
1110            $code->();
1111        };
1112
1113        ...
1114        $ctx->release;
1115    };
1116
1117=back
1118
1119This tool will hide a context for the provided block of code. This means any
1120tools run inside the block will get a completely new context if they acquire
1121one. The new context will be inherited by tools nested below the one that
1122acquired it.
1123
1124This will normally hide the current context for the top hub. If you need to
1125hide the context for a different hub you can pass in the optional C<$hid>
1126parameter.
1127
1128=head2 intercept(&)
1129
1130Usage:
1131
1132    my $events = intercept {
1133        ok(1, "pass");
1134        ok(0, "fail");
1135        ...
1136    };
1137
1138This function takes a codeblock as its only argument, and it has a prototype.
1139It will execute the codeblock, intercepting any generated events in the
1140process. It will return an array reference with all the generated event
1141objects. All events should be subclasses of L<Test2::Event>.
1142
1143As of version 1.302178 the events array that is returned is blssed as an
1144L<Test2::API::InterceptResult> instance. L<Test2::API::InterceptResult>
1145Provides a helpful interface for filtering and/or inspecting the events list
1146overall, or individual events within the list.
1147
1148This is intended to help you test your test code. This is not intended for
1149people simply writing tests.
1150
1151=head2 run_subtest(...)
1152
1153Usage:
1154
1155    run_subtest($NAME, \&CODE, $BUFFERED, @ARGS)
1156
1157    # or
1158
1159    run_subtest($NAME, \&CODE, \%PARAMS, @ARGS)
1160
1161This will run the provided codeblock with the args in C<@args>. This codeblock
1162will be run as a subtest. A subtest is an isolated test state that is condensed
1163into a single L<Test2::Event::Subtest> event, which contains all events
1164generated inside the subtest.
1165
1166=head3 ARGUMENTS:
1167
1168=over 4
1169
1170=item $NAME
1171
1172The name of the subtest.
1173
1174=item \&CODE
1175
1176The code to run inside the subtest.
1177
1178=item $BUFFERED or \%PARAMS
1179
1180If this is a simple scalar then it will be treated as a boolean for the
1181'buffered' setting. If this is a hash reference then it will be used as a
1182parameters hash. The param hash will be used for hub construction (with the
1183specified keys removed).
1184
1185Keys that are removed and used by run_subtest:
1186
1187=over 4
1188
1189=item 'buffered' => $bool
1190
1191Toggle buffered status.
1192
1193=item 'inherit_trace' => $bool
1194
1195Normally the subtest hub is pushed and the sub is allowed to generate its own
1196root context for the hub. When this setting is turned on a root context will be
1197created for the hub that shares the same trace as the current context.
1198
1199Set this to true if your tool is producing subtests without user-specified
1200subs.
1201
1202=item 'no_fork' => $bool
1203
1204Defaults to off. Normally forking inside a subtest will actually fork the
1205subtest, resulting in 2 final subtest events. This parameter will turn off that
1206behavior, only the original process/thread will return a final subtest event.
1207
1208=back
1209
1210=item @ARGS
1211
1212Any extra arguments you want passed into the subtest code.
1213
1214=back
1215
1216=head3 BUFFERED VS UNBUFFERED (OR STREAMED)
1217
1218Normally all events inside and outside a subtest are sent to the formatter
1219immediately by the hub. Sometimes it is desirable to hold off sending events
1220within a subtest until the subtest is complete. This usually depends on the
1221formatter being used.
1222
1223=over 4
1224
1225=item Things not effected by this flag
1226
1227In both cases events are generated and stored in an array. This array is
1228eventually used to populate the C<subevents> attribute on the
1229L<Test2::Event::Subtest> event that is generated at the end of the subtest.
1230This flag has no effect on this part, it always happens.
1231
1232At the end of the subtest, the final L<Test2::Event::Subtest> event is sent to
1233the formatter.
1234
1235=item Things that are effected by this flag
1236
1237The C<buffered> attribute of the L<Test2::Event::Subtest> event will be set to
1238the value of this flag. This means any formatter, listener, etc which looks at
1239the event will know if it was buffered.
1240
1241=item Things that are formatter dependant
1242
1243Events within a buffered subtest may or may not be sent to the formatter as
1244they happen. If a formatter fails to specify then the default is to B<NOT SEND>
1245the events as they are generated, instead the formatter can pull them from the
1246C<subevents> attribute.
1247
1248A formatter can specify by implementing the C<hide_buffered()> method. If this
1249method returns true then events generated inside a buffered subtest will not be
1250sent independently of the final subtest event.
1251
1252=back
1253
1254An example of how this is used is the L<Test2::Formatter::TAP> formatter. For
1255unbuffered subtests the events are rendered as they are generated. At the end
1256of the subtest, the final subtest event is rendered, but the C<subevents>
1257attribute is ignored. For buffered subtests the opposite occurs, the events are
1258NOT rendered as they are generated, instead the C<subevents> attribute is used
1259to render them all at once. This is useful when running subtests tests in
1260parallel, since without it the output from subtests would be interleaved
1261together.
1262
1263=head1 OTHER API EXPORTS
1264
1265Exports in this section are not commonly needed. These all have the 'test2_'
1266prefix to help ensure they stand out. You should look at the L</MAIN API
1267EXPORTS> section before looking here. This section is one where "Great power
1268comes with great responsibility". It is possible to break things badly if you
1269are not careful with these.
1270
1271All exports are optional. You need to list which ones you want at import time:
1272
1273    use Test2::API qw/test2_init_done .../;
1274
1275=head2 STATUS AND INITIALIZATION STATE
1276
1277These provide access to internal state and object instances.
1278
1279=over 4
1280
1281=item $bool = test2_init_done()
1282
1283This will return true if the stack and IPC instances have already been
1284initialized. It will return false if they have not. Init happens as late as
1285possible. It happens as soon as a tool requests the IPC instance, the
1286formatter, or the stack.
1287
1288=item $bool = test2_load_done()
1289
1290This will simply return the boolean value of the loaded flag. If Test2 has
1291finished loading this will be true, otherwise false. Loading is considered
1292complete the first time a tool requests a context.
1293
1294=item test2_set_is_end()
1295
1296=item test2_set_is_end($bool)
1297
1298This is used to toggle Test2's belief that the END phase has already started.
1299With no arguments this will set it to true. With arguments it will set it to
1300the first argument's value.
1301
1302This is used to prevent the use of C<caller()> in END blocks which can cause
1303segfaults. This is only necessary in some persistent environments that may have
1304multiple END phases.
1305
1306=item $bool = test2_get_is_end()
1307
1308Check if Test2 believes it is the END phase.
1309
1310=item $stack = test2_stack()
1311
1312This will return the global L<Test2::API::Stack> instance. If this has not
1313yet been initialized it will be initialized now.
1314
1315=item $bool = test2_is_testing_done()
1316
1317This will return true if testing is complete and no other events should be
1318sent. This is useful in things like warning handlers where you might want to
1319turn warnings into events, but need them to start acting like normal warnings
1320when testing is done.
1321
1322    $SIG{__WARN__} = sub {
1323        my ($warning) = @_;
1324
1325        if (test2_is_testing_done()) {
1326            warn @_;
1327        }
1328        else {
1329            my $ctx = context();
1330            ...
1331            $ctx->release
1332        }
1333    }
1334
1335=item test2_ipc_disable
1336
1337Disable IPC.
1338
1339=item $bool = test2_ipc_diabled
1340
1341Check if IPC is disabled.
1342
1343=item test2_ipc_wait_enable()
1344
1345=item test2_ipc_wait_disable()
1346
1347=item $bool = test2_ipc_wait_enabled()
1348
1349These can be used to turn IPC waiting on and off, or check the current value of
1350the flag.
1351
1352Waiting is turned on by default. Waiting will cause the parent process/thread
1353to wait until all child processes and threads are finished before exiting. You
1354will almost never want to turn this off.
1355
1356=item $bool = test2_no_wait()
1357
1358=item test2_no_wait($bool)
1359
1360B<DISCOURAGED>: This is a confusing interface, it is better to use
1361C<test2_ipc_wait_enable()>, C<test2_ipc_wait_disable()> and
1362C<test2_ipc_wait_enabled()>.
1363
1364This can be used to get/set the no_wait status. Waiting is turned on by
1365default. Waiting will cause the parent process/thread to wait until all child
1366processes and threads are finished before exiting. You will almost never want
1367to turn this off.
1368
1369=item $fh = test2_stdout()
1370
1371=item $fh = test2_stderr()
1372
1373These functions return the filehandles that test output should be written to.
1374They are primarily useful when writing a custom formatter and code that turns
1375events into actual output (TAP, etc.).  They will return a dupe of the original
1376filehandles that formatted output can be sent to regardless of whatever state
1377the currently running test may have left STDOUT and STDERR in.
1378
1379=item test2_reset_io()
1380
1381Re-dupe the internal filehandles returned by C<test2_stdout()> and
1382C<test2_stderr()> from the current STDOUT and STDERR.  You shouldn't need to do
1383this except in very peculiar situations (for example, you're testing a new
1384formatter and you need control over where the formatter is sending its output.)
1385
1386=back
1387
1388=head2 BEHAVIOR HOOKS
1389
1390These are hooks that allow you to add custom behavior to actions taken by Test2
1391and tools built on top of it.
1392
1393=over 4
1394
1395=item test2_add_callback_exit(sub { ... })
1396
1397This can be used to add a callback that is called after all testing is done. This
1398is too late to add additional results, the main use of this callback is to set the
1399exit code.
1400
1401    test2_add_callback_exit(
1402        sub {
1403            my ($context, $exit, \$new_exit) = @_;
1404            ...
1405        }
1406    );
1407
1408The C<$context> passed in will be an instance of L<Test2::API::Context>. The
1409C<$exit> argument will be the original exit code before anything modified it.
1410C<$$new_exit> is a reference to the new exit code. You may modify this to
1411change the exit code. Please note that C<$$new_exit> may already be different
1412from C<$exit>
1413
1414=item test2_add_callback_post_load(sub { ... })
1415
1416Add a callback that will be called when Test2 is finished loading. This
1417means the callback will be run once, the first time a context is obtained.
1418If Test2 has already finished loading then the callback will be run immediately.
1419
1420=item test2_add_callback_testing_done(sub { ... })
1421
1422This adds your coderef as a follow-up to the root hub after Test2 is finished loading.
1423
1424This is essentially a helper to do the following:
1425
1426    test2_add_callback_post_load(sub {
1427        my $stack = test2_stack();
1428        $stack->top; # Insure we have a hub
1429        my ($hub) = Test2::API::test2_stack->all;
1430
1431        $hub->set_active(1);
1432
1433        $hub->follow_up(sub { ... }); # <-- Your coderef here
1434    });
1435
1436=item test2_add_callback_context_acquire(sub { ... })
1437
1438Add a callback that will be called every time someone tries to acquire a
1439context. This will be called on EVERY call to C<context()>. It gets a single
1440argument, a reference to the hash of parameters being used the construct the
1441context. This is your chance to change the parameters by directly altering the
1442hash.
1443
1444    test2_add_callback_context_acquire(sub {
1445        my $params = shift;
1446        $params->{level}++;
1447    });
1448
1449This is a very scary API function. Please do not use this unless you need to.
1450This is here for L<Test::Builder> and backwards compatibility. This has you
1451directly manipulate the hash instead of returning a new one for performance
1452reasons.
1453
1454=item test2_add_callback_context_init(sub { ... })
1455
1456Add a callback that will be called every time a new context is created. The
1457callback will receive the newly created context as its only argument.
1458
1459=item test2_add_callback_context_release(sub { ... })
1460
1461Add a callback that will be called every time a context is released. The
1462callback will receive the released context as its only argument.
1463
1464=item test2_add_callback_pre_subtest(sub { ... })
1465
1466Add a callback that will be called every time a subtest is going to be
1467run. The callback will receive the subtest name, coderef, and any
1468arguments.
1469
1470=item @list = test2_list_context_acquire_callbacks()
1471
1472Return all the context acquire callback references.
1473
1474=item @list = test2_list_context_init_callbacks()
1475
1476Returns all the context init callback references.
1477
1478=item @list = test2_list_context_release_callbacks()
1479
1480Returns all the context release callback references.
1481
1482=item @list = test2_list_exit_callbacks()
1483
1484Returns all the exit callback references.
1485
1486=item @list = test2_list_post_load_callbacks()
1487
1488Returns all the post load callback references.
1489
1490=item @list = test2_list_pre_subtest_callbacks()
1491
1492Returns all the pre-subtest callback references.
1493
1494=item test2_add_uuid_via(sub { ... })
1495
1496=item $sub = test2_add_uuid_via()
1497
1498This allows you to provide a UUID generator. If provided UUIDs will be attached
1499to all events, hubs, and contexts. This is useful for storing, tracking, and
1500linking these objects.
1501
1502The sub you provide should always return a unique identifier. Most things will
1503expect a proper UUID string, however nothing in Test2::API enforces this.
1504
1505The sub will receive exactly 1 argument, the type of thing being tagged
1506'context', 'hub', or 'event'. In the future additional things may be tagged, in
1507which case new strings will be passed in. These are purely informative, you can
1508(and usually should) ignore them.
1509
1510=back
1511
1512=head2 IPC AND CONCURRENCY
1513
1514These let you access, or specify, the IPC system internals.
1515
1516=over 4
1517
1518=item $bool = test2_has_ipc()
1519
1520Check if IPC is enabled.
1521
1522=item $ipc = test2_ipc()
1523
1524This will return the global L<Test2::IPC::Driver> instance. If this has not yet
1525been initialized it will be initialized now.
1526
1527=item test2_ipc_add_driver($DRIVER)
1528
1529Add an IPC driver to the list. This will add the driver to the start of the
1530list.
1531
1532=item @drivers = test2_ipc_drivers()
1533
1534Get the list of IPC drivers.
1535
1536=item $bool = test2_ipc_polling()
1537
1538Check if polling is enabled.
1539
1540=item test2_ipc_enable_polling()
1541
1542Turn on polling. This will cull events from other processes and threads every
1543time a context is created.
1544
1545=item test2_ipc_disable_polling()
1546
1547Turn off IPC polling.
1548
1549=item test2_ipc_enable_shm()
1550
1551Legacy, this is currently a no-op that returns 0;
1552
1553=item test2_ipc_set_pending($uniq_val)
1554
1555Tell other processes and events that an event is pending. C<$uniq_val> should
1556be a unique value no other thread/process will generate.
1557
1558B<Note:> After calling this C<test2_ipc_get_pending()> will return 1. This is
1559intentional, and not avoidable.
1560
1561=item $pending = test2_ipc_get_pending()
1562
1563This returns -1 if there is no way to check (assume yes)
1564
1565This returns 0 if there are (most likely) no pending events.
1566
1567This returns 1 if there are (likely) pending events. Upon return it will reset,
1568nothing else will be able to see that there were pending events.
1569
1570=item $timeout = test2_ipc_get_timeout()
1571
1572=item test2_ipc_set_timeout($timeout)
1573
1574Get/Set the timeout value for the IPC system. This timeout is how long the IPC
1575system will wait for child processes and threads to finish before aborting.
1576
1577The default value is C<30> seconds.
1578
1579=back
1580
1581=head2 MANAGING FORMATTERS
1582
1583These let you access, or specify, the formatters that can/should be used.
1584
1585=over 4
1586
1587=item $formatter = test2_formatter
1588
1589This will return the global formatter class. This is not an instance. By
1590default the formatter is set to L<Test2::Formatter::TAP>.
1591
1592You can override this default using the C<T2_FORMATTER> environment variable.
1593
1594Normally 'Test2::Formatter::' is prefixed to the value in the
1595environment variable:
1596
1597    $ T2_FORMATTER='TAP' perl test.t     # Use the Test2::Formatter::TAP formatter
1598    $ T2_FORMATTER='Foo' perl test.t     # Use the Test2::Formatter::Foo formatter
1599
1600If you want to specify a full module name you use the '+' prefix:
1601
1602    $ T2_FORMATTER='+Foo::Bar' perl test.t     # Use the Foo::Bar formatter
1603
1604=item test2_formatter_set($class_or_instance)
1605
1606Set the global formatter class. This can only be set once. B<Note:> This will
1607override anything specified in the 'T2_FORMATTER' environment variable.
1608
1609=item @formatters = test2_formatters()
1610
1611Get a list of all loaded formatters.
1612
1613=item test2_formatter_add($class_or_instance)
1614
1615Add a formatter to the list. Last formatter added is used at initialization. If
1616this is called after initialization a warning will be issued.
1617
1618=back
1619
1620=head1 OTHER EXAMPLES
1621
1622See the C</Examples/> directory included in this distribution.
1623
1624=head1 SEE ALSO
1625
1626L<Test2::API::Context> - Detailed documentation of the context object.
1627
1628L<Test2::IPC> - The IPC system used for threading/fork support.
1629
1630L<Test2::Formatter> - Formatters such as TAP live here.
1631
1632L<Test2::Event> - Events live in this namespace.
1633
1634L<Test2::Hub> - All events eventually funnel through a hub. Custom hubs are how
1635C<intercept()> and C<run_subtest()> are implemented.
1636
1637=head1 MAGIC
1638
1639This package has an END block. This END block is responsible for setting the
1640exit code based on the test results. This end block also calls the callbacks that
1641can be added to this package.
1642
1643=head1 SOURCE
1644
1645The source code repository for Test2 can be found at
1646F<http://github.com/Test-More/test-more/>.
1647
1648=head1 MAINTAINERS
1649
1650=over 4
1651
1652=item Chad Granum E<lt>exodist@cpan.orgE<gt>
1653
1654=back
1655
1656=head1 AUTHORS
1657
1658=over 4
1659
1660=item Chad Granum E<lt>exodist@cpan.orgE<gt>
1661
1662=back
1663
1664=head1 COPYRIGHT
1665
1666Copyright 2020 Chad Granum E<lt>exodist@cpan.orgE<gt>.
1667
1668This program is free software; you can redistribute it and/or
1669modify it under the same terms as Perl itself.
1670
1671See F<http://dev.perl.org/licenses/>
1672
1673=cut
1674