Test2::...:Context(3)
okay bestie π welcome to the Test2::API::Context(3) page from User Contributed Perl Documentation β this is the one about the little context object that's lowkey the backbone of Test2 testing tools. let's get into it β¨
π NAME π
Test2::API::Context β Object to represent a testing context. periodt.
π DESCRIPTION π
okay so the context object is the primary interface for authors of testing tools written with Test2. it represents the context in which a test takes place β that's File and Line Number β and gives you a quick way to generate events from that context. it also takes care of sending events to the correct Test2::Hub instance. no cap, it's doing a lot of background work for you π«Ά
β¨ SYNOPSIS β¨
in general you will not be creating contexts directly. to obtain a context you should always use context(), which is exported by the Test2::API module. iykyk.
use Test2::API qw/context/;
sub my_ok {
my ($bool, $name) = @_;
my $ctx = context();
if ($bool) {
$ctx->pass($name);
}
else {
$ctx->fail($name);
}
$ctx->release; # You MUST do this!
return $bool;
}
context objects make it easy to wrap other tools that also use context. once you grab a context, any tool you call before releasing your context will inherit it β it's giving nested-tool magic β¨
sub wrapper {
my ($bool, $name) = @_;
my $ctx = context();
$ctx->diag("wrapping my_ok");
my $out = my_ok($bool, $name);
$ctx->release; # You MUST do this!
return $out;
}
π¨ CRITICAL DETAILS π¨
π you MUST always use the context() sub from Test2::API
creating your own context via Test2::API::Context->new() will almost never produce a desirable result. use context(), which is exported by Test2::API. fr fr.
there are a handful of cases where a tool author may want to create a new context by hand, which is why the new method exists. unless you really know what you are doing, you should avoid this. like, respectfully, don't π
π you MUST always release the context when done with it
releasing the context tells the system you are done with it. this gives it a chance to run any necessary callbacks or cleanup tasks. if you forget to release the context, it will try to detect the problem and warn you about it. so please bestie, release the context β it's the bare minimum π«Ά
π« you MUST NOT pass context objects around
when you obtain a context object, it is made specifically for your tool and any tools nested within. if you pass a context around, you run the risk of polluting other tools with incorrect context information. that's a vibe check fail π
if you are certain that you want a different tool to use the same context, you may pass it a snapshot. $ctx->snapshot will give you a shallow clone of the context that is safe to pass around or store. slay β¨
π you MUST NOT store or cache a context for later
as long as a context exists for a given hub, all tools that try to get a context will get the existing instance. if you try to store the context, you will pollute other tools with incorrect context information. nope nope nope.
if you are certain that you want to save the context for later, you can use a snapshot. $ctx->snapshot will give you a shallow clone of the context that is safe to pass around or store. iconic behavior only π
context() has some mechanisms to protect you if you do cause a context to persist beyond the scope in which it was obtained. in practice you should not rely on these protections, and they are fairly noisy with warnings. so likeβ¦ don't test your luck π
β° you SHOULD obtain your context as soon as possible in a given tool
you never know what tools you call from within your own tool will need a context. obtaining the context early ensures that nested tools can find the context you want them to find. get it early, bestie β future you will be obsessed πΈ
π METHODS π
okay so this is the part where the context actually does stuff instead of just sitting there being a whole vibe β¨ every one of these is a thing you call on your $ctx, so let's get into it.
$ctx->done_testing;β lowkey just tells everyone testing is done. If no plan has been set yet, this will generate a Plan event for you. no plan? no problem, she'll make one π$clone = $ctx->snapshot()β hands you a shallow clone of the context. the shallow clone is safe to store for later, so it's giving "keep this in your pocket, bestie" energy π$ctx->release()β releases the context. this runs cleanup tasks, and several important hooks. it will also restore$!,$?, and$@to whatever they were when the context was created. iconic behavior honestly.
β οΈ Note: if a context is acquired more than once, an internal refcount is kept.release()decrements the ref count, and none of the other actions ofrelease()will occur unless the refcount hits0. so the last call torelease()is the only one that resets$?,$!,$@, and runs the cleanup tasks. don't come for her, that's just how the refcount works π
$ctx->throw($message)β throws an exception that reports to the file and line number of the context. it also releases the context for you, so it's giving "I'll handle it, don't worry about it" energy π«Ά$ctx->alert($message)β issues a warning from the file and line number of the context.$stack = $ctx->stack()β returns theTest2::API::Stackinstance that the context used to find the current hub. iykyk π₯$hub = $ctx->hub()β returns theTest2::Hubinstance that the context recognizes as the current one, aka the one where all events should be sent. main character hub energy π$dbg = $ctx->trace()β returns theTest2::EventFacet::Traceinstance that the context is using.$ctx->do_in_context(\&code, @args);β okay so sometimes you have a context that is not current, and you want things to use it as the current one anyway. in those cases you can call$ctx->do_in_context(sub { ... }). the codeblock will be run, and anything inside of it that looks for a context will find the one on which the method was called. slay πΈ
this DOES NOT affect context on other hubs β only the hub used by the context will be affected.
my $ctx = ...;
$ctx->do_in_context(sub {
my $ctx = context(); # returns the $ctx the sub is called on
});
π¦ Note: the context will actually be cloned, and the clone will be used instead of the original. that way the thread id, process id, and error variables stay correct without modifying the original context. considerate queen behavior fr.
$ctx->restore_error_vars()β sets$!,$?, and$@to what they were when the context was created. there is no localization or anything done here β calling this method will actually set these vars. so like, actually actually π$! = $ctx->errno()β the (numeric) value of$!when the context was created.$? = $ctx->child_error()β the value of$?when the context was created.$@ = $ctx->eval_error()β the value of$@when the context was created. that's it, that's the whole method π
π₯ EVENT PRODUCTION METHODS π₯
β¨ Which one do I use?
okay so the big question. here's the tea β
the pass* and fail* methods are optimal if they meet your situation β using one of them will always be the most optimal. that said, they are optimal by eliminating many features, so like, you're trading features for speed, bestie.
methods such as ok, and note are shortcuts for generating common 1-task events based on the old API. however, they are forward compatible, and easy to use. if these meet your needs then go ahead and use them, but please check back often for alternatives that may be added β¨
if you want to generate new style events β events that do many things at once β then you want the *ev2* methods. these let you directly specify which facets you wish to use. very build-your-own-adventure, we love to see it π
$event = $ctx->pass()$event = $ctx->pass($name)
this will send and return a Test2::Event::Pass event. you may optionally provide a $name for the assertion.
the Test2::Event::Pass is a specially crafted and optimized event, so using this will help the performance of passing tests. she's optimized, she's fast, she ate π
$true = $ctx->pass_and_release()$true = $ctx->pass_and_release($name)
this is a combination of pass() and release(). you can use this if you do not plan to do anything with the context after sending the event. it helps write more clear and compact code. cute and efficient? we stan π«Ά
sub shorthand {
my ($bool, $name) = @_;
my $ctx = context();
return $ctx->pass_and_release($name) if $bool;
... Handle a failure ...
}
sub longform {
my ($bool, $name) = @_;
my $ctx = context();
if ($bool) {
$ctx->pass($name);
$ctx->release;
return 1;
}
... Handle a failure ...
}
my $event = $ctx->fail()my $event = $ctx->fail($name)my $event = $ctx->fail($name, @diagnostics)
this lets you send a Test2::Event::Fail event. you may optionally provide a $name and @diagnostics messages.
diagnostics messages can be simple strings, data structures, or instances of Test2::EventFacet::Info::Table (which are converted inline into the Test2::EventFacet::Info structure). very flexible, we love options π
my $false = $ctx->fail_and_release()my $false = $ctx->fail_and_release($name)my $false = $ctx->fail_and_release($name, @diagnostics)
this is a combination of fail() and release(). it can be used to write clearer and shorter code. the way that it just combines them π
sub shorthand {
my ($bool, $name) = @_;
my $ctx = context();
return $ctx->fail_and_release($name) unless $bool;
... Handle a success ...
}
sub longform {
my ($bool, $name) = @_;
my $ctx = context();
unless ($bool) {
$ctx->pass($name);
$ctx->release;
return 1;
}
... Handle a success ...
}
$event = $ctx->ok($bool, $name)$event = $ctx->ok($bool, $name, \@on_fail)
π NOTE: use of this method is discouraged in favor ofpass()andfail()which produceTest2::Event::PassandTest2::Event::Failevents. these newer event types are faster and less crufty. respectfully, she's a little old-school.
this will create a Test2::Event::Ok object for you. if $bool is false then a Test2::Event::Diag event will be sent as well, with details about the failure. if you do not want automatic diagnostics you should use the send_event() method directly.
the third argument ("\@on_fail") is an optional set of diagnostics to be sent in the event of a test failure. unlike with fail() these diagnostics must be plain strings β data structures are not supported. no fancy structures here, bestie π
$event = $ctx->note($message)β sends aTest2::Event::Note. this event prints a message toSTDOUT. she's a yapper and we respect it β¨$event = $ctx->diag($message)β sends aTest2::Event::Diag. this event prints a message toSTDERR. different stream, different vibe π¦$event = $ctx->plan($max)$event = $ctx->plan(0, 'SKIP', $reason)
this can be used to send a Test2::Event::Plan event. this event usually takes either a number of tests you expect to run. optionally you can set the expected count to 0 and give the 'SKIP' directive with a reason to cause all tests to be skipped. skipping everything on purpose? periodt π
$event = $ctx->skip($name, $reason);β sends aTest2::Event::Skipevent.$event = $ctx->bail($reason)β sends aTest2::Event::Bailevent. this event will completely terminate all testing. like, that's it, we're done, pack it up π$event = $ctx->send_ev2(%facets)β this lets you build and send a V2 event directly from facets. the event is returned after it is sent.
this example sends a single assertion, a note (comment for stdout in Test::Builder talk) and sets the plan to 1. look at her go π₯
my $event = $ctx->send_event(
plan => {count => 1},
assert => {pass => 1, details => "A passing assert"},
info => [{tag => 'NOTE', details => "This is a note"}],
);
$event = $ctx->build_e2(%facets)β this is the same assend_ev2(), except it builds and returns the event without sending it. build her but don't send her, got it π$event = $ctx->send_ev2_and_release($Type, %parameters)β this is a combination ofsend_ev2()andrelease().
sub shorthand {
my $ctx = context();
return $ctx->send_ev2_and_release(assert => {pass => 1, details => 'foo'});
}
sub longform {
my $ctx = context();
my $event = $ctx->send_ev2(assert => {pass => 1, details => 'foo'});
$ctx->release;
return $event;
}
$event = $ctx->send_event($Type, %parameters)β it is better to usesend_ev2()in new code. just putting that out there π
this lets you build and send an event of any type. the $Type argument should be the event package name with Test2::Event:: left off, or a fully qualified package name prefixed with a +. the event is returned after it is sent.
my $event = $ctx->send_event('Ok', ...);
or
my $event = $ctx->send_event('+Test2::Event::Ok', ...);
$event = $ctx->build_event($Type, %parameters)β it is better to usebuild_ev2()in new code. this is the same assend_event(), except it builds and returns the event without sending it πΈ$event = $ctx->send_event_and_release($Type, %parameters)β it is better to usesend_ev2_and_release()in new code. this is a combination ofsend_event()andrelease().
sub shorthand {
my $ctx = context();
return $ctx->send_event_and_release(Pass => { name => 'foo' });
}
sub longform {
my $ctx = context();
my $event = $ctx->send_event(Pass => { name => 'foo' });
$ctx->release;
return $event;
}
π₯ HOOKS π₯
okay bestie so there are literally 2 types of hooks, and you're gonna remember them forever: init hooks and release hooks. the names are giving exactly what they are β these hooks get triggered when contexts are created or released. periodt. π
β¨ INIT HOOKS β¨
these ones get called whenever a context is initialized. meaning: when a new instance is created. and listen β these hooks are NOT called every time something requests a context, only when a genuinely new one gets made. no cap. π«Ά
πΈ GLOBAL
this is how you add a global init callback. global callbacks happen for every context, for any hub or stack. iconic behaviour honestly:
Test2::API::test2_add_callback_context_init(sub {
my $ctx = shift;
...
});
π¦ PER HUB
this is how you add an init callback for all contexts created for a given hub. these callbacks will not run for other hubs β they stay in their own lane, as they should:
$hub->add_context_init(sub {
my $ctx = shift;
...
});
π PER CONTEXT
this is how you specify an init hook that only runs if your call to context() generates a new context. the callback gets ignored if context() is returning an existing context β like, sorry babe, no new context, no hook:
my $ctx = context(on_init => sub {
my $ctx = shift;
...
});
π RELEASE HOOKS π
these get called whenever a context is released. that means when the last reference to the instance is about to be destroyed. and again, bestie, read carefully: these hooks are NOT called every time $ctx->release is called. π the way this trips people up...
π GLOBAL
this is how you add a global release callback. global callbacks happen for every context for any hub or stack:
Test2::API::test2_add_callback_context_release(sub {
my $ctx = shift;
...
});
β PER HUB
this is how you add a release callback for all contexts created for a given hub. these callbacks won't run for other hubs β boundaries, we love to see it:
$hub->add_context_release(sub {
my $ctx = shift;
...
});
π PER CONTEXT
this is how you add release callbacks directly to a context. and here's the tea: the callback will ALWAYS be added to the context that gets returned. doesn't matter if a new one is generated, or if an existing one is returned. always. π
my $ctx = context(on_release => sub {
my $ctx = shift;
...
});
π§ THIRD PARTY META-DATA π§
this object consumes Test2::Util::ExternalMeta, which hands you a consistent way to attach meta-data to instances of this class. genuinely so useful for tools, plugins, and other extensions β like, the ecosystem ate with this one. π₯
π SOURCE π
the source code repository for Test2 can be found at https://github.com/Test-More/test-more/ β go be nosy, it's encouraged. π
π MAINTAINERS π
- Chad Granum
<exodist@cpan.org>
πΈ AUTHORS πΈ
- Chad Granum
<exodist@cpan.org> - Kent Fredric
<kentnl@cpan.org>
π¦ 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 https://dev.perl.org/licenses/
aaaand that's the whole page, bestie!! π you made it to the end, i'm so proud of you fr fr π«Ά this wasperl v5.42.0, dated2025-07-28, and it'sTest2::...:Context(3)β now go forth and slay your contexts, mwah πβ¨
π¦ where this page comes from
- opensuse-leap 16.0: perl-Test-Simple 1.302214-bp160.1.2 Β· Artistic-1.0 OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms