This file is indexed.

/usr/share/perl5/Test2/AsyncSubtest.pm is in libtest2-suite-perl 0.000102-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
package Test2::AsyncSubtest;
use strict;
use warnings;

use Test2::IPC;

our $VERSION = '0.000102';

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/;
use List::Util qw/first/;

use Scope::Guard();
use Test2::API();
use Test2::API::Context();
use Test2::Util::Trace();
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 send_to
    events
    finished
    active
    stack
    id
    children
    _in_use
    _attached pid tid
};

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

my @STACK;

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

sub init {
    my $self = shift;

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

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

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

    $self->{+TID}       = get_tid;
    $self->{+PID}       = $$;
    $self->{+ID}        = 1;
    $self->{+FINISHED}  = 0;
    $self->{+ACTIVE}    = 0;
    $self->{+_IN_USE}   = 0;
    $self->{+CHILDREN}  = [];

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

    $self->{+TRACE} ||= Test2::Util::Trace->new(
        frame    => [caller(1)],
        buffered => $to->buffered,
        nested   => $to->nested,
    );

    my $hub = $self->{+HUB};
    $hub->set_ast_ids({}) unless $hub->ast_ids;
    $hub->listen($self->_listener);
    $hub->pre_filter($self->_pre_filter);
}

sub _listener {
    my $self = shift;

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

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

sub _pre_filter {
    my $self = shift;

    sub {
        my ($hub, $e) = @_;
        return $e if $hub->is_local;

        my $attached = $self->{+_ATTACHED};
        return $e if $attached && @$attached && $attached->[0] == $$ && $attached->[1] == get_tid;
        require Data::Dumper;
        my $dump = Data::Dumper::Dumper($e);
        $e->trace->throw(<<"        EOT");
You must attach to an AsyncSubtest before you can send events to it from another process or thread.
Here is a dump of the commit which triggered this exception:
$dump
        EOT
        return;
    };
}

sub context {
    my $self = shift;

    my $send_to = $self->{+SEND_TO};

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

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

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

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

    return $class->new(
        id    => $id,
        trace => Test2::Util::Trace->new(
            frame    => [caller(1)],
            buffered => $hub->buffered,
            nested   => $hub->nested,
        ),
    );
}

sub cleave {
    my $self = shift;
    my $id = $self->{+ID}++;
    $self->{+HUB}->ast_ids->{$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->{+HUB}->ast_ids->{$id};

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

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

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

sub detach {
    my $self = shift;

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

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

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

    my $id = $att->[2];

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

    delete $self->{+_ATTACHED};
}

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

    $hub->cull;

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

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

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

    $self->start;

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

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

    $self->stop;

    my $hub = $self->{+HUB};

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

    unless ($ok) {
        my $e = Test2::Event::Exception->new(
            error => $err,
            trace => Test2::Util::Trace->new(
                frame    => [caller(0)],
                buffered => $hub->buffered,
                nested   => $hub->nested,
            ),
        );
        $hub->send($e);
    }

    return $hub->is_passing;
}

sub start {
    my $self = shift;

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

    $self->{+ACTIVE}++;

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

    return $hub->is_passing;
}

sub stop {
    my $self = shift;

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

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

    pop @STACK;

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

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

    my $hub = $self->hub;

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

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

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

    $self->wait;

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

    my $trace = Test2::Util::Trace->new(
        frame    => $self->{+TRACE}->{frame},
        buffered => $hub->buffered,
        nested   => $hub->nested,
    );

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

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

    return $hub->is_passing if $params{silent};

    my $ctx = $self->context;

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

        my $e = $ctx->build_event(
            'Subtest',
            pass       => $hub->is_passing,
            subtest_id => $hub->id,
            name       => $self->{+NAME},
            buffered   => 1,
            subevents  => $self->{+EVENTS},
            $todo ? (
                todo => $todo,
                effective_pass => 1,
            ) : (),
        );

        $ctx->hub->send($e);

        unless ($e->effective_pass) {
            $ctx->failure_diag($e);

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

        $pass = $e->pass;
    }

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

    return $pass;
}

sub wait {
    my $self = shift;

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

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

    $hub->cull;

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

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

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

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

    $self->attach($id);

    return $self->_guard;
}

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

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

    $self->run($code, @args);

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

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

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

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

        $self->run($code, @args);

        $self->detach(get_tid);
        return 0;
    });

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

    return $thr;
}

