NAME
Test2::Manual::Tooling::Plugin::TestExit - How to safely add pre-exit behaviors.
DESCRIPTION
This describes the correct/safe way to add pre-exit behaviors to tests via a custom plugin.
The naive way to attempt this would be to add an END { ... }
block. That can work, and may not cause problems.... On the other hand there are a lot of ways that can bite you. Describing all the potential problems of an END block, and how it might conflict with Test2 (Which has its own END block) is beyond the scope of this document.
COMPLETE CODE UP FRONT
package Test2::Plugin::MyPlugin;
use Test2::API qw{test2_add_callback_exit};
sub import {
my $class = shift;
test2_add_callback_exit(sub {
my ($ctx, $orig_code, $new_exit_code_ref) = @_;
return if $orig_code == 42;
$$new_exit_code_ref = 42;
});
}
1;
LINE BY LINE
- use Test2::API qw{test2_add_callback_exit};
-
This imports the
(test2_add_callback_exit)
callback. - test2_add_callback_exit(sub { ... });
-
This adds our callback to be called before exiting.
- my ($ctx, $orig_code, $new_exit_code_ref) = @_
-
The callback gets 3 arguments. First is a context object you may use. The second is the original exit code of the
END
block Test2 is using. The third argument is a scalar reference which you may use to get the current exit code, or set a new one. - return if $orig_code == 42
-
This is a short-cut to do nothing if the original exit code was already 42.
- $$new_exit_code_ref = 42
-
This changes the exit code to 42.
SEE ALSO
Test2::Manual - Primary index of the manual.
SOURCE
The source code repository for Test2-Manual can be found at https://github.com/Test-More/test-more/.
MAINTAINERS
AUTHORS
COPYRIGHT
Copyright Chad Granum <exodist@cpan.org>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See http://dev.perl.org/licenses/