<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">package Test2::AsyncSubtest;
use strict;
use warnings;

use Test2::IPC;

our $VERSION = '0.000162';

our @CARP_NOT = qw/Test2::Util::HashBase/;

use Carp qw/croak cluck confess/;
use Test2::Util qw/get_tid CAN_THREAD CAN_FORK/;
use Scalar::Util qw/blessed weaken/;
use List::Util qw/first/;

use Test2::API();
use Test2::API::Context();
use Test2::Util::Trace();
use Test2::Util::Guard();
use Time::HiRes();

use Test2::AsyncSubtest::Hub();
use Test2::AsyncSubtest::Event::Attach();
use Test2::AsyncSubtest::Event::Detach();

use Test2::Util::HashBase qw{
    name hub
    trace frame send_to
    events
    finished
    active
    stack
    id cid uuid
    children
    _in_use
    _attached pid tid
    start_stamp stop_stamp
};

sub CAN_REALLY_THREAD {
    return 0 unless CAN_THREAD;
    return 0 unless eval { require threads; threads-&gt;VERSION('1.34'); 1 };
    return 1;
}


my $UUID_VIA = Test2::API::_add_uuid_via_ref();
my $CID = 1;
my @STACK;

sub TOP { @STACK ? $STACK[-1] : undef }

sub init {
    my $self = shift;

    croak "'name' is a required attribute"
        unless $self-&gt;{+NAME};

    my $to = $self-&gt;{+SEND_TO} ||= Test2::API::test2_stack()-&gt;top;

    $self-&gt;{+STACK} = [@STACK];
    $_-&gt;{+_IN_USE}++ for reverse @STACK;

    $self-&gt;{+TID}       = get_tid;
    $self-&gt;{+PID}       = $$;
    $self-&gt;{+CID}       = 'AsyncSubtest-' . $CID++;
    $self-&gt;{+ID}        = 1;
    $self-&gt;{+FINISHED}  = 0;
    $self-&gt;{+ACTIVE}    = 0;
    $self-&gt;{+_IN_USE}   = 0;
    $self-&gt;{+CHILDREN}  = [];
    $self-&gt;{+UUID} = ${$UUID_VIA}-&gt;() if defined $$UUID_VIA;

    unless($self-&gt;{+HUB}) {
        my $ipc = Test2::API::test2_ipc();
        my $formatter = Test2::API::test2_stack-&gt;top-&gt;format;
        my $args = delete $self-&gt;{hub_init_args} || {};
        my $hub = Test2::AsyncSubtest::Hub-&gt;new(
            %$args,
            ipc       =&gt; $ipc,
            nested    =&gt; $to-&gt;nested + 1,
            buffered  =&gt; 1,
            formatter =&gt; $formatter,
        );
        weaken($hub-&gt;{ast} = $self);
        $self-&gt;{+HUB} = $hub;
    }

    $self-&gt;{+TRACE} ||= Test2::Util::Trace-&gt;new(
        frame    =&gt; $self-&gt;{+FRAME} || [caller(1)],
        buffered =&gt; $to-&gt;buffered,
        nested   =&gt; $to-&gt;nested,
        cid      =&gt; $self-&gt;{+CID},
        uuid     =&gt; $self-&gt;{+UUID},
        hid      =&gt; $to-&gt;hid,
        huuid    =&gt; $to-&gt;uuid,
    );

    my $hub = $self-&gt;{+HUB};
    $hub-&gt;set_ast_ids({}) unless $hub-&gt;ast_ids;
    $hub-&gt;listen($self-&gt;_listener);
}

sub _listener {
    my $self = shift;

    my $events = $self-&gt;{+EVENTS} ||= [];

    sub { push @$events =&gt; $_[1] };
}

sub context {
    my $self = shift;

    my $send_to = $self-&gt;{+SEND_TO};

    confess "Attempt to close AsyncSubtest when original parent hub (a non async-subtest?) has ended"
        if $send_to-&gt;ended;

    return Test2::API::Context-&gt;new(
        trace =&gt; $self-&gt;{+TRACE},
        hub   =&gt; $send_to,
    );
}

