Test2::...:Context(3)

πŸ“¦ version 1.302214, in opensuse-leap 16.0

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 of release() will occur unless the refcount hits 0. so the last call to release() 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 the Test2::API::Stack instance that the context used to find the current hub. iykyk πŸ”₯
  • $hub = $ctx->hub() β€” returns the Test2::Hub instance 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 the Test2::EventFacet::Trace instance 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 of pass() and fail() which produce Test2::Event::Pass and Test2::Event::Fail events. 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 a Test2::Event::Note. this event prints a message to STDOUT. she's a yapper and we respect it ✨
  • $event = $ctx->diag($message) β€” sends a Test2::Event::Diag. this event prints a message to STDERR. 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 a Test2::Event::Skip event.
  • $event = $ctx->bail($reason) β€” sends a Test2::Event::Bail event. 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 as send_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 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. 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 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 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 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 was perl v5.42.0, dated 2025-07-28, and it's Test2::...:Context(3) β€” now go forth and slay your contexts, mwah πŸŽ€βœ¨
πŸ“¦ where this page comes from