Test2::Event(3pm)

✨ NAME ✨

Okay bestie, welcome to the Test2::Event(3pm) page from the Perl Programmers Reference Guide πŸ’–

Test2::Event is the base class for events. Like, the blueprint every event object inherits from.


πŸ’… DESCRIPTION πŸ’…

It’s the base class for all event objects that get passed through Test2. Periodt. Every event vibes on top of this.


🌸 SYNOPSIS 🌸

package Test2::Event::MyEvent;
use strict;
use warnings;

# This will make our class an event subclass (required)
use base 'Test2::Event';

# Add some accessors (optional)
# You are not obligated to use HashBase, you can use any object tool you
# want, or roll your own accessors.
use Test2::Util::HashBase qw/foo bar baz/;

# Use this if you want the legacy API to be written for you, for this to
# work you will need to implement a facet_data() method.
use Test2::Util::Facets2Legacy;

# Chance to initialize some defaults
sub init {
    my $self = shift;
    # no other args in @_

    $self->set_foo('xxx') unless defined $self->foo;

    ...
}

# This is the new way for events to convey data to the Test2 system
sub facet_data {
    my $self = shift;

    # Get common facets such as 'about', 'trace' 'amnesty', and 'meta'
    my $facet_data = $self->common_facet_data();

    # Are you making an assertion?
    $facet_data->{assert} = {pass => 1, details => 'my assertion'};
    ...

    return $facet_data;
}

1;

πŸ¦‹ METHODS πŸ¦‹

πŸ’– GENERAL πŸ’–

  • $trace = $e->trace β€” grabs you a snapshot of the Test2::EventFacet::Trace exactly as it was when this event got generated. Like a little time capsule for your test event ⏳
  • $bool_or_undef = $e->related($e2) β€” checks if two events are related. And β€œrelated” here means their traces share a signature, meaning they were created with the same context (or at the very least by contexts which share an id, which is the same thing unless someone is doing something very bad πŸ™ˆ).

This is how you reliably link multiple events created by the same tool. For instance a failing test like "ok(0, "fail"" will generate 2 events, one being a Test2::Event::Ok, the other being a Test2::Event::Diag. Both of these events are related, having been created under the same context and by the same initial tool (though multiple tools may have been nested under the initial one).

This returns undef if the relationship cannot be checked, which happens if either event has an incomplete or missing trace. It returns 0 if the traces are complete but do not match. It returns 1 if there is a match. No cap.

  • $e->add_amnesty({tag => $TAG, details => $DETAILS}); β€” adds amnesty to this event. Amnesty only affects failing assertions in most cases, but some formatters may display them for passing assertions, or even non-assertions as well.

Amnesty prevents a failed assertion from causing the overall test to fail. In other words: it marks a failure as expected and allowed. Iconic forgiveness behavior πŸ’…

Note: this is literally how 'TODO' is implemented under the hood. TODO is essentially amnesty with the 'TODO' tag. The details are the reason for the TODO.

  • $uuid = $e->uuid β€” if UUID tagging is enabled (see Test::API) then any event that has made its way through a hub will be tagged with a UUID. A newly created event will not yet be tagged in most cases.
  • $class = $e->load_facet($name) β€” used to load a facet by name (or key). It attempts to load the facet class; if it succeeds it returns the class it loaded. If it fails it returns undef. This caches the result at the class level so future calls are faster ⚑

The $name variable should be the key used to access the facet in a facets hashref. For instance the assertion facet has the key 'assert', the information facet has the 'info' key, and the error facet has the key 'errors'. You may include or omit the 's' at the end of the name; the method is smart enough to try both the 's' and no-'s' forms. It checks what you provided first, and if that is not found it will add or strip the 's' and try again.

  • @classes = $e->FACET_TYPES()
  • @classes = Test2::Event->FACET_TYPES() β€” returns a list of all facets that have been loaded using the load_facet() method. This will not return any classes that have not been loaded, or have been loaded directly without a call to load_facet().

Note: the core facet types are automatically loaded and populated in this list ✨

