TEST2::API::CONTEXT(3perl)
π Test2::API::Context β the manual page, but make it cute π
okay bestie, welcome to Test2::API::Context(3perl) from the Perl Programmers Reference Guide β¨ this is the page about the context object, which is likeβ¦ the main character of writing test tools with Test2 fr fr π
πΈ NAME πΈ
Test2::API::Context β the object that represents a testing context π (yes that's its whole job, it's giving very focused queen π)
π¦ DESCRIPTION π¦
So. The context object is the primary interface for authors of testing tools written with Test2 π if you're building test tooling, this is your bestie, your ride-or-die, the one you text at 2am.
What does it represent? The context in which a test takes place β that's the File</> and the Line Number β and it also gives you a quick way to generate events straight from that context β¨ and on top of all that, it handles sending those events to the correct Test2::Hub instance. iconic multitasking, no notes π
β¨ SYNOPSIS β¨
okay so, first things first, the vibe check:
In general you will not be creating contexts directly. To obtain a context you should always usecontext()which is exported by theTest2::APImodule. periodt π
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;
}
see that $ctx->release;? with the comment? that is not optional bestie, do not skip her π
Context objects also 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:
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;
}
it's giving inheritance, it's giving nesting, it's giving "the vibes propagate downward" π
π CRITICAL DETAILS π
this section is the rules section. read it. actually read it. i'm not being dramatic (i am being a little dramatic but it's warranted).
π 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 π don't do it. Use context() which is exported by Test2::API. that's the move.
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. iykyk π«£
π 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 like, it's not gonna silently hate you, but it WILL be loud about it πΈ
π 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 it π If you pass a context around you run the risk of polluting other tools with incorrect context information. not slay. extremely not slay.
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 π
π 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 π«
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 β¨
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 π
π 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. front-load the context. it's the responsible thing π«Ά
okay that's part 1, and there's still more coming so don't go anywhere π¦
π METHODS π
okay bestie, here's the whole toolbox. every single one of these is called on $ctx (your context object), and every single one is here, no skips, no cuts. let's go π«Ά
β¨ $ctx->done_testing;
the "we're done here" button. note that testing is finished β and if no plan has been set yet, this will generate a Plan event for you. slay.
β¨ $clone = $ctx->snapshot()
hands you back a shallow clone of the context. and here's the tea: a shallow clone is safe to store for later. π
β¨ $ctx->release()
releases the context. this runs cleanup tasks, plus several important hooks. it will also restore $!, $?, and $@ to whatever they were when the context was created. iconic restorative behaviour fr fr.
β οΈ 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. this means only the last call torelease()will reset$?,$!,$@, and run the cleanup tasks. so likeβ¦ don't expect the cleanup to pop off early, bestie.
β¨ $ctx->throw($message)
throws an exception, reporting to the file and line number of the context. and it also releases the context for you, which is very generous of it. π
β¨ $ctx->alert($message)
issues a warning from the file and line number of the context. lowkey the calmer sibling of throw().
β¨ $stack = $ctx->stack()
returns the Test2::API::Stack instance that the context used to find the current hub. π¦
β¨ $hub = $ctx->hub()
returns the Test2::Hub instance that the context recognizes as the current one β i.e. the one all events should be sent to.
β¨ $dbg = $ctx->trace()
returns the Test2::EventFacet::Trace instance used by the context. yes bestie, trace, as in the receipts of where you are. π΅οΈββοΈ
β¨ $ctx->do_in_context(\&code, @args);
sometimes you have a context that is not current, and you want things to use it as the current one anyway. in these 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. main character energy, honestly.
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. this allows the thread id, process id, and error variables to be correct without modifying the original context. it's giving responsible.
β¨ $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. no buffer, just vibes and consequences. π
β¨ $! = $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.
π EVENT PRODUCTION METHODS π
Which one do I use? π
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, y'know, tradeoffs, 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. periodt. π
π $event = $ctx->pass() | $event = $ctx->pass($name)
this will send and return an Test2::Event::Pass event. you may optionally provide a $name for the assertion.
the Test2::Event::Pass is a specially crafted and optimized event β using this will help the performance of passing tests. we love a fast queen. π₯
π $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. β¨
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 an 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). flexible fr fr.
π 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(). this can be used to write clearer and shorter code. π«Ά
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. it's giving legacy, bestie.
this will create an Test2::Event::Ok object for you. if $bool is false then an 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 stuff here, sorry. π
π $event = $ctx->note($message)
send an Test2::Event::Note. this event prints a message to STDOUT. π
π $event = $ctx->diag($message)
send an Test2::Event::Diag. this event prints a message to STDERR. π©Ί
π $event = $ctx->plan($max) | $event = $ctx->plan(0, 'SKIP', $reason)
this can be used to send an 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. group project cancelled, but make it official. π
π $event = $ctx->skip($name, $reason);
send an Test2::Event::Skip event. π¦
π $event = $ctx->bail($reason)
this sends an Test2::Event::Bail event. this event will completely terminate all testing. everything. gone. the whole vibe check has failed. π
π $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.
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 as send_ev2(), except it builds and returns the event without sending it. π
π $event = $ctx->send_ev2_and_release($Type, %parameters)
this is a combination of send_ev2() and release().
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 use send_ev2() in new code. π
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 use build_ev2() in new code. β¨
this is the same as send_event(), except it builds and returns the event without sending it.
π $event = $ctx->send_event_and_release($Type, %parameters)
it is better to use send_ev2_and_release() in new code. π
this is a combination of send_event() and release().
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 so there are 2 types of hooks, bestie: init hooks and release hooks. and like, the names are literally telling you everything β these hooks get triggered when contexts are created or released. periodt. π
π± INIT HOOKS π±
these get called whenever a context is initialized. which meansβ¦ whenever a new instance is created. important: these hooks are NOT called every time something requests a context β only when a genuinely new one gets created. iykyk π¦
π GLOBAL
here's how you add a global init callback. global callbacks happen for every context, for any hub or stack. no exceptions, no favourites π
Test2::API::test2_add_callback_context_init(sub {
my $ctx = shift;
...
});
π PER HUB
and here's how you add an init callback for all contexts created for one specific hub. these callbacks will not run for other hubs. it's giving exclusive π
$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 just gets ignored if context() is returning an existing context. no hard feelings π
my $ctx = context(on_init => sub {
my $ctx = shift;
...
});
π RELEASE HOOKS π
these get called whenever a context is released. which means β when the last reference to the instance is about to be destroyed. heads up: these hooks are NOT called every time $ctx->release is called. okay? okay. π
π GLOBAL
here's 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 will not run for other hubs π«Ά
$hub->add_context_release(sub {
my $ctx = shift;
...
});
π― PER CONTEXT
and this is how you add release callbacks directly to a context. the callback will ALWAYS be added to the context that gets returned β it does not matter if a new one is generated, or if an existing one is returned. always. no cap π₯
my $ctx = context(on_release => sub {
my $ctx = shift;
...
});
ποΈ THIRD PARTY META-DATA ποΈ
so this object consumes Test2::Util::ExternalMeta, which is the thing that gives you a consistent, no-drama way to attach meta-data to instances of this class. genuinely so useful for tools, plugins, and other extensions. obsessed π
β¨
π¦ SOURCE π¦
the source code repository for Test2 lives at <https://github.com/Test-More/test-more/>. go look, it slays π¦
π 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/>
and that's a wrap bestie πβ¨ this whole page is from perl v5.44.0, dated 2026-10-17, and it's the Test2::...Context(3perl) page β go forth and hook all the things, you absolute icon π
π«Ά
π¦ where this page comes from
- arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms