1package Test2::Tools::Grab;
2use strict;
3use warnings;
4
5our $VERSION = '0.000162';
6
7use Test2::Util::Grabber;
8use Test2::EventFacet::Trace();
9
10our @EXPORT = qw/grab/;
11use base 'Exporter';
12
13sub grab { Test2::Util::Grabber->new(trace => Test2::EventFacet::Trace->new(frame => [caller(0)]) ) }
14
151;
16
17__END__
18
19=pod
20
21=encoding UTF-8
22
23=head1 NAME
24
25Test2::Tools::Grab - Temporarily intercept all events without adding a scope
26level.
27
28=head1 DESCRIPTION
29
30This package provides a function that returns an object that grabs all events.
31Once the object is destroyed events will once again be sent to the main hub.
32
33=head1 SYNOPSIS
34
35    use Test2::Tools::Grab;
36
37    my $grab = grab();
38
39    # Generate some events, they are intercepted.
40    ok(1, "pass");
41    ok(0, "fail");
42
43    my $events_a = $grab->flush;
44
45    # Generate some more events, they are intercepted.
46    ok(1, "pass");
47    ok(0, "fail");
48
49    my $events_b = $grab->finish;
50
51=head1 EXPORTS
52
53=over 4
54
55=item $grab = grab()
56
57This lets you intercept all events for a section of code without adding
58anything to your call stack. This is useful for things that are sensitive to
59changes in the stack depth.
60
61    my $grab = grab();
62        ok(1, 'foo');
63        ok(0, 'bar');
64
65    my $events = $grab->finish;
66
67    is(@$events, 2, "grabbed 2 events.");
68
69If the C<$grab> object is destroyed without calling C<finish()>, it will
70automatically clean up after itself and restore the parent hub.
71
72    {
73        my $grab = grab();
74        # Things are grabbed
75    }
76    # Things are back to normal
77
78By default the hub used has C<no_ending> set to true. This will prevent the hub
79from enforcing that you issued a plan and ran at least 1 test. You can turn
80enforcement back one like this:
81
82    $grab->hub->set_no_ending(0);
83
84With C<no_ending> turned off, C<finish> will run the post-test checks to
85enforce the plan and that tests were run. In many cases this will result in
86additional events in your events array.
87
88=back
89
90=head1 SEE ALSO
91
92L<Test2::Util::Grabber> - The object constructed and returned by this tool.
93
94=head1 SOURCE
95
96The source code repository for Test2 can be found at
97F<https://github.com/Test-More/Test2-Suite/>.
98
99=head1 MAINTAINERS
100
101=over 4
102
103=item Chad Granum E<lt>exodist@cpan.orgE<gt>
104
105=back
106
107=head1 AUTHORS
108
109=over 4
110
111=item Chad Granum E<lt>exodist@cpan.orgE<gt>
112
113=back
114
115=head1 COPYRIGHT
116
117Copyright 2018 Chad Granum E<lt>exodist@cpan.orgE<gt>.
118
119This program is free software; you can redistribute it and/or
120modify it under the same terms as Perl itself.
121
122See F<http://dev.perl.org/licenses/>
123
124=cut
125