sub _gen_event {
    my $self = shift;
    my ($type, $id, $hub) = @_;

    my $class = "Test2::AsyncSubtest::Event::$type";

    return $class-&gt;new(
        id    =&gt; $id,
        trace =&gt; Test2::Util::Trace-&gt;new(
            frame    =&gt; [caller(1)],
            buffered =&gt; $hub-&gt;buffered,
            nested   =&gt; $hub-&gt;nested,
            cid      =&gt; $self-&gt;{+CID},
            uuid     =&gt; $self-&gt;{+UUID},
            hid      =&gt; $hub-&gt;hid,
            huuid    =&gt; $hub-&gt;uuid,
        ),
    );
}

sub cleave {
    my $self = shift;
    my $id = $self-&gt;{+ID}++;
    $self-&gt;{+HUB}-&gt;ast_ids-&gt;{$id} = 0;
    return $id;
}

sub attach {
    my $self = shift;
    my ($id) = @_;

    croak "An ID is required" unless $id;

    croak "ID $id is not valid"
        unless defined $self-&gt;{+HUB}-&gt;ast_ids-&gt;{$id};

    croak "ID $id is already attached"
        if $self-&gt;{+HUB}-&gt;ast_ids-&gt;{$id};

    croak "You must attach INSIDE the child process/thread"
        if $self-&gt;{+HUB}-&gt;is_local;

    $self-&gt;{+_ATTACHED} = [ $$, get_tid, $id ];
    $self-&gt;{+HUB}-&gt;send($self-&gt;_gen_event('Attach', $id, $self-&gt;{+HUB}));
}

sub detach {
    my $self = shift;

    if ($self-&gt;{+PID} == $$ &amp;&amp; $self-&gt;{+TID} == get_tid) {
        cluck "You must detach INSIDE the child process/thread ($$, " . get_tid . " instead of $self-&gt;{+PID}, $self-&gt;{+TID})";
        return;
    }

    my $att = $self-&gt;{+_ATTACHED}
        or croak "Not attached";

    croak "Attempt to detach from wrong child"
        unless $att-&gt;[0] == $$ &amp;&amp; $att-&gt;[1] == get_tid;

    my $id = $att-&gt;[2];

    $self-&gt;{+HUB}-&gt;send($self-&gt;_gen_event('Detach', $id, $self-&gt;{+HUB}));

    delete $self-&gt;{+_ATTACHED};
}

sub ready { return !shift-&gt;pending }
sub pending {
    my $self = shift;
    my $hub = $self-&gt;{+HUB};
    return -1 unless $hub-&gt;is_local;

    $hub-&gt;cull;

    return $self-&gt;{+_IN_USE} + keys %{$self-&gt;{+HUB}-&gt;ast_ids};
}

sub run {
    my $self = shift;
    my ($code, @args) = @_;

    croak "AsyncSubtest-&gt;run() takes a codeblock as the first argument"
        unless $code &amp;&amp; ref($code) eq 'CODE';

    $self-&gt;start;

    my ($ok, $err, $finished);
    T2_SUBTEST_WRAPPER: {
        $ok = eval { $code-&gt;(@args); 1 };
        $err = $@;

        # They might have done 'BEGIN { skip_all =&gt; "whatever" }'
        if (!$ok &amp;&amp; $err =~ m/Label not found for "last T2_SUBTEST_WRAPPER"/) {
            $ok  = undef;
            $err = undef;
        }
        else {
            $finished = 1;
        }
    }

    $self-&gt;stop;

    my $hub = $self-&gt;{+HUB};

    if (!$finished) {
        if(my $bailed = $hub-&gt;bailed_out) {
            my $ctx = $self-&gt;context;
            $ctx-&gt;bail($bailed-&gt;reason);
            return;
        }
        my $code = $hub-&gt;exit_code;
        $ok = !$code;
        $err = "Subtest ended with exit code $code" if $code;
    }

    unless ($ok) {
        my $e = Test2::Event::Exception-&gt;new(
            error =&gt; $err,
            trace =&gt; Test2::Util::Trace-&gt;new(
                frame    =&gt; [caller(0)],
                buffered =&gt; $hub-&gt;buffered,
                nested   =&gt; $hub-&gt;nested,
                cid      =&gt; $self-&gt;{+CID},
                uuid     =&gt; $self-&gt;{+UUID},
                hid      =&gt; $hub-&gt;hid,
                huuid    =&gt; $hub-&gt;uuid,
            ),
        );
        $hub-&gt;send($e);
    }

    return $hub-&gt;is_passing;
}