sub _guard {
    my $self = shift;

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

    return Scope::Guard->new(sub {
        return unless $$ == $pid && get_tid == $tid;

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

        cluck $error;

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

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

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

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

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

    warn "Subtest $self->{+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<Test2::Event::Subtest> 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->new(name => foo);

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

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

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

    ...

    $ast->finish;

    done_testing;

=head1 CONSTRUCTION

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

=over 4

=item name => $name (required)

Name of the subtest. This construction argument is required.

=item send_to => $hub (optional)

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

=item trace => $trace (optional)

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

=item hub => $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<Test2::AsyncSubtest::Hub>.

=back

=head1 METHODS

=head2 SIMPLE ACCESSORS

=over 4

=item $bool = $ast->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<< $ast->run(...) >> us running.

=item $arrayref = $ast->children

Get an arrayref of child processes/threads. Numerical items are PIDs, blessed
items are L<threads> instances.

=item $arrayref = $ast->events

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

=item $bool = $ast->finished

True if C<finished()> has already been called.

=item $hub = $ast->hub

The hub created for the subtest.

=item $int = $ast->id

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

=item $str = $ast->name

Name of the subtest.

=item $pid = $ast->pid

PID in which the subtest was created.

=item $tid = $ast->tid

Thread ID in which the subtest was created.

=item $hub = $ast->send_to

Hub to which the final subtest event should be sent.

=item $arrayref = $ast->stack

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

=item $trace = $ast->trace

L<Test2::Util::Trace> instance used for error reporting.

=back

=head2 INTERFACE

=over 4

=item $ast->attach($id)

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

B<Note:> C<< my $id = $ast->cleave >> 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<< $ast->attach($id) >>

=item $id = $ast->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<attach()>.

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

=item $ctx = $ast->context

Get an L<Test2::API::Context> 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<< $ctx->release >> on it.

=item $ast->detach

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

=item $ast->finish

=item $ast->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<Note:> This calls C<< $ast->wait >>.

These are the options:

=over 4

=item collapse => 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<Test2::Event::Ok> event.

=item silent => 1

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

=item no_plan => 1

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

=item skip => "reason"

This will issue an L<Test2::Event::Skip> 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->fork

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

It is recommended that you use C<< $ast->run_fork(sub { ... }) >> instead.

=item $bool = $ast->pending

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

=item $bool = $ast->ready

This is essentially C<< !$ast->pending >>.

=item $ast->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->run_fork(sub { ... })

Same as C<< $ast->run() >>, except that the codeblock is run in a child
process.

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

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

B<** DISCOURAGED **> Threads cause problems. This method remains for anyone who
REALYL 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<< $ast->run() >>, except that the codeblock is run in a child
thread.

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

=item $passing = $ast->start

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

=item $ast->stop

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

=item $ast->wait

Wait on all threads/processes that were started using C<< $ast->fork >>,
C<< $ast->run_fork >>, or C<< $ast->run_thread >>.

=back

=head1 SOURCE

The source code repository for Test2-AsyncSubtest can be found at
F<https://github.com/Test-More/Test2-Suite/>.

=head1 MAINTAINERS

=over 4

=item Chad Granum E<lt>exodist@cpan.orgE<gt>

=back

=head1 AUTHORS

=over 4

=item Chad Granum E<lt>exodist@cpan.orgE<gt>

=back

=head1 COPYRIGHT

Copyright 2015 Chad Granum E<lt>exodist7@gmail.comE<gt>.

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

See F<http://dev.perl.org/licenses/>

=cut