Test2::Manual::Tooling::FirstTool(3) | User Contributed Perl Documentation | Test2::Manual::Tooling::FirstTool(3) |
Test2::Manual::Tooling::FirstTool - Write your first tool with Test2.
This tutorial will help you write your very first tool by cloning the "ok()" tool.
package Test2::Tools::MyOk; use strict; use warnings; use Test2::API qw/context/; use base 'Exporter'; our @EXPORT = qw/ok/; sub ok($;$@) { my ($bool, $name, @diag) = @_; my $ctx = context(); return $ctx->pass_and_release($name) if $bool; return $ctx->fail_and_release($name, @diag); } 1;
"ok()" and similar test tools use prototypes to enforce argument parsing. Your test tools do not necessarily need prototypes, like any perl function you need to make the decision based on how it is used.
The prototype requires at least 1 argument, which will be forced into a scalar context. The second argument is optional, and is also forced to be scalar, it is the name of the test. Any remaining arguments are treated as diagnostics messages that will only be used if the test failed.
Note: A test function MUST always release the context when it is done, you cannot simply let it fall out of scope and be garbage collected. Test2 does a pretty good job of yelling at you if you make this mistake.
Note: You MUST NOT ever store or pass around a real context object. If you wish to hold on to a context for any reason you must use clone to make a copy "my $copy = $ctx->clone". The copy may be passed around or stored, but the original MUST be released when you are done with it.
This is short form for:
if($bool) { $ctx->pass($name); $ctx->release; return 1; }
This is short form for:
$ctx->fail($name, @diag); $ctx->release; return 0;
Test2::API::Context is the place to read up on what methods the context provides.
Test2::Manual - Primary index of the manual.
The source code repository for Test2-Manual can be found at https://github.com/Test-More/Test2-Suite/.
Copyright 2018 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/
2020-10-22 | perl v5.34.0 |