🌈 NEW API 🌈

  • $hashref = $e->common_facet_data(); β€” subclasses can use this to generate a starting facet data hashref. It populates the hashref with the trace, meta, amnesty, and about facets. These facets are nearly always produced the same way for all events.
  • $hashref = $e->facet_data() β€” if you do not override this, then the default implementation will attempt to generate facets from the legacy API. This generation is limited only to what the legacy API can provide. It is recommended that you override this method and write out explicit facet data. Future-you will thank you 🫢
  • $hashref = $e->facets() β€” takes the hashref from facet_data() and blesses each facet into the proper "Test2::EventFacet::*" subclass. If no class can be found for any given facet it will be passed along unchanged.
  • @errors = $e->validate_facet_data();
  • @errors = $e->validate_facet_data(%params);
  • @errors = $e->validate_facet_data(\%facets, %params);
  • @errors = Test2::Event->validate_facet_data(%params);
  • @errors = Test2::Event->validate_facet_data(\%facets, %params); β€” this method validates facet data and returns a list of errors. If no errors are found this returns an empty list.

This can be called as an object method with no arguments, in which case the facet_data() method will be called to get the facet data to be validated.

When used as an object method the \%facet_data argument may be omitted.

When used as a class method the \%facet_data argument is required.

Remaining arguments get slurped into a %params hash.

Currently only 1 parameter is defined:

  • require_facet_class => $BOOL β€” when set to true (default is false) this rejects any facets where a facet class cannot be found. Normally facets without classes are assumed to be custom and are ignored.

🧚 WHAT ARE FACETS? 🧚

Facets are how events convey their purpose to the Test2 internals and formatters. An event without facets will have no intentional effect on the overall test state, and will not be displayed at all by most formatters, except perhaps to say that an event of an unknown type was seen πŸ‘€

Facets are produced by the facet_data() subroutine, which you should nearly-always override. facet_data() is expected to return a hashref where each key is the facet type, and the value is either a hashref with the data for that facet, or an array of hashrefs. Some facets must be defined as single hashrefs, some must be defined as an array of hashrefs. No facets allow both. That’s the rule, bestie.

facet_data() MUST NOT bless the data it returns. The main hashref and nested facet hashrefs MUST be bare, though items contained within each facet may be blessed. The data returned by this method should also be copies of the internal data in order to prevent accidental state modification.

facets() takes the data from facet_data() and blesses it into the "Test2::EventFacet::*" packages. This is rarely used however, the EventFacet packages are primarily for convenience and documentation. The EventFacet classes are not used at all internally; instead the raw data is used.

Here is a list of facet types by package. The packages are not used internally, but are where the documentation for each type is kept.

Note: every single facet type has the 'details' field. This field is always intended for human consumption, and when provided, should explain the 'why' for the facet. All other fields are facet specific.

  • about => {...} β€” Test2::EventFacet::About. This contains information about the event itself such as the event package name. The "details" field for this facet is an overall summary of the event.
  • assert => {...} β€” Test2::EventFacet::Assert. This facet is used if an assertion was made. The "details" field of this facet is the description of the assertion.
  • control => {...} β€” Test2::EventFacet::Control. This facet is used to tell the Test2::Event::Hub about special actions the event causes. Things like halting all testing, terminating the current test, etc. In this facet the "details" field explains why any special action was taken.

Note: this is how bail-out is implemented πŸ’€

  • meta => {...} β€” Test2::EventFacet::Meta. The meta facet contains all the meta-data attached to the event. In this case the "details" field has no special meaning, but may be present if something sets the 'details' meta-key on the event.
  • parent => {...} β€” Test2::EventFacet::Parent. This facet contains nested events and similar details for subtests. In this facet the "details" field will typically be the name of the subtest.
  • plan => {...} β€” Test2::EventFacet::Plan. This facet tells the system that a plan has been set. The "details" field of this is usually left empty, but when present explains why the plan is what it is. This is most useful if the plan is to skip-all.
  • trace => {...} β€” Test2::EventFacet::Trace. This facet contains information related to when and where the event was generated. This is how the test file and line number of a failure is known. This facet can also help you tell if tests are related.

In this facet the "details" field overrides the "failed at test_file.t line 42." message provided on assertion failure.

  • amnesty => [{...}, ...] β€” Test2::EventFacet::Amnesty. The amnesty facet is a list instead of a single item. This is important as amnesty can come from multiple places at once.

For each instance of amnesty the "details" field explains why amnesty was granted.

