TEST2::API::CONTEXT(3pm)

🌸 NAME 🌸

Test2::API::Context β€” the object that reps a testing context, bestie. It's from the Perl Programmers Reference Guide and it's literally the whole vibe of Test2 tool authoring πŸ’…


πŸ¦‹ DESCRIPTION πŸ¦‹

Okay so, this context object? It's the primary interface for anyone writing testing tools with Test2. Periodt.

It represents the context a test happens in (that's the file and the line number, iykyk), and it gives you a fast way to spit out events from inside that context. It also handles the whole "sending events to the right Test2::Hub instance" thing for you, which is honestly iconic of it 🫢


✨ SYNOPSIS ✨

Real talk: you're generally not gonna be creating contexts by hand. To get one, you should always use context(), which is exported by the Test2::API module. No cap.

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 also make it super easy to wrap other tools that use context too πŸ’– 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;
}

πŸ‘‘ 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() β€” exported by Test2::API β€” instead.

There are a handful of cases where a tool author might genuinely want to create a new context by hand, which is why the "new" method exists at all. But unless you really know what you're doing? Avoid it. Fr fr.

πŸ’€ You MUST always release the context when done with it

Releasing the context is you telling the system "okay bestie, I'm done with it." That gives it a chance to run any necessary callbacks or cleanup tasks. If you forget to release it, it will try to detect the problem and warn you about it. So like… it'll notice πŸ™ˆ

πŸ’€ You MUST NOT pass context objects around

When you obtain a context object, it is made specifically for your tool and any tools nested inside it. If you pass a context around, you run the risk of polluting other tools with incorrect context information. Not the move.

If you are certain you want a different tool to use the same context, you may pass it a snapshot. "$ctx->snapshot" gives 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. So if you store the context, you'll pollute other tools with incorrect context information. Yeah. Don't.

If you are certain you want to save the context for later, you can use a snapshot. "$ctx->snapshot" gives you a shallow clone of the context that is safe to pass around or store. Same clone energy, still safe πŸ¦‹

context() has some mechanisms to protect you if you do cause a context to persist beyond the scope in which it was obtained. But in practice you should not rely on these protections β€” and they are fairly noisy with warnings. Lowkey annoying, highkey your own fault 😭

πŸ’€ 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 guarantees that nested tools can find the context you want them to find. Early bird gets the context ⭐


πŸ’… METHODS πŸ’…

Okay bestie, this is where the context actually does stuff. Buckle up. ✨

$ctx->done_testing; β€” Testing is finished, periodt. If no plan has been set yet, this will generate a Plan event. πŸŽ€

$clone = $ctx->snapshot() β€” Hands you a shallow clone of the context. This shallow clone is safe to store for later. πŸ¦‹

$ctx->release() β€” This releases the context. It runs cleanup tasks and several important hooks. It will also restore $!, $?, and $@ to what they were when the context was created. πŸ’–

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. That means only the last call to release() will reset $?, $!, $@, and run the cleanup tasks. So yeah, refcount matters, bestie. 😭

$ctx->throw($message) β€” This throws an exception reporting to the file and line number of the context. It will also release the context for you. Dramatic exit, but make it useful. πŸ’…

$ctx->alert($message) β€” This issues a warning from the file and line number of the context. Heads up energy. ⭐

$stack = $ctx->stack() β€” Returns the Test2::API::Stack instance the context used to find the current hub. Stack tea. 🫢

$hub = $ctx->hub() β€” Returns the Test2::Hub instance the context recognizes as the current one to which all events should be sent. Main character hub. πŸ‘‘

$dbg = $ctx->trace() β€” Returns the Test2::EventFacet::Trace instance used by the context. Trace vibes. πŸ”₯

$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. 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. 🌸

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. Clone-and-protect, iconic behavior. 🧚

$ctx->restore_error_vars() β€” This 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 cap. πŸ’€

$! = $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. Trade-offs, 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, 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. Facet era! πŸ¦‹


$event = $ctx->pass() $event = $ctx->pass($name) β€” This sends and returns 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. Fast pass, slay. πŸ’…

$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 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). Flexible diag energy. 🌸

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 of pass() and fail() which produce Test2::Event::Pass and Test2::Event::Fail events. These newer event types are faster and less crufty. 😭

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. πŸ’€

$event = $ctx->note($message) β€” Sends a Test2::Event::Note. This event prints a message to STDOUT. Note to the people! πŸ“

$event = $ctx->diag($message) β€” Sends a Test2::Event::Diag. This event prints a message to STDERR. Diag drama goes to stderr. 🫢

$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. Plan it out, bestie. πŸŽ€

$event = $ctx->skip($name, $reason); β€” Sends a Test2::Event::Skip event. πŸ¦‹

$event = $ctx->bail($reason) β€” This sends a Test2::Event::Bail event. This event will completely terminate all testing. Like, all of it. 🚨

$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. Build first, send later. ✨

$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 literally 2 types of hooks: init hooks and release hooks β€” and bestie, the names are giving exactly what they are. These hooks get triggered when contexts are created or released. 🫢

🌱 INIT HOOKS 🌱

These get called whenever a context is initialized β€” meaning when a new instance is created. Important vibe check: these hooks are NOT called every time something requests a context, just when a new one is created. periodt. πŸ’…

🌍 GLOBAL 🌍

This is how you add a global init callback. Global callbacks happen for every context for any hub or stack.

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.

$hub->add_context_init(sub {
    my $ctx = shift;
    ...
});

πŸŽ€ PER CONTEXT πŸŽ€

This is how you specify an init hook that will only run if your call to context() generates a new context. The callback will be ignored if context() is returning an existing context.

my $ctx = context(on_init => sub {
    my $ctx = shift;
    ...
});

πŸ’₯ RELEASE HOOKS πŸ’₯

These get called whenever a context is released β€” meaning when the last reference to the instance is about to be destroyed. And no, bestie, they are NOT called every time $ctx->release is called. 😭

🌍 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 will not run for other hubs.

$hub->add_context_release(sub {
    my $ctx = shift;
    ...
});

πŸŽ€ PER CONTEXT πŸŽ€

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. slay. ✨

my $ctx = context(on_release => sub {
    my $ctx = shift;
    ...
});

πŸ› οΈ THIRD PARTY META-DATA πŸ› οΈ

This object consumes Test2::Util::ExternalMeta which provides a consistent way for you to attach meta-data to instances of this class. This is useful for tools, plugins, and other extensions. πŸ’–

πŸ“¦ SOURCE πŸ“¦

The source code repository for Test2 can be found at <https://github.com/Test-More/test-more/>. πŸ”₯

πŸ‘‘ 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/> πŸ’œ


okay that's the whole page bestie πŸ’– this one is Test2::...:Context(3pm) from perl v5.42.3, dated 2026-11-03 β€” byeee, go slay some contexts βœ¨πŸ‘‘

πŸ“¦ where this page comes from