Spec-Zone .ru
спецификации, руководства, описания, API
Spec-Zone .ru
спецификации, руководства, описания, API
Библиотека разработчика Mac Разработчик
Поиск

 

Эта страница руководства для  версии 10.9 Mac OS X

Если Вы выполняете различную версию  Mac OS X, просматриваете документацию локально:

Читать страницы руководства

Страницы руководства предназначаются как справочник для людей, уже понимающих технологию.

  • Чтобы изучить, как руководство организовано или узнать о синтаксисе команды, прочитайте страницу руководства для страниц справочника (5).

  • Для получения дополнительной информации об этой технологии, ищите другую документацию в Библиотеке Разработчика Apple.

  • Для получения общей информации о записи сценариев оболочки, считайте Shell, Пишущий сценарий Учебника для начинающих.



Test::Trap(3)                        User Contributed Perl Documentation                       Test::Trap(3)



NAME
       Test::Trap - Trap exit codes, exceptions, output, etc.

VERSION
       Version 0.2.2

SYNOPSIS
         use Test::More;
         use Test::Trap;

         my @r = trap { some_code(@some_parameters) };
         is ( $trap->exit, 1, 'Expecting &some_code to exit with 1' );
         is ( $trap->stdout, '', 'Expecting no STDOUT' );
         like ( $trap->stderr, qr/^Bad parameters; exiting\b/, 'Expecting warnings.' );

DESCRIPTION
       Primarily (but not exclusively) for use in test scripts: A block eval on steroids, configurable and
       extensible, but by default trapping (Perl) STDOUT, STDERR, warnings, exceptions, would-be exit codes,
       and return values from boxed blocks of test code.

       The values collected by the latest trap can then be queried or tested through a special trap object.

EXPORT
       A function and a scalar may be exported by any name.  The function (by default named "trap") is an
       analogue to block eval(), and the scalar (by default named $trap) is the corresponding analogue to
       $@.

       Optionally, you may specify the layers of the exported trap.  Layers may be specified by name, with a
       colon sigil.  Multiple layers may be given in a list, or just stringed together like
       ":flow:stderr:warn".

       (For the advanced user, you may also specify anonymous layer implementations -- i.e. an appropriate
       subroutine.)

       See below for a list of the built-in layers, most of which are enabled by default.  Note, finally,
       that the ordering of the layers matter: The :raw layer is always on the bottom (anything underneath
       it is ignored), and any other "flow control" layers used should be right down there with it.

FUNCTION
   trap BLOCK
       This function may be exported by any name, but defaults to "trap".

       By default, traps exceptions (like block eval), but also exits and exit codes, returns and return
       values, context, and (Perl) output on STDOUT or STDERR, and warnings.  All information trapped can be
       queried through the trap object, which is by default exported as $trap, but can be exported by any
       name.

       The value returned from "trap" mimics that returned from "eval":  If the BLOCK would die or exit, it
       returns an undefined value in scalar context or an empty list in list context; otherwise it returns
       whatever the BLOCK would return in the given context (also available as the trapped return values).

