Test::S...:Context(3)

πŸ“¦
version 1.302027 Β· 2 versions
, in fedora 43

okay bestie, welcome to Test::Stream::Context(3) from the User Contributed Perl Documentation set β€” and no cap, this page is the blueprint for context objects in Test::Stream. πŸ’–

✨ NAME ✨

Test::Stream::Context β€” the object that represents a testing context. That's it. That's the whole name vibe. πŸŽ€

🚫 DEPRECATED 🚫

This distribution is deprecated in favor of Test2, Test2::Suite, and Test2::Workflow.

See Test::Stream::Manual::ToTest2 for a conversion guide. Not me being dramatic, it's literally in the docs. πŸ’€

🌈 DESCRIPTION 🌈

The context object is the primary interface for authors of testing tools written with Test::Stream. It represents the context in which a test takes place β€” that's File and Line Number, bestie β€” and it gives you a quick way to generate events from that context. It also handles sending events to the correct Test::Stream::Hub instance. Slay. ✨

πŸ¦‹ SYNOPSIS πŸ¦‹

use Test::Stream::Context qw/context release/;

sub my_ok {
    my ($bool, $name) = @_;
    my $ctx = context();
    $ctx->ok($bool, $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:

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;
}

Notice above that we are grabbing a return value, then releasing our context, then returning the value. We can combine these last 3 statements into a single statement using the release function:

sub wrapper {
    my ($bool, $name) = @_;
    my $ctx = context();
    $ctx->diag("wrapping my_ok");

    # You must always release the context.
    release $ctx, my_ok($bool, $name);
}

🚨 CRITICAL DETAILS 🚨

These are the rules, bestie. Read them. Live them. Periodt. πŸ’…

πŸ’… 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 be released for you using a destructor, and it will give you a warning.

In general the destructor is not preferred because it does not allow callbacks to run some types of code, for example you cannot throw an exception from a destructor. So like, don't rely on 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. If you pass a context around you run the risk of polluting other tools with incorrect context information.

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. Main character energy: get that context first. ✨

πŸ“¦ EXPORTS πŸ“¦

All exports are optional, you must specify subs to import. If you want to import all subs use '-all'.

use Test::Stream::Context '-all';

πŸŽ€ context()

Usage:

$ctx = context()
$ctx = context(%params)

The context() function will always return the current context to you. If there is already a context active it will be returned. If there is not an active context one will be generated. When a context is generated it will default to using the file and line number where the currently running sub was called from.

Please see the "CRITICAL DETAILS" section for important rules about what you can and cannot do with a context once it is obtained.

Note This function will throw an exception if you ignore the context object it returns. So like, don't ignore it. 😭

✨ OPTIONAL PARAMETERS ✨

All parameters to context are optional.

  • level => $int β€” If you must obtain a context in a sub deeper than your entry point you can use this to tell it how many EXTRA stack frames to look back. If this option is not provided the default of 0 is used.
sub third_party_tool {
    my $sub = shift;
    ... # Does not obtain a context
    $sub->();
    ...
}

third_party_tool(sub {
    my $ctx = context(level => 1);
    ...
    $ctx->release;
});
  • wrapped => $int β€” Use this if you need to write your own tool that wraps a call to context() with the intent that it should return a context object.
sub my_context {
    my %params = ( wrapped => 0, @_ );
    $params{wrapped}++;
    my $ctx = context(%params);
    ...
    return $ctx;
}

sub my_tool {
    my $ctx = my_context();
    ...
    $ctx->release;
}

If you do not do this, then tools you call that also check for a context will notice that the context they grabbed was created at the same stack depth, which will trigger protective measures that warn you and destroy the existing context. 🚩

  • stack => $stack β€” Normally context() looks at the global hub stack initialized in Test::Stream::Sync. If you are maintaining your own Test::Stream::Stack instance you may pass it in to be used instead of the global one.
  • hub => $hub β€” Use this parameter if you want to obtain the context for a specific hub instead of whatever one happens to be at the top of the stack.
  • on_init => sub { ... } β€” This lets you provide a callback sub that will be called ONLY if your call to context() generated a new context. The callback WILL NOT be called if context() is returning an existing context. The only argument passed into the callback will be the context object itself.
sub foo {
    my $ctx = context(on_init => sub { 'will run' });

    my $inner = sub {
        # This callback is not run since we are getting the existing
        # context from our parent sub.
        my $ctx = context(on_init => sub { 'will NOT run' });
        $ctx->release;
    }
    $inner->();

    $ctx->release;
}
  • on_release => sub { ... } β€” This lets you provide a callback sub that will be called when the context instance is released. This callback will be added to the returned context even if an existing context is returned. If multiple calls to context add callbacks then all will be called in reverse order when the context is finally released.
sub foo {
    my $ctx = context(on_release => sub { 'will run second' });

    my $inner = sub {
        my $ctx = context(on_release => sub { 'will run first' });

        # Neither callback runs on this release
        $ctx->release;
    }
    $inner->();

    # Both callbacks run here.
    $ctx->release;
}

🎁 release()

Usage:

release $ctx;
release $ctx, ...;

This is intended as a shortcut that lets you release your context and return a value in one statement. This function will get your context, and any other arguments provided. It will release your context, then return everything else. If you only provide one argument it will return that one argument as a scalar. If you provide multiple arguments it will return them all as a list.

sub scalar_tool {
    my $ctx = context();
    ...

    return release $ctx, 1;
}

sub list_tool {
    my $ctx = context();
    ...

    return release $ctx, qw/a b c/;
}

This tool is most useful when you want to return the value you get from calling a function that needs to see the current context:

my $ctx = context();
my $out = some_tool(...);
$ctx->release;
return $out;

We can combine the last 3 lines of the above like so:

my $ctx = context();
release $ctx, some_tool(...);

✨ METHODS ✨

πŸŽ€ CLASS METHODS πŸŽ€

  • Test::Stream::Context->ON_INIT(sub { ... }, ...) β€” bestie, these are GLOBAL hooks into the context tools! Every sub you add via ON_INIT gets called every single time a new context is initialized. πŸ’–
  • Test::Stream::Context->ON_RELEASE(sub { ... }, ...) β€” same vibe but for release! Every sub added via ON_RELEASE gets called every single time a context is released. πŸŽ€
Heads up: your subs will receive exactly 1 argument, and that's the context itself. Also, do NOT call release on the context inside your callback, okay? πŸ™…β€β™€οΈ

πŸ’… INSTANCE METHODS πŸ’…

  • $clone = $ctx->snapshot() β€” returns a shallow clone of the context. It's safe to store for later, no cap. 🧚
  • $ctx->release() β€” releases the context. It also sets the $ctx variable to undef (and yes, it works no matter what you named your variable, periodt). πŸ’€
  • $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 you don't gotta do it yourself. 😭
  • $ctx->alert($message) β€” issues a warning from the file and line number of the context. πŸ””
  • $stack = $ctx->stack() β€” returns the Test::Stream::Stack instance that the context used to find the current hub. πŸ₯ž
  • $hub = $ctx->hub() β€” returns the Test::Stream::Hub instance that the context recognises as the current one β€” the one all events should be sent to. πŸ›°οΈ
  • $dbg = $ctx->debug() β€” returns the Test::Stream::DebugInfo instance used by the context. 🐞
  • $ctx->do_in_context(\&code, @args); β€” sometimes you have a context that isn't current, but you want stuff to use it as the current one. That's when you call $ctx->do_in_context(sub { ... }). The codeblock runs, and anything inside that looks for a context will find the one you called the method on. ✨
This does NOT affect context on other hubs β€” only the hub used by the context gets affected. πŸ’…
my $ctx = ...;
$ctx->do_in_context(sub {
    my $ctx = context(); # returns the $ctx the sub is called on
});

πŸ”₯ EVENT PRODUCTION METHODS πŸ”₯

  • $event = $ctx->ok($bool, $name) / $event = $ctx->ok($bool, $name, \@diag) β€” creates a Test::Stream::Event::Ok object for you. The diagnostics array gets used on the object if the test fails; if it passes, the diagnostics are ignored. πŸ’–
  • $event = $ctx->note($message) β€” sends a Test::Stream::Event::Note. This event prints a message to STDOUT. πŸ“
  • $event = $ctx->diag($message) β€” sends a Test::Stream::Event::Diag. This event prints a message to STDERR. 🚨
  • $event = $ctx->plan($max) / $event = $ctx->plan(0, 'SKIP', $reason) β€” sends a Test::Stream::Event::Plan event. Usually you give it the number of tests you expect to run. Optionally, you can set the expected count to 0 and pass the 'SKIP' directive with a reason to skip all tests. πŸ—“οΈ
  • $event = $ctx->bail($reason) β€” sends a Test::Stream::Event::Bail event. This event will completely terminate all testing. πŸ›‘
  • $event = $ctx->send_event($Type, %parameters) β€” lets you build and send an event of any type. The $Type argument should be the event package name with Test::Stream::Event:: left off, or a fully qualified package name prefixed with a '+'. The event is returned after it's sent. πŸš€
my $event = $ctx->send_event('Ok', ...);

or

my $event = $ctx->send_event('+Test::Stream::Event::Ok', ...);
  • $event = $ctx->build_event($Type, %parameters) β€” same as send_event(), except it builds and returns the event without sending it. πŸ› οΈ

πŸͺ HOOKS πŸͺ

There are 2 types of hooks: init hooks and release hooks. As the names suggest, these hooks are triggered when contexts are created or released. πŸŽ€

🌟 INIT HOOKS 🌟

These are called whenever a context is initialized β€” that means when a new instance is created. These hooks are NOT called every time something requests a context, just when a new one is created. πŸ’«

🌈 GLOBAL 🌈

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

Test::Stream::Context->ON_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 are called whenever a context is released β€” that means when the last reference to the instance is about to be destroyed. These hooks 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. 🌍

Test::Stream::Context->ON_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. πŸ’…

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

πŸ“š SOURCE πŸ“š

The source code repository for Test::Stream can be found at http://github.com/Test-More/Test-Stream/. πŸ™

πŸ‘‘ MAINTAINERS πŸ‘‘

  • Chad Granum <exodist@cpan.org>

πŸ’œ AUTHORS πŸ’œ

  • Chad Granum <exodist@cpan.org>
  • Kent Fredric <kentnl@cpan.org>

Copyright 2015 Chad Granum <exodist7@gmail.com>.

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/


And that's the whole vibe! This page is from perl v5.42.0, dated 2025-07-25, and it's Test::S...:Context(3). Slay bestie, go write some tests! πŸ’…βœ¨

πŸ“¦ where this page comes from