1Test::Trap(3)         User Contributed Perl Documentation        Test::Trap(3)
2
3
4

NAME

6       Test::Trap - Trap exit codes, exceptions, output, etc.
7

VERSION

9       Version 0.3.4
10

SYNOPSIS

12         use Test::More;
13         use Test::Trap;
14
15         my @r = trap { some_code(@some_parameters) };
16         is ( $trap->exit, 1, 'Expecting &some_code to exit with 1' );
17         is ( $trap->stdout, '', 'Expecting no STDOUT' );
18         like ( $trap->stderr, qr/^Bad parameters; exiting\b/, 'Expecting warnings.' );
19

DESCRIPTION

21       Primarily (but not exclusively) for use in test scripts: A block eval
22       on steroids, configurable and extensible, but by default trapping
23       (Perl) STDOUT, STDERR, warnings, exceptions, would-be exit codes, and
24       return values from boxed blocks of test code.
25
26       The values collected by the latest trap can then be queried or tested
27       through a special trap object.
28

EXPORT

30       A function and a scalar may be exported by any name.  The function (by
31       default named "trap") is an analogue to block eval(), and the scalar
32       (by default named $trap) is the corresponding analogue to $@.
33
34       Optionally, you may specify the layers of the exported trap.  Layers
35       may be specified by name, with a colon sigil.  Multiple layers may be
36       given in a list, or just stringed together like ":flow:stderr:warn".
37
38       (For the advanced user, you may also specify anonymous layer
39       implementations -- i.e. an appropriate subroutine.)
40
41       See below for a list of the built-in layers, most of which are enabled
42       by default.  Note, finally, that the ordering of the layers matter: The
43       :raw layer is always on the bottom (anything underneath it is ignored),
44       and any other "flow control" layers used should be right down there
45       with it.
46

FUNCTION

48   trap BLOCK
49       This function may be exported by any name, but defaults to "trap".
50
51       By default, traps exceptions (like block eval), but also exits and exit
52       codes, returns and return values, context, and (Perl) output on STDOUT
53       or STDERR, and warnings.  All information trapped can be queried
54       through the trap object, which is by default exported as $trap, but can
55       be exported by any name.
56
57       The value returned from "trap" mimics that returned from "eval":  If
58       the BLOCK would die or exit, it returns an undefined value in scalar
59       context or an empty list in list context; otherwise it returns whatever
60       the BLOCK would return in the given context (also available as the
61       trapped return values).
62

TRAP LAYERS

64       Exactly what the "trap" traps depends on the layers of the trap.  It is
65       possible to register more (see Test::Trap::Builder), but the following
66       layers are pre-defined by this module:
67
68   :raw
69       The only built-in terminating layer, at which the processing of the
70       layers stops, and the actual call to the user code is performed.  On
71       success, it collects the return value(s) in the appropriate context.
72       Pushing the :raw layer on a trap will for most purposes remove all
73       layers below.
74
75   :die
76       The layer emulating block eval, trapping normal exceptions.
77
78   :exit
79       The third "flow control" layer, capturing exit codes if anything used
80       in the dynamic scope of the trap calls CORE::GLOBAL::exit().  (See
81       CAVEATS below for more.)
82
83   :flow
84       A shortcut for :raw:die:exit (effectively pushing all three layers on
85       the trap).  Since this includes :raw, it is also terminating:  Pushing
86       :flow on a trap will effectively remove all layers below.
87
88   :stdout, :stderr
89       Layers trapping Perl output on STDOUT and STDERR, respectively.
90
91   :stdout(perlio), :stderr(perlio)
92       As above, but specifying a capture strategy using PerlIO::scalar.  If
93       this strategy is not available (typically if PerlIO is not), this is an
94       error.  See "CAPTURE STRATEGIES".
95
96   :stdout(tempfile), :stderr(tempfile)
97       As above, but specifying a capture strategy using File::Temp.  Note
98       that this is the default strategy, unless the ":output()" layer is used
99       to set another default.  See "CAPTURE STRATEGIES".
100
101   :stdout(a;b;c), :stderr(a,b,c)
102       (Either syntax, commas or semicolons, is permitted, as is any number of
103       names in the list.)  As above, but specifying the capture strategy by
104       the first existing name among a, b, and c.  If no such strategy is
105       found, this is an error.  See "CAPTURE STRATEGIES".
106
107   :warn
108       A layer trapping warnings, with additional tee: If STDERR is open, it
109       will also print the warnings there.  (This output may be trapped by the
110       :stderr layer, be it above or below the :warn layer.)
111
112   :default
113       A short-cut for :raw:die:exit:stdout:stderr:warn (effectively pushing
114       all six layers on the trap).  Since this includes :raw, it is also
115       terminating:  Pushing :default on a trap will effectively remove all
116       layers below.
117
118       The other interesting property of :default is that it is what every
119       trap starts with:  In order not to include the six layers that make up
120       :default, you need to push a terminating layer (such as :raw or :flow)
121       on the trap.
122
123   :on_fail(m)
124       A (non-default, non-trapping) layer that installs a callback method (by
125       name) m to be run on test failures.  To run the "diag_all" method every
126       time a test fails:
127
128         use Test::Trap qw/ :on_fail(diag_all) /;
129
130   :void, :scalar, :list
131       These (non-default, non-trapping) layers will cause the trapped user
132       code to be run in void, scalar, or list context, respectively.  (By
133       default, the trap will propagate context, that is, it will run the code
134       in whatever context the trap itself is in.)
135
136       If more than one of these layers are pushed on the trap, the deepest
137       (that is, leftmost) takes precedence:
138
139         use Test::Trap qw/ :scalar:void:list /;
140         trap { 42, 13 };
141         $trap->return_is_deeply( [ 13 ], 'Scalar comma.' );
142
143   :output(a;b;c)
144       A (non-default, non-trapping) layer that sets the default capture
145       strategy for any output trapping (":stdout", ":stderr", or other
146       similarly defined) layers below iton the trap.
147
148         use Test::Trap qw/ :output(systemsafe) /;
149         trap { system echo => 'Hello Unix!' }; # trapped!
150
151         use Test::Trap qw/ :flow:stderr:output(systemsafe):stdout /;
152         trap { system echo => 'Hello Unix!' }; # *not* trapped!
153         trap { system q/ echo 'Hello Unix!' >&2 / }; # trapped!
154
155       See "CAPTURE STRATEGIES".
156