TRAP LAYERS
       Exactly what the "trap" traps depends on the layers of the trap.  It is possible to register more
       (see Test::Trap::Builder), but the following layers are pre-defined by this module:

   :raw
       The terminating layer, at which the processing of the layers stops, and the actual call to the user
       code is performed.  On success, it collects the return value(s) in the appropriate context.  Pushing
       the :raw layer on a trap will for most purposes remove all layers below.

   :die
       The layer emulating block eval, capturing normal exceptions.

   :exit
       The third "flow control" layer, capturing exit codes if anything used in the dynamic scope of the
       trap calls CORE::GLOBAL::exit().  (See CAVEATS below for more.)

   :flow
       A pseudo-layer shortcut for :raw:die:exit.  Since this includes :raw, pushing :flow on a trap will
       remove all layers below.

   :stdout, :stderr
       Layers trapping Perl output on STDOUT and STDERR, respectively.

   :stdout(perlio), :stderr(perlio)
       As above, but specifying a backend implemented using PerlIO::scalar.  If this backend is not
       available (typically if PerlIO is not), this is an error.

   :stdout(tempfile), :stderr(tempfile)
       As above, but specifying a backend implemented using File::Temp.  Note that this is the default
       implementation, unless the ":output()" layer is used to set another default.

   :stdout(a;b;c), :stderr(a,b,c)
       (Either syntax, commas or semicolons, is permitted, as is any number of names in the list.)  As
       above, but specifying the backend implementation by the first existing name among a, b, and c.  If no
       such implementation is available, this is an error.

   :warn
       A layer trapping warnings, with additional tee: If STDERR is open, it will also print the warnings
       there.  (This output may be trapped by the :stderr layer, be it above or below the :warn layer.)

   :default
       A pseudo-layer short-cut for :raw:die:exit:stdout:stderr:warn.  Since this includes :raw, pushing
       :default on a trap will remove all layers below.  The other interesting property of :default is that
       it is what every trap starts with:  In order not to include any of the six layers that make up
       :default, you need to push a terminating layer (such as :raw or :flow) on the trap.

   :on_fail(m)
       A (non-default) pseudo-layer that installs a callback method (by name) m to be run on test failures.
       To run the "diag_all" method every time a test fails:

         use Test::Trap qw/ :on_fail(diag_all) /;

   :void, :scalar, :list
       Runs the trapped user code in void, scalar, or list context, respectively.  (By default, the code is
       run in whatever context the trap itself is in.)

       If more than one of these layers are pushed on the trap, the deepest (that is, leftmost) takes
       precedence:

         use Test::Trap qw/ :scalar:void:list /;
         trap { 42, 13 };
         $trap->return_is_deeply( [ 13 ], 'Scalar comma.' );

   :output(a;b;c)
       A (non-default) pseudo-layers that sets the default backend layer implementation for any output
       trapping (":stdout", ":stderr", or other similarly defined) layers already on the trap.

         use Test::Trap qw/ :output(systemsafe) /;
         trap { system echo => 'Hello Unix!' }; # trapped!

RESULT ACCESSORS
       The following methods may be called on the trap objects after any trap has been sprung, and access
       the outcome of the run.

       Any property will be undef if not actually trapped -- whether because there is no layer to trap them
       or because flow control passed them by.  (If there is an active and successful trap layer, empty
       strings and empty arrays trapped will of course be defined.)

       When properties are set, their values will be as follows:

   leaveby
       A string indicating how the trap terminated: "return", "die", or "exit".

   die
       The exception, if the latest trap threw one.

   exit
       The exit code, if the latest trap tried to exit.

   return [INDEX ...]
       Returns undef if the latest trap did not terminate with a return; otherwise returns three different
       views of the return array:

          if no INDEX is passed, returns a reference to the array (NB! an empty array of indices qualifies
           as "no index")

          if called with at least one INDEX in scalar context, returns the array element indexed by the
           first INDEX (ignoring the rest)

          if called with at least one INDEX in list context, returns the slice of the array by these
           indices

       Note: The array will hold but a single value if the trap was sprung in scalar context, and will be
       empty if it was in void context.

   stdout, stderr
       The captured output on the respective file handles.

   warn [INDEX]
       Returns undef if the latest trap had no warning-trapping layer; otherwise returns three different
       views of the warn array:

          if no INDEX is passed, returns a reference to the array (NB! an empty array of indices qualifies
           as "no index")

          if called with at least one INDEX in scalar context, returns the array element indexed by the
           first INDEX (ignoring the rest)

          if called with at least one INDEX in list context, returns the slice of the array by these
           indices

   wantarray
       The context in which the latest code trapped was called.  (By default a propagated context, but
       layers can override this.)

   list, scalar, void
       True if the latest code trapped was called in the indicated context.  (By default the code will be
       called in a propagated context, but layers can override this.)