sub start {
    my $self = shift;

    croak "Subtest is already complete"
        if $self-&gt;{+FINISHED};

    $self-&gt;{+START_STAMP} = Time::HiRes::time() unless defined $self-&gt;{+START_STAMP};

    $self-&gt;{+ACTIVE}++;

    push @STACK =&gt; $self;
    my $hub = $self-&gt;{+HUB};
    my $stack = Test2::API::test2_stack();
    $stack-&gt;push($hub);

    return $hub-&gt;is_passing;
}

sub stop {
    my $self = shift;

    croak "Subtest is not active"
        unless $self-&gt;{+ACTIVE}--;

    croak "AsyncSubtest stack mismatch"
        unless @STACK &amp;&amp; $self == $STACK[-1];

    $self-&gt;{+STOP_STAMP} = Time::HiRes::time();

    pop @STACK;

    my $hub = $self-&gt;{+HUB};
    my $stack = Test2::API::test2_stack();
    $stack-&gt;pop($hub);
    return $hub-&gt;is_passing;
}

sub finish {
    my $self = shift;
    my %params = @_;

    my $hub = $self-&gt;hub;

    croak "Subtest is already finished"
        if $self-&gt;{+FINISHED}++;

    croak "Subtest can only be finished in the process/thread that created it"
        unless $hub-&gt;is_local;

    croak "Subtest is still active"
        if $self-&gt;{+ACTIVE};

    $self-&gt;wait;
    $self-&gt;{+STOP_STAMP} = Time::HiRes::time() unless defined $self-&gt;{+STOP_STAMP};
    my $stop_stamp = $self-&gt;{+STOP_STAMP};

    my $todo       = $params{todo};
    my $skip       = $params{skip};
    my $empty      = !@{$self-&gt;{+EVENTS}};
    my $no_asserts = !$hub-&gt;count;
    my $collapse   = $params{collapse};
    my $no_plan    = $params{no_plan} || ($collapse &amp;&amp; $no_asserts) || $skip;

    my $trace = Test2::Util::Trace-&gt;new(
        frame    =&gt; $self-&gt;{+TRACE}-&gt;{frame},
        buffered =&gt; $hub-&gt;buffered,
        nested   =&gt; $hub-&gt;nested,
        cid      =&gt; $self-&gt;{+CID},
        uuid     =&gt; $self-&gt;{+UUID},
        hid      =&gt; $hub-&gt;hid,
        huuid    =&gt; $hub-&gt;uuid,
    );

    $hub-&gt;finalize($trace, !$no_plan)
        unless $hub-&gt;no_ending || $hub-&gt;ended;

    if ($hub-&gt;ipc) {
        $hub-&gt;ipc-&gt;drop_hub($hub-&gt;hid);
        $hub-&gt;set_ipc(undef);
    }

    return $hub-&gt;is_passing if $params{silent};

    my $ctx = $self-&gt;context;

    my $pass = 1;
    if ($skip) {
        $ctx-&gt;skip($self-&gt;{+NAME}, $skip);
    }
    else {
        if ($collapse &amp;&amp; $empty) {
            $ctx-&gt;ok($hub-&gt;is_passing, $self-&gt;{+NAME});
            return $hub-&gt;is_passing;
        }

        if ($collapse &amp;&amp; $no_asserts) {
            push @{$self-&gt;{+EVENTS}} =&gt; Test2::Event::Plan-&gt;new(trace =&gt; $trace, max =&gt; 0, directive =&gt; 'SKIP', reason =&gt; "No assertions");
        }

        my $e = $ctx-&gt;build_event(
            'Subtest',
            pass         =&gt; $hub-&gt;is_passing,
            subtest_id   =&gt; $hub-&gt;id,
            subtest_uuid =&gt; $hub-&gt;uuid,
            name         =&gt; $self-&gt;{+NAME},
            buffered     =&gt; 1,
            subevents    =&gt; $self-&gt;{+EVENTS},
            start_stamp  =&gt; $self-&gt;{+START_STAMP},
            stop_stamp   =&gt; $self-&gt;{+STOP_STAMP},
            $todo ? (
                todo =&gt; $todo,
                effective_pass =&gt; 1,
            ) : (),
        );

        $ctx-&gt;hub-&gt;send($e);

        unless ($e-&gt;effective_pass) {
            $ctx-&gt;failure_diag($e);

            $ctx-&gt;diag("Bad subtest plan, expected " . $hub-&gt;plan . " but ran " . $hub-&gt;count)
                if $hub-&gt;plan &amp;&amp; !$hub-&gt;check_plan &amp;&amp; !grep {$_-&gt;causes_fail} @{$self-&gt;{+EVENTS}};
        }

        $pass = $e-&gt;pass;
    }

    $_-&gt;{+_IN_USE}-- for reverse @{$self-&gt;{+STACK}};

    return $pass;
}