CAPTURE STRATEGIES

158       How output is trapped, depends on the capture strategy used.  It is
159       possible to register more (see Test::Trap::Builder), but the following
160       strategies are pre-defined by this module:
161
162   tempfile
163       The default capture strategy, provided by
164       Test::Trap::Builder::TempFile, in which output is temporarily
165       redirected to (and read back from) a tempfile.
166
167   tempfile-preserve
168       A variant of the capture strategy provided by
169       Test::Trap::Builder::TempFile, in which the handles used to write to
170       and read from the tempfile are both binmoded with the same perlio
171       layers as the trapped output handle originally had.
172
173       Caveat emptor: If the handle has perlio custom layers, they may (or may
174       not) fail to apply to the tempfile read and write handles.
175
176   systemsafe
177       A capture strategy provided by Test::Trap::Builder::SystemSafe, like
178       the default strategy, except it outputs on file handles with the same
179       file descriptors as the trapped output handle originally had, and so
180       can be used to trap output from forked-off processes, including
181       system().
182
183       This strategy may be "safe" in relation to forked-off processes, but it
184       is fragile.  For one, it only works with handles that have "real" file
185       descriptors.  For another, it depends on the original file descriptors
186       being available after closing.  (If signal handlers or threads open
187       files, they may well not be.)  And it may fail in other ways.  But in
188       relation to forked-off processes, the other pre-defined strategies will
189       silently fail to trap, as will similarly simple strategies.  This one,
190       when not crashing, will trap that output.
191
192   systemsafe-preserve
193       A variant of the capture strategy provided by
194       Test::Trap::Builder::SystemSafe, in which the handles used to write to
195       and read from the tempfile are both binmoded with the same perlio
196       layers as the trapped output handle originally had.
197
198       Caveat emptor: If the handle has perlio custom layers, they may (or may
199       not) fail to apply to the tempfile read and write handles.
200
201   perlio
202       A capture strategy provided by Test::Trap::Builder::PerlIO, in which
203       output is temporarily redirected to an in-memory file via
204       PerlIO::scalar.
205
206       If PerlIO::scalar is not available, neither is this strategy.
207

RESULT ACCESSORS

209       The following methods may be called on the trap objects after any trap
210       has been sprung, and access the outcome of the run.
211
212       Any property will be undef if not actually trapped -- whether because
213       there is no layer to trap them or because flow control passed them by.
214       (If there is an active and successful trap layer, empty strings and
215       empty arrays trapped will of course be defined.)
216
217       When properties are set, their values will be as follows:
218
219   leaveby
220       A string indicating how the trap terminated: "return", "die", or
221       "exit".
222
223   die
224       The exception, if the latest trap threw one.
225
226   exit
227       The exit code, if the latest trap tried to exit (by way of the trap's
228       own &CORE::GLOBAL::exit only; see "CAVEATS").
229
230   return [INDEX ...]
231       Returns undef if the latest trap did not terminate with a return;
232       otherwise returns three different views of the return array:
233
234       ·   if no INDEX is passed, returns a reference to the array (NB! an
235           empty array of indices qualifies as "no index")
236
237       ·   if called with at least one INDEX in scalar context, returns the
238           array element indexed by the first INDEX (ignoring the rest)
239
240       ·   if called with at least one INDEX in list context, returns the
241           slice of the array by these indices
242
243       Note: The array will hold but a single value if the trap was sprung in
244       scalar context, and will be empty if it was in void context.
245
246   stdout, stderr
247       The captured output on the respective file handles.
248
249   warn [INDEX]
250       Returns undef if the latest trap had no warning-trapping layer;
251       otherwise returns three different views of the warn array:
252
253       ·   if no INDEX is passed, returns a reference to the array (NB! an
254           empty array of indices qualifies as "no index")
255
256       ·   if called with at least one INDEX in scalar context, returns the
257           array element indexed by the first INDEX (ignoring the rest)
258
259       ·   if called with at least one INDEX in list context, returns the
260           slice of the array by these indices
261
262   wantarray
263       The context in which the latest code trapped was called.  (By default a
264       propagated context, but layers can override this.)
265
266   list, scalar, void
267       True if the latest code trapped was called in the indicated context.
268       (By default the code will be called in a propagated context, but layers
269       can override this.)
270