RESULT TESTS
       For each accessor, a number of convenient standard test methods are also available.  By default,
       these are a few standard tests from Test::More, plus the "nok" test (a negated "ok" test).  All for
       convenience:

   ACCESSOR_ok        [INDEX,] TEST_NAME
   ACCESSOR_nok       [INDEX,] TEST_NAME
   ACCESSOR_is        [INDEX,] SCALAR, TEST_NAME
   ACCESSOR_isnt      [INDEX,] SCALAR, TEST_NAME
   ACCESSOR_isa_ok    [INDEX,] SCALAR, INVOCANT_NAME
   ACCESSOR_like      [INDEX,] REGEX, TEST_NAME
   ACCESSOR_unlike    [INDEX,] REGEX, TEST_NAME
   ACCESSOR_is_deeply          STRUCTURE, TEST_NAME
       INDEX is not optional:  It is required for array accessors (like "return" and "warn"), and disallowed
       for scalar accessors.  Note that the "is_deeply" test does not accept an index.  Even for array
       accessors, it operates on the entire array.

       For convenience and clarity, tests against a flow control ACCESSOR ("return", "die", "exit", or any
       you define yourself) will first test whether the trap was left by way of the flow control mechanism
       in question, and fail with appropriate diagnostics otherwise.

   did_die, did_exit, did_return
       Conveniences: Tests whether the trap was left by way of the flow control mechanism in question.  Much
       like "leaveby_is('die')" etc, but with better diagnostics and (run-time) spell checking.

   quiet
       Convenience: Passes if zero-length output was trapped on both STDOUT and STDERR, and generate better
       diagnostics otherwise.

UTILITIES
   diag_all
       Prints a diagnostic message (as per "diag" in Test::More) consisting of a dump (in Perl code, as per
       Data::Dump) of the trap object.

   diag_all_once
       As "diag_all", except if this instance of the trap object has already been diag_all_once'd, the
       diagnostic message will instead consist of the string "(as above)".

       This could be useful with the "on_fail" layer:

         use Test::Trap qw/ :on_fail(diag_all_once) /;

CAVEATS
       This module must be loaded before any code containing exit()s to be trapped is compiled.  Any exit()
       already compiled won't be trappable, and will terminate the program anyway.

       This module overrides &CORE::GLOBAL::exit, so may not work correctly (or even at all) in the presence
       of other code overriding &CORE::GLOBAL::exit.  More precisely: This module installs its own exit() on
       entry of the block, and restores the previous one, if any, only upon leaving the block.

       If you use fork() in the dynamic scope of a trap, beware that the (default) :exit layer of that trap
       does not trap exit() in the children, but passes them to the outer handler.  If you think about it,
       this is what you are likely to want it to do in most cases.

       Note that the (default) :exit layer only traps &CORE::GLOBAL::exit calls (and bare exit() calls that
       compile to that).  It makes no attempt to trap CORE::exit(), POSIX::_exit(), exec(), nor segfault.
       Nor does it attempt to trap anything else that might terminate the program.  The trap is a block eval
       on steroids -- not the last block eval of Krypton!

       This module traps warnings using $SIG{__WARN__}, so may not work correctly (or even at all) in the
       presence of other code setting this handler.  More precisely: This module installs its own __WARN__
       handler on entry of the block, and restores the previous one, if any, only upon leaving the block.

       The (default) :stdout and :stderr handlers will not trap output from system() calls.

       Threads?  No idea.  It might even work correctly.

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

AUTHOR
       Eirik Berg Hanssen, "<ebhanssen@allverden.no>"

COPYRIGHT & LICENSE
       Copyright 2006-2012 Eirik Berg Hanssen, All Rights Reserved.

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



perl v5.16.2                                     2013-08-25                                    Test::Trap(3)

Сообщение о проблемах

Способ сообщить о проблеме с этой страницей руководства зависит от типа проблемы:

Ошибки содержания
Ошибки отчета в содержании этой документации к проекту Perl. (См. perlbug (1) для инструкций представления.)
Отчеты об ошибках
Сообщите об ошибках в функциональности описанного инструмента или API к Apple через Генератор отчетов Ошибки и к проекту Perl, использующему perlbug (1).
Форматирование проблем
Отчет, форматирующий ошибки в интерактивной версии этих страниц со ссылками на отзыв ниже.