sub wait {
    my $self = shift;

    my $hub = $self-&gt;{+HUB};
    my $children = $self-&gt;{+CHILDREN};

    while (@$children) {
        $hub-&gt;cull;
        if (my $child = pop @$children) {
            if (blessed($child)) {
                $child-&gt;join;
            }
            else {
                waitpid($child, 0);
            }
        }
        else {
            Time::HiRes::sleep('0.01');
        }
    }

    $hub-&gt;cull;

    cluck "Subtest '$self-&gt;{+NAME}': All children have completed, but we still appear to be pending"
        if $hub-&gt;is_local &amp;&amp; keys %{$self-&gt;{+HUB}-&gt;ast_ids};
}

sub fork {
    croak "Forking is not supported" unless CAN_FORK;
    my $self = shift;
    my $id = $self-&gt;cleave;
    my $pid = CORE::fork();

    unless (defined $pid) {
        delete $self-&gt;{+HUB}-&gt;ast_ids-&gt;{$id};
        croak "Failed to fork";
    }

    if($pid) {
        push @{$self-&gt;{+CHILDREN}} =&gt; $pid;
        return $pid;
    }

    $self-&gt;attach($id);

    return $self-&gt;_guard;
}

sub run_fork {
    my $self = shift;
    my ($code, @args) = @_;

    my $f = $self-&gt;fork;
    return $f unless blessed($f);

    $self-&gt;run($code, @args);

    $self-&gt;detach();
    $f-&gt;dismiss();
    exit 0;
}

sub run_thread {
    croak "Threading is not supported"
        unless CAN_REALLY_THREAD;

    my $self = shift;
    my ($code, @args) = @_;

    my $id = $self-&gt;cleave;
    my $thr =  threads-&gt;create(sub {
        $self-&gt;attach($id);

        $self-&gt;run($code, @args);

        $self-&gt;detach(get_tid);
        return 0;
    });

    push @{$self-&gt;{+CHILDREN}} =&gt; $thr;

    return $thr;
}

sub _guard {
    my $self = shift;

    my ($pid, $tid) = ($$, get_tid);

    return Test2::Util::Guard-&gt;new(sub {
        return unless $$ == $pid &amp;&amp; get_tid == $tid;

        my $error = "Scope Leak";
        if (my $ex = $@) {
            chomp($ex);
            $error .= " ($ex)";
        }

        cluck $error;

        my $e = $self-&gt;context-&gt;build_event(
            'Exception',
            error =&gt; "$error\n",
        );
        $self-&gt;{+HUB}-&gt;send($e);
        $self-&gt;detach();
        exit 255;
    });
}

sub DESTROY {
    my $self = shift;
    return unless $self-&gt;{+NAME};

    if (my $att = $self-&gt;{+_ATTACHED}) {
        return unless $self-&gt;{+HUB};
        eval { $self-&gt;detach() };
    }

    return if $self-&gt;{+FINISHED};
    return unless $self-&gt;{+PID} == $$;
    return unless $self-&gt;{+TID} == get_tid;

    local $@;
    eval { $_-&gt;{+_IN_USE}-- for reverse @{$self-&gt;{+STACK}} };

    warn "Subtest $self-&gt;{+NAME} did not finish!";
    exit 255;
}

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