RESULT TESTS

272       For each accessor, a number of convenient standard test methods are
273       also available.  By default, these are a few standard tests from
274       Test::More, plus the "nok" test (a negated "ok" test).  All for
275       convenience:
276
277   ACCESSOR_ok        [INDEX,] TEST_NAME
278   ACCESSOR_nok       [INDEX,] TEST_NAME
279   ACCESSOR_is        [INDEX,] SCALAR, TEST_NAME
280   ACCESSOR_isnt      [INDEX,] SCALAR, TEST_NAME
281   ACCESSOR_isa_ok    [INDEX,] SCALAR, INVOCANT_NAME
282   ACCESSOR_like      [INDEX,] REGEX, TEST_NAME
283   ACCESSOR_unlike    [INDEX,] REGEX, TEST_NAME
284   ACCESSOR_is_deeply          STRUCTURE, TEST_NAME
285       INDEX is not optional:  It is required for array accessors (like
286       "return" and "warn"), and disallowed for scalar accessors.  Note that
287       the "is_deeply" test does not accept an index.  Even for array
288       accessors, it operates on the entire array.
289
290       For convenience and clarity, tests against a flow control ACCESSOR
291       ("return", "die", "exit", or any you define yourself) will first test
292       whether the trap was left by way of the flow control mechanism in
293       question, and fail with appropriate diagnostics otherwise.
294
295   did_die, did_exit, did_return
296       Conveniences: Tests whether the trap was left by way of the flow
297       control mechanism in question.  Much like "leaveby_is('die')" etc, but
298       with better diagnostics and (run-time) spell checking.
299
300   quiet
301       Convenience: Passes if zero-length output was trapped on both STDOUT
302       and STDERR, and generate better diagnostics otherwise.
303

UTILITIES

305   diag_all
306       Prints a diagnostic message (as per "diag" in Test::More) consisting of
307       a dump (in Perl code, as per Data::Dump) of the trap object.
308
309   diag_all_once
310       As "diag_all", except if this instance of the trap object has already
311       been diag_all_once'd, the diagnostic message will instead consist of
312       the string "(as above)".
313
314       This could be useful with the "on_fail" layer:
315
316         use Test::Trap qw/ :on_fail(diag_all_once) /;
317

CAVEATS

319       This module must be loaded before any code containing exit()s to be
320       trapped is compiled.  Any exit() already compiled won't be trappable,
321       and will terminate the program anyway.
322
323       This module overrides &CORE::GLOBAL::exit, so may not work correctly
324       (or even at all) in the presence of other code overriding
325       &CORE::GLOBAL::exit.  More precisely: This module installs its own
326       exit() on entry of the block, and restores the previous one, if any,
327       only upon leaving the block.
328
329       If you use fork() in the dynamic scope of a trap, beware that the
330       (default) :exit layer of that trap does not trap exit() in the
331       children, but passes them to the outer handler.  If you think about it,
332       this is what you are likely to want it to do in most cases.
333
334       Note that the (default) :exit layer only traps &CORE::GLOBAL::exit
335       calls (and bare exit() calls that compile to that).  It makes no
336       attempt to trap CORE::exit(), POSIX::_exit(), exec(), untrapped
337       exceptions from die(), nor segfault.  Nor does it attempt to trap
338       anything else that might terminate the program.  The trap is a block
339       eval on steroids -- not the last block eval of Krypton!
340
341       This module traps warnings using $SIG{__WARN__}, so may not work
342       correctly (or even at all) in the presence of other code setting this
343       handler.  More precisely: This module installs its own __WARN__ handler
344       on entry of the block, and restores the previous one, if any, only upon
345       leaving the block.
346
347       The (default) :stdout and :stderr handlers will not trap output from
348       system() calls.
349
350       Threads?  No idea.  It might even work correctly.
351

BUGS

353       Please report any bugs or feature requests directly to the author.
354

AUTHOR

356       Eirik Berg Hanssen, "<ebhanssen@cpan.org>"
357
359       Copyright 2006-2014 Eirik Berg Hanssen, All Rights Reserved.
360
361       This program is free software; you can redistribute it and/or modify it
362       under the same terms as Perl itself.
363
364
365
366perl v5.32.0                      2020-07-28                     Test::Trap(3)
Impressum