Note: outside of formatters amnesty only acts to forgive a failing assertion.

  • errors => [{...}, ...] β€” Test2::EventFacet::Error. The errors facet is a list instead of a single item; any number of errors can be listed. In this facet "details" describes the error, or may contain the raw error message itself (such as an exception). In perl exception may be blessed objects, as such the raw data for this facet may contain nested items which are blessed.

Not all errors are considered fatal, bestie β€” there's a "fail" field that has to be set for an error to actually cause the test to fail. 😌

Note: this facet is unique in that the field name is errors while the package is Error. It's literally the only facet type that's both a list and has a name where the plural isn't the same as the singular. Yeah, that may cause some confusion, but the author feels it'll be less confusing than the alternative. πŸ™ˆ
  • info => [{...}, ...] β€” 🌸 the Test2::EventFacet::Info facet

The info facet is a list instead of a single item, so you can attach literally any quantity of extra information to an event. Some of that info may be critical diagnostics, some may just be commentary in nature β€” the "debug" flag is what decides which is which. πŸ¦‹

For this facet the "details" flag is the info itself. That info may be a string, or it may be a data structure to display. This is one of the few facet types that may contain blessed items. ✨


πŸ•°οΈ LEGACY API ✨

These are the old-school methods, still iconic, still doing their job πŸ’…

  • $bool = $e->causes_fail β€” returns true if this event should result in a test failure. In general this should be false. 🫢
  • $bool = $e->increments_count β€” should be true if this event should result in a test count increment. πŸ”’
  • $e->callback($hub) β€” if your event needs to have extra effects on the Test2::Hub, you can override this method. πŸŽ€

This is called BEFORE your event is passed to the formatter. ⏰

  • $num = $e->nested β€” if this event is nested inside of other events, this should be the depth of nesting. (This is mainly for subtests.) πŸͺ†
  • $bool = $e->global β€” set this to true if your event is global, meaning ALL threads and processes should see it no matter when or where it's generated. This is not a common thing to want β€” it's used by bail-out and skip_all to end testing. πŸŒπŸ’€
  • $code = $e->terminate β€” this is called AFTER your event has been passed to the formatter. It should normally return undef; only change this if your event should cause the test to exit immediately. πŸšͺ

If you want this event to cause the test to exit you should return the exit code here. Exit code of 0 means exit success, any other integer means exit with failure. 😬

This is used by Test2::Event::Plan to exit 0 when the plan is 'skip_all'. This is also used by Test2::Event:Bail to force the test to exit with a failure. πŸ”₯

This is called after the event has been sent to the formatter, in order to ensure the event is seen and understood. πŸ‘€

  • $msg = $e->summary β€” this is intended to be a human readable summary of the event. Ideally it should only be one line long, but you can use multiple lines if necessary. It's for human consumption β€” you do not need to make it easy for machines to understand. 🧚

The default is to simply return the event package name. 🏷️

  • ($count, $directive, $reason) = $e->sets_plan() β€” check if this event sets the testing plan. It'll return an empty list if it doesn't. If it does set the plan, it returns a list of 1 to 3 items, in order: Expected Test Count, Test Directive, Reason for directive. πŸ“‹
  • $bool = $e->diagnostics β€” true if the event contains diagnostics info. This is useful because a non-verbose harness may choose to hide events that aren't in this category. Some formatters may choose to send these to STDERR instead of STDOUT to make sure they're seen. 🩺
  • $bool = $e->no_display β€” false by default. This returns true on events that should not be displayed by formatters. πŸ™ˆ
  • $id = $e->in_subtest β€” if the event is inside a subtest, this should have the subtest ID. πŸͺΊ
  • $id = $e->subtest_id β€” if the event is a final subtest event, this should contain the subtest ID. 🏁

πŸ”– THIRD PARTY META-DATA

This object consumes Test2::Util::ExternalMeta, which gives you a consistent way to attach meta-data to instances of this class. Super 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>

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 the whole page, bestie β€” no cap, you now know Test2::Event front to back πŸŽ‰ This was Test2::Event(3pm) from perl v5.42.3, dated 2026-11-03 β€” go forth and slay your events πŸ’–πŸ¦‹

πŸ“¦ where this page comes from