Test2::AsyncSubtest - Object representing an async subtest.

=head1 DESCRIPTION

Regular subtests have a limited scope, they start, events are generated, then
they close and send an L&lt;Test2::Event::Subtest&gt; event. This is a problem if you
want the subtest to keep receiving events while other events are also being
generated. This class implements subtests that stay open until you decide to
close them.

This is mainly useful for tools that start a subtest in one process and then
spawn children. In many cases it is nice to let the parent process continue
instead of waiting on the children.

=head1 SYNOPSIS

    use Test2::AsyncSubtest;

    my $ast = Test2::AsyncSubtest-&gt;new(name =&gt; foo);

    $ast-&gt;run(sub {
        ok(1, "Event in parent" );
    });

    ok(1, "Event outside of subtest");

    $ast-&gt;run_fork(sub {
        ok(1, "Event in child process");
    });

    ...

    $ast-&gt;finish;

    done_testing;

=head1 CONSTRUCTION

    my $ast = Test2::AsyncSubtest-&gt;new( ... );

=over 4

=item name =&gt; $name (required)

Name of the subtest. This construction argument is required.

=item send_to =&gt; $hub (optional)

Hub to which the final subtest event should be sent. This must be an instance
of L&lt;Test2::Hub&gt; or a subclass. If none is specified then the current top hub
will be used.

=item trace =&gt; $trace (optional)

File/Line to which errors should be attributed. This must be an instance of
L&lt;Test2::Util::Trace&gt;. If none is specified then the file/line where the
constructor was called will be used.

=item hub =&gt; $hub (optional)

Use this to specify a hub the subtest should use. By default a new hub is
generated. This must be an instance of L&lt;Test2::AsyncSubtest::Hub&gt;.

=back

=head1 METHODS

=head2 SIMPLE ACCESSORS

=over 4

=item $bool = $ast-&gt;active

True if the subtest is active. The subtest is active if its hub appears in the
global hub stack. This is true when C&lt;&lt; $ast-&gt;run(...) &gt;&gt; us running.

=item $arrayref = $ast-&gt;children

Get an arrayref of child processes/threads. Numerical items are PIDs, blessed
items are L&lt;threads&gt; instances.

=item $arrayref = $ast-&gt;events

Get an arrayref of events that have been sent to the subtests hub.

=item $bool = $ast-&gt;finished

True if C&lt;finished()&gt; has already been called.

=item $hub = $ast-&gt;hub

The hub created for the subtest.

=item $int = $ast-&gt;id

Attach/Detach counter. Used internally, not useful to users.

=item $str = $ast-&gt;name

Name of the subtest.

=item $pid = $ast-&gt;pid

PID in which the subtest was created.

=item $tid = $ast-&gt;tid

Thread ID in which the subtest was created.

=item $hub = $ast-&gt;send_to

Hub to which the final subtest event should be sent.

=item $arrayref = $ast-&gt;stack

Stack of async subtests at the time this one was created. This is mainly for
internal use.

=item $trace = $ast-&gt;trace

L&lt;Test2::Util::Trace&gt; instance used for error reporting.

=back

=head2 INTERFACE

=over 4

=item $ast-&gt;attach($id)

Attach a subtest in a child/process to the original.

B&lt;Note:&gt; C&lt;&lt; my $id = $ast-&gt;cleave &gt;&gt; must have been called in the parent
process/thread before the child was started, the id it returns must be used in
the call to C&lt;&lt; $ast-&gt;attach($id) &gt;&gt;

=item $id = $ast-&gt;cleave

Prepare a slot for a child process/thread to attach. This must be called BEFORE
the child process or thread is started. The ID returned is used by C&lt;attach()&gt;.

This must only be called in the original process/thread.

=item $ctx = $ast-&gt;context

Get an L&lt;Test2::API::Context&gt; instance that can be used to send events to the
context in which the hub was created. This is not a canonical context, you
should not call C&lt;&lt; $ctx-&gt;release &gt;&gt; on it.

=item $ast-&gt;detach

Detach from the parent in a child process/thread. This should be called just
before the child exits.

=item $ast-&gt;finish

=item $ast-&gt;finish(%options)

Finish the subtest, wait on children, and send the final subtest event.

This must only be called in the original process/thread.

B&lt;Note:&gt; This calls C&lt;&lt; $ast-&gt;wait &gt;&gt;.

These are the options:

=over 4

=item collapse =&gt; 1

This intelligently allows a subtest to be empty.

If no events bump the test count then the subtest no final plan will be added.
The subtest will not be considered a failure (normally an empty subtest is a
failure).

If there are no events at all the subtest will be collapsed into an
L&lt;Test2::Event::Ok&gt; event.

=item silent =&gt; 1

This will prevent finish from generating a final L&lt;Test2::Event::Subtest&gt;
event. This effectively ends the subtest without it effecting the parent
subtest (or top level test).

=item no_plan =&gt; 1

This will prevent a final plan from being added to the subtest for you when
none is directly specified.

=item skip =&gt; "reason"

This will issue an L&lt;Test2::Event::Skip&gt; instead of a subtest. This will throw
an exception if any events have been seen, or if state implies events have
occurred.

=back

=item $out = $ast-&gt;fork

This is a slightly higher level interface to fork. Running it will fork your
code in-place just like C&lt;fork()&gt;. It will return a pid in the parent, and an
L&lt;Test2::Util::Guard&gt; instance in the child. An exception will be thrown if
fork fails.

It is recommended that you use C&lt;&lt; $ast-&gt;run_fork(sub { ... }) &gt;&gt; instead.

=item $bool = $ast-&gt;pending

True if there are child processes, threads, or subtests that depend on this
one.

=item $bool = $ast-&gt;ready

This is essentially C&lt;&lt; !$ast-&gt;pending &gt;&gt;.

=item $ast-&gt;run(sub { ... })

Run the provided codeblock inside the subtest. This will push the subtest hub
onto the stack, run the code, then pop the hub off the stack.

=item $pid = $ast-&gt;run_fork(sub { ... })

Same as C&lt;&lt; $ast-&gt;run() &gt;&gt;, except that the codeblock is run in a child
process.

You do not need to directly call C&lt;wait($pid)&gt;, that will be done for you when
C&lt;&lt; $ast-&gt;wait &gt;&gt;, or C&lt;&lt; $ast-&gt;finish &gt;&gt; are called.

=item my $thr = $ast-&gt;run_thread(sub { ... });

B&lt;** DISCOURAGED **&gt; Threads cause problems. This method remains for anyone who
REALLY wants it, but it is no longer supported. Tests for this functionality do
not even run unless the AUTHOR_TESTING or T2_DO_THREAD_TESTS env vars are
enabled.

Same as C&lt;&lt; $ast-&gt;run() &gt;&gt;, except that the codeblock is run in a child
thread.

You do not need to directly call C&lt;&lt; $thr-&gt;join &gt;&gt;, that is done for you when
C&lt;&lt; $ast-&gt;wait &gt;&gt;, or C&lt;&lt; $ast-&gt;finish &gt;&gt; are called.

=item $passing = $ast-&gt;start

Push the subtest hub onto the stack. Returns the current pass/fail status of
the subtest.

=item $ast-&gt;stop

Pop the subtest hub off the stack. Returns the current pass/fail status of the
subtest.

=item $ast-&gt;wait

Wait on all threads/processes that were started using C&lt;&lt; $ast-&gt;fork &gt;&gt;,
C&lt;&lt; $ast-&gt;run_fork &gt;&gt;, or C&lt;&lt; $ast-&gt;run_thread &gt;&gt;.

=back

=head1 SOURCE

The source code repository for Test2-AsyncSubtest can be found at
F&lt;https://github.com/Test-More/Test2-Suite/&gt;.

=head1 MAINTAINERS

=over 4

=item Chad Granum E&lt;lt&gt;exodist@cpan.orgE&lt;gt&gt;

=back

=head1 AUTHORS

=over 4

=item Chad Granum E&lt;lt&gt;exodist@cpan.orgE&lt;gt&gt;

=back

=head1 COPYRIGHT

Copyright 2018 Chad Granum E&lt;lt&gt;exodist7@gmail.comE&lt;gt&gt;.

This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.

See F&lt;http://dev.perl.org/licenses/&gt;

=cut
</pre></body></html>