TEST2::TOOLS::COMPARE(3perl)

๐Ÿ‘‘ NAME ๐Ÿ‘‘

Test2::Tools::Compare โ€” tools for comparing deep data structures, bestie ๐Ÿ’–


๐ŸŒธ DESCRIPTION ๐ŸŒธ

Okay so back in the day Test::More had is_deeply(), right? This library is the Test2 glow-up of that whole concept โ€” it compares data structures, but it does NOT stop there, no ma'am. It goes a whole step further and hands you tools to build a specification of a data structure, and then you verify your actual data against that spec. And guess what? There are both 'strict' and 'relaxed' versions of the tools. Pick your vibe. ๐Ÿ’…


โœจ SYNOPSIS โœจ

use Test2::Tools::Compare;

# Hash for demonstration purposes
my $some_hash = {a => 1, b => 2, c => 3};

# Strict checking, everything must match
is(
    $some_hash,
    {a => 1, b => 2, c => 3},
    "The hash we got matches our expectations"
);

# Relaxed Checking, only fields we care about are checked, and we can use a
# regex to approximate a field.
like(
    $some_hash,
    {a => 1, b => qr/\A[0-9]+\z/},
    "'a' is 1, 'b' is an integer, we don't care about 'c'."
);

๐Ÿฆ‹ ADVANCED ๐Ÿฆ‹

So there are declarative hash, array, and object builders that let you generate specifications. Lowkey they're more verbose than just handing over a plain hash, but the glow-up is real: every single component you specify gets a line number attached to it. That's iconic for debugging, because when a test fails the output tells you not only which field was wrong but also the exact line where you declared that field. Chef's kiss. ๐Ÿ˜ญ

use Test2::Tools::Compare qw{
    is like isnt unlike
    match mismatch validator
    hash array bag object meta number float rounded within string subset bool
    in_set not_in_set check_set
    item field call call_list call_hash prop check all_items all_keys all_vals all_values
    etc end filter_items
    T F D DF E DNE FDNE U L
    event fail_events
    exact_ref
};

is(
    $some_hash,
    hash {
        field a => 1;
        field b => 2;
        field c => 3;
    },
    "Hash matches spec"
);

๐Ÿ’… COMPARISON TOOLS ๐Ÿ’…

๐Ÿ’– $bool = is($got, $expect)

๐Ÿ’– $bool = is($got, $expect, $name)

๐Ÿ’– $bool = is($got, $expect, $name, @diag)

Okay so $got is the data structure you wanna check, $expect is what you want $got to look like, $name is an optional name for the test, and @diag is optional diagnostics messages that get printed to STDERR if things go wrong โ€” they will NOT show up when the comparison succeeds, so no messy noise. The boolean true/false result of the comparison gets returned. ๐Ÿซถ

This is the strict checker. It requires a perfect match between $got and $expect. All hash fields must be specified, all array items must be present, etc. All non-scalar/hash/array/regex references must be identical (same memory address). Scalar, hash and array references will be traversed and compared. Regex references get compared to see if they have the same pattern.

is(
    $some_hash,
    {a => 1, b => 2, c => 3},
    "The hash we got matches our expectations"
);

The only exception to strictness is when you give it an $expect object that was built from a specification โ€” in that case the specification itself determines the strictness. Strictness only applies to literal values/references that you provide and that get converted to a specification for you. ๐Ÿงš

is(
    $some_hash,
    hash {    # Note: the hash function is not exported by default
        field a => 1;
        field b => match(qr/\A[0-9]+\z/);    # Note: The match function is not exported by default
        # Don't care about other fields.
    },
    "The hash comparison is not strict"
);

This works for both deep and shallow structures. Like, you can literally use this to compare two strings:

is('foo', 'foo', "strings match");
Note: This is not the tool to use if you want to check if two references are the same exact reference โ€” use ref_is() from the Test2::Tools::Ref plugin instead. Most of the time this will work as well, however there are problems if your reference contains a cycle and refers back to itself at some point. If that happens, an exception will be thrown to break an otherwise infinite recursion. ๐Ÿ’€
Note: Non-reference values will be compared as strings using "eq", so that means strings '2.0' and '2' will not match, but numeric 2.0 and 2 will, since they are both stringified to '2'.

๐Ÿ’– $bool = isnt($got, $expect)

๐Ÿ’– $bool = isnt($got, $expect, $name)

๐Ÿ’– $bool = isnt($got, $expect, $name, @diag)

Opposite of is(). Does all the same checks, but passes when there is a mismatch. Gender-flipped queen. ๐Ÿ‘‘


๐Ÿ’– $bool = like($got, $expect)

๐Ÿ’– $bool = like($got, $expect, $name)

๐Ÿ’– $bool = like($got, $expect, $name, @diag)

$got is the data structure you want to check. $expect is what you want $got to look like. $name is an optional name for the test. @diag is optional diagnostics messages that will be printed to STDERR in event of failure โ€” they will not be displayed when the comparison is successful. The boolean true/false result of the comparison is returned.

This is the relaxed checker. It will ignore hash keys or array indexes that you don't actually specify in your $expect structure. Plus, regex and sub references get used as validators. If you provide a regex using qr/.../, the regex itself will be used to validate the corresponding value in the $got structure. Same energy for coderefs โ€” the value is passed in as the first argument (and in $_) and the sub should return a boolean value. In this tool, regexes will stringify the thing they are checking. โœจ

like(
    $some_hash,
    {a => 1, b => qr/\A[0-9]+\z/},
    "'a' is 1, 'b' is an integer, we don't care about other fields"
);

This works for both deep and shallow structures. For instance you can use this to compare two strings:

like('foo bar', qr/^foo/, "string matches the pattern");

๐Ÿ’– $bool = unlike($got, $expect)

๐Ÿ’– $bool = unlike($got, $expect, $name)

๐Ÿ’– $bool = unlike($got, $expect, $name, @diag)

Opposite of like(). Does all the same checks, but passes when there is a mismatch. ๐Ÿ’…


The is(), isnt(), like(), and unlike() functions can be made to dump $got using Data::Dumper when tests fail by setting the "T2_AUTO_DUMP" environment variable to "1". (Alternatively, "T2_AUTO_DUMP" can be set to the name of a Perl module providing a compatible Dump() method.) The "T2_AUTO_DEPARSE" environment variable can be used to enable Data::Dumper's deparsing of coderefs. ๐Ÿ”ฅ


๐ŸŽ€ QUICK CHECKS ๐ŸŽ€

Note: None of these are exported by default. You need to request them, bestie. ๐Ÿ™ˆ

Quick checks are a way to quickly generate a common value specification. These can be used in structures passed into "is" and "like" through the $expect argument.

Example:

is($foo, T(), '$foo has a true value');

โญ $check = T()

This verifies that the value in the corresponding $got structure is true โ€” any true value will do.

is($foo, T(), '$foo has a true value');

is(
    { a => 'xxx' },
    { a => T() },
    "The 'a' key is true"
);

โญ $check = F()

This verifies that the value in the corresponding $got structure is false โ€” any false value will do, but the value must exist.

is($foo, F(), '$foo has a false value');

is(
    { a => 0 },
    { a => F() },
    "The 'a' key is false"
);

It is important to note that a nonexistent value does not count as false. This check will generate a failing test result:

is(
    { a => 1 },
    { a => 1, b => F() },
    "The 'b' key is false"
);

This will produce the following output:

not ok 1 - The b key is false
# Failed test "The 'b' key is false"
# at some_file.t line 10.
# +------+------------------+-------+---------+
# | PATH | GOT              | OP    | CHECK   |
# +------+------------------+-------+---------+
# | {b}  | <DOES NOT EXIST> | FALSE | FALSE() |
# +------+------------------+-------+---------+

In Perl, you can have behavior that is different for a missing key vs. a false key, so it was decided not to count a completely absent value as false. See the DNE() shortcut below for checking that a field is missing. ๐Ÿฆ‹

If you want to check for false and/or DNE use the FDNE() check.


โญ $check = D()

This is to verify that the value in the $got structure is defined. Any value other than "undef" will pass.

This will pass:

is('foo', D(), 'foo is defined');

This will fail:

is(undef, D(), 'foo is defined');

โญ $check = U()

This is to verify that the value in the $got structure is undefined. ๐ŸŒˆ

This will pass:

is(undef, U(), 'not defined');

This will fail:

is('foo', U(), 'not defined');

โญ $check = DF()

This is to verify that the value in the $got structure is defined but false. Any false value other than "undef" will pass.

This will pass:

is(0, DF(), 'foo is defined but false');

These will fail:

is(undef, DF(), 'foo is defined but false');
is(1, DF(), 'foo is defined but false');

โญ $check = E()

This can be used to check that a value exists. This is useful to check that an array has more values, or to check that a key exists in a hash, even if the value is undefined. ๐Ÿ‘‘

These pass:

is(['a', 'b', undef], ['a', 'b', E()], "There is a third item in the array");
is({a => 1, b => 2}, {a => 1, b => E()}, "The 'b' key exists in the hash");

These will fail:

is(['a', 'b'], ['a', 'b', E()], "Third item exists");
is({a => 1}, {a => 1, b => E()}, "'b' key exists");

โญ $check = DNE()

This can be used to check that no value exists. This is useful to check the end bound of an array, or to check that a key does not exist in a hash. โœจ

These pass:

is(['a', 'b'], ['a', 'b', DNE()], "There is no third item in the array");
is({a => 1}, {a => 1, b => DNE()}, "The 'b' key does not exist in the hash");

These will fail:

is(['a', 'b', 'c'], ['a', 'b', DNE()], "No third item");
is({a => 1, b => 2}, {a => 1, b => DNE()}, "No 'b' key");
  • FDNE() โ€” lowkey the combo meal of F() and DNE() ๐ŸŸ it passes when the value is false, OR when it doesn't exist at all. Either way, slay.
  • L() โ€” checks that the thing in the $got structure is defined AND has length. Anything that isn't undef or the empty string passes โœจ (yes, references count too, they're valid).

These are gonna pass, bestie:

is('foo', L(), 'value is defined and has length');
is([],    L(), 'value is defined and has length');

And these? Not so much ๐Ÿ’€:

is(undef, L(), 'value is defined and has length');
is('',    L(), 'value is defined and has length');

๐Ÿ’– VALUE SPECIFICATIONS ๐Ÿ’–

Note: None of these are exported by default. You need to request them. fr fr, you gotta ask nicely first ๐Ÿฅบ
  • string "..." โ€” verifies the value matches that string, using the eq operator.
  • !string "..." โ€” verifies the value does NOT match that string, using the ne operator.
  • number ...; โ€” verifies the value matches the given number, using the == operator.
  • !number ...; โ€” verifies the value does not match the given number, using the != operator.
  • number_lt ...; / number_le ...; / number_ge ...; / number_gt ...; โ€” verifies the value is less than, less than or equal to, greater than or equal to, or greater than the given number. it's giving comparison buffet, pick your fighter ๐ŸฅŠ
  • float ...; โ€” verifies the value is approximately equal to the given number. close enough counts here ๐Ÿ’…

If a 'precision' parameter is specified, both operands get rounded to 'precision' number of fractional decimal digits and then compared with eq.

is($near_val, float($val, precision => 4), "Near 4 decimal digits");

Otherwise the check happens within a range of +/- 'tolerance', and the default 'tolerance' is 1e-08. iconic default behavior ngl.

is( $near_val, float($val, tolerance => 0.01), "Almost there...");

See also "within" and "rounded". โœจ

  • !float ...; โ€” verifies the value is not approximately equal to the given number.

If a 'precision' parameter is specified, both operands get rounded to 'precision' number of fractional decimal digits and compared with eq.

Otherwise the check happens within a range of +/- 'tolerance', with a default 'tolerance' of 1e-08.

See also "!within" and "!rounded". ๐Ÿ’œ

  • within($num, $tolerance); โ€” verifies the value approximately matches $num, within a range of +/- $tolerance. Compared using the == operator.

$tolerance is optional and defaults to 1e-08.

  • !within($num, $tolerance); โ€” verifies the value does not approximately match $num within a range of +/- $tolerance. Compared using the != operator.

$tolerance is optional and defaults to 1e-08.

  • rounded($num, $precision); โ€” verifies the value approximately matches $num, when both get rounded to $precision number of fractional digits. Compared using the eq operator. ๐ŸŽ€
  • !rounded($num, $precision); โ€” verifies the value does not approximately match $num, when both get rounded to $precision number of fractional digits. Compared using the ne operator.
  • bool ...; โ€” verifies the value has the same boolean value as the given argument (XNOR). twin behavior ๐Ÿซถ
  • !bool ...; โ€” verifies the value has a different boolean value from the given argument (XOR). opposites attract, apparently ๐Ÿ˜ญ
  • check_isa ...; โ€” verifies the value is an instance of the given class name.
  • !check_isa ...; โ€” verifies the value is not an instance of the given class name.
  • match qr/.../ / !mismatch qr/.../ โ€” verifies the value matches the regex pattern. This form of pattern check will NOT stringify references being checked. no sneaky stringification here bestie.
Note: !mismatch() is documented for completion, please do not use it. like... it's in the docs but it's a legacy jumpscare, please don't ๐Ÿ™ˆ
  • !match qr/.../ / mismatch qr/.../ โ€” verifies the value does not match the regex pattern. This form of pattern check will NOT stringify references being checked.
Note: mismatch() was created before overloading of ! for match() was a thing. so it's a lil historical artifact, iykyk ๐Ÿบ
  • validator(sub{ ... }) / validator($NAME => sub{ ... }) / validator($OP, $NAME, sub{ ... }) โ€” the coderef is the only required argument. The coderef should check that the value is what you expect and return a boolean true or false. Optionally you can specify a name and an operator that are used in diagnostics. They also get provided to the sub itself as named parameters. ๐Ÿงš

Check the value using this sub. The sub gets the value in $_, and it receives the value plus several other items as named parameters.

my $check = validator(sub {
    my %params = @_;

    # These both work:
    my $got = $_;
    my $got = $params{got};

    # Check if a value exists at all
    my $exists = $params{exists}

    # What $OP (if any) did we specify when creating the validator
    my $operator = $params{operator};

    # What name (if any) did we specify when creating the validator
    my $name = $params{name};

    ...

    return $bool;
}
  • exact_ref($ref) โ€” checks that the value is exactly the same reference as the one you provided. same object, same vibe check, periodt ๐Ÿ‘‘

๐ŸŒˆ SET BUILDERS ๐ŸŒˆ

Note: None of these are exported by default. You need to request them.
  • my $check = check_set($check1, $check2, ...) โ€” checks that the value matches ALL of the specified checks. all of them. every single one. no skipping ๐Ÿ™…โ€โ™€๏ธ
  • my $check = in_set($check1, $check2, ...) โ€” checks that the value matches ONE OR MORE of the specified checks. it's giving "any of these is fine" energy โœจ
  • not_in_set($check1, $check2, ...) โ€” checks that the value DOES NOT match ANY of the specified checks. the whole squad is rejected ๐Ÿ’€
  • check $thing โ€” checks that the value matches the specified thing.

๐ŸŽ€ HASH BUILDER ๐ŸŽ€

Note: None of these are exported by default. You need to request them.
$check = hash {
    field foo => 1;
    field bar => 2;

    # Ensure the 'baz' keys does not even exist in the hash.
    field baz => DNE();

    # Ensure the key exists, but is set to undef
    field bat => undef;

    # Any check can be used
    field boo => $check;

    # Set checks that apply to all keys or values. Can be done multiple
    # times, and each call can define multiple checks, all will be run.
    all_vals match qr/a/, match qr/b/;    # All values must have an 'a' and a 'b'
    all_keys match qr/x/;                 # All keys must have an 'x'

    ...

    end(); # optional, enforces that no other keys are present.
};
  • $check = hash { ... } โ€” this is how you define a hash check ๐Ÿ’…
  • field $NAME => $VAL / field $NAME => $CHECK โ€” specifies a field check. This checks the hash key named by $NAME and makes sure it matches the value in $VAL. You can drop any valid check in $VAL, like the result of another call to array { ... }, DNE(), and so on. sky's the limit ๐Ÿฆ‹
Note: This function can only be used inside a hash builder sub, and must be called in void context.
  • all_keys($CHECK1, $CHECK2, ...) โ€” adds checks that apply to all keys. You can put this literally anywhere in the hash block, and you can call it any number of times with any number of arguments. spamming allowed โœจ
  • all_vals($CHECK1, $CHECK2, ...) / all_values($CHECK1, $CHECK2, ...) โ€” adds checks that apply to all values. You can put this anywhere in the hash block too, and call it any number of times with any number of arguments.
  • end() โ€” enforces that no keys are found in the hash other than the ones you specified. This is basically the use strict of a hash check ngl ๐Ÿ”’ can be used anywhere in the hash builder, though typically it goes at the end.
  • etc() โ€” ignores any extra keys found in the hash. This is the opposite of end(). Can be used anywhere in the hash builder, though typically it's placed at the end. live and let live ๐Ÿ•Š๏ธ
  • DNE() โ€” a handy check you can use with field() to ensure that a field (D)oes (N)ot (E)xist. bye felicia ๐Ÿ‘‹
field foo => DNE();

โญ ARRAY BUILDER โญ

Note: None of these are exported by default. You need to request them.
$check = array {
    # Uses the next index, in this case index 0;
    item 'a';

    # Gets index 1 automatically
    item 'b';

    # Specify the index
    item 2 => 'c';

    # We skipped index 3, which means we don't care what it is.
    item 4 => 'e';

    # Gets index 5.
    item 'f';

    # Remove any REMAINING items that contain 0-9.
    filter_items { grep {!m/[0-9]/} @_ };

    # Set checks that apply to all items. Can be done multiple times, and
    # each call can define multiple checks, all will be run.
    all_items match qr/a/, match qr/b/;
    all_items match qr/x/;

    # Of the remaining items (after the filter is applied) the next one
    # (which is now index 6) should be 'g'.
    item 6 => 'g';

    item 7 => DNE; # Ensure index 7 does not exist.

    end(); # Ensure no other indexes exist.
};
  • $check = array { ... } โ€” the array-flavored builder ๐Ÿ“
  • item $VAL / item $CHECK / item $IDX, $VAL / item $IDX, $CHECK โ€” adds an expected item to the array. If $IDX isn't specified it'll automatically calculate it based on the last item added. You can skip indexes, which basically says "idk don't check that one" ๐Ÿคทโ€โ™€๏ธ

You can provide any value to check in $VAL, or you can provide any valid check object.

Note: Items MUST be added in order. no jumping around bestie.
Note: This function can only be used inside an array, bag or subset builder sub, and must be called in void context.
  • filter_items { my @remaining = @_; ...; return @filtered } โ€” this adds a filter. All items still remaining in the array from the point the filter is reached get passed into the filter sub as arguments, and the sub should return only the items that should be checked. like a little sieve ๐Ÿซถ
Note: This function can only be used inside an array builder sub, and must be called in void context.
  • all_items($CHECK1, $CHECK2, ...) โ€” adds checks that apply to all items. You can put this anywhere in the array block, and call it any number of times with any number of arguments. go off, spam it ๐Ÿ”ฅ
  • end() โ€” enforces that there are no indexes after the last one specified. This will not force checking of skipped indexes. so skipped stays skipped, respect the skip ๐Ÿ’…

etc()

Ignore any extra items you find chillin' in the array. It's the exact opposite vibe of end(). โœจ You can drop this literally anywhere in the array builder โ€” start, middle, wherever โ€” but bestie, most people just put it at the end because that's the natural place for it. ๐Ÿ’…

DNE()

This is the handy little check you pair with item() when you need to make sure an index (D)oes (N)ot (E)xist. ๐Ÿ’€

item 5 => DNE();

๐Ÿ‘œ BAG BUILDER ๐Ÿ‘œ

Note: None of these are exported by default. You gotta request them, bestie. ๐Ÿซถ
$check = bag {
    item 'a';
    item 'b';

    end(); # Ensure no other elements exist.
};

So a bag is like an array, but we literally do not care about the order of the items. ๐Ÿ™ˆ In that example up there, $check would match both ['a','b'] and ['b','a']. Order is not the point, the existence is. Periodt.

$check = bag { ... }

Build yourself a bag check. That's the vibe.

item $VAL

item $CHECK

Add an expected item to the bag. ๐Ÿ’–

You can hand it any value to check in $VAL, or you can hand it any valid check object. Either way slays.

Note: This function can only be used inside an array, bag or subset builder sub, and it must be called in void context.

all_items($CHECK1, $CHECK2, ...)

Add checks that apply to all items. ๐Ÿ‘‘ You can put this literally anywhere in the bag block, and you can call it as many times as you want with as many arguments as you want. No cap.

end()

Enforce that there are no more items after the last one you specified. That's it, that's the whole job. โœ…

etc()

Ignore any extra items found in the array. This is the opposite of end(). ๐ŸŒธ Same deal โ€” drop it anywhere in the bag builder, though typically it goes at the end.


๐Ÿ”ข ORDERED SUBSET BUILDER ๐Ÿ”ข

Note: None of these are exported by default. You need to request them. ๐Ÿ’…
$check = subset {
    item 'a';
    item 'b';
    item 'c';

    # Doesn't matter if the array has 'd', the check will skip past any
    # unknown items until it finds the next one in our subset.

    item 'e';
    item 'f';
};

$check = subset { ... }

Build the subset check. Slay.

item $VAL

item $CHECK

Add an expected item to the subset. โœจ

You can provide any value to check in $VAL, or you can provide any valid check object.

Note: Items MUST be added in order. Like, this is not optional, bestie. The whole point is the order.
Note: This function can only be used inside an array, bag or subset builder sub, and must be called in void context.

๐Ÿ”ฎ META BUILDER ๐Ÿ”ฎ

Note: None of these are exported by default. You need to request them. ๐Ÿซถ
my $check = meta {
    prop blessed => 'My::Module'; # Ensure value is blessed as our package
    prop reftype => 'HASH';       # Ensure value is a blessed hash
    prop isa     => 'My::Base';   # Ensure value is an instance of our class
    prop size    => 4;            # Check the number of hash keys
    prop this    => ...;          # Check the item itself
};

meta { ... }

meta_check { ... }

Build a meta check. ๐Ÿ’œ Now listen โ€” if you're using Moose, then the meta() function is gonna beef with the one Moose exports, so in those cases meta_check() is there for you. Neither one is exported by default, so you're always opting in.

prop $NAME => $VAL

prop $NAME => $CHECK

Check the property specified by $name against the value or the check. ๐ŸŽ€

The valid properties are:

  • 'blessed' โ€” What package (if any) the thing is blessed as.
  • 'reftype' โ€” Reference type (if any) the thing is.
  • 'isa' โ€” What class the thing is an instance of.
  • 'this' โ€” The thing itself.
  • 'size' โ€” For array references this returns the number of elements. For hashes this returns the number of keys. For everything else this returns undef.

๐ŸŽ€ OBJECT BUILDER ๐ŸŽ€

Note: None of these are exported by default. You need to request them. ๐ŸŒธ
my $check = object {
    call foo => 1; # Call the 'foo' method, check the result.

    # Call the specified sub-ref as a method on the object, check the
    # result. This is useful for wrapping methods that return multiple
    # values.
    call sub { [ shift->get_list ] } => [...];

    # This can be used to ensure a method does not exist.
    call nope => DNE();

    # Check the hash key 'foo' of the underlying reference, this only works
    # on blessed hashes.
    field foo => 1;

    # Check the value of index 4 on the underlying reference, this only
    # works on blessed arrays.
    item 4 => 'foo';

    # Check the meta-property 'blessed' of the object.
    prop blessed => 'My::Module';

    # Check if the object is an instance of the specified class.
    prop isa => 'My::Base';

    # Ensure only the specified hash keys or array indexes are present in
    # the underlying hash. Has no effect on meta-property checks or method
    # checks.
    end();
};

$check = object { ... }

Specify an object check for use in comparisons. That's the whole assignment, bestie. โœจ

call $METHOD_NAME => $RESULT

call $METHOD_NAME => $CHECK

call [$METHOD_NAME, @METHOD_ARGS] => $RESULT

call [$METHOD_NAME, @METHOD_ARGS] => $CHECK

call sub { ... }, $RESULT

call sub { ... }, $CHECK

Call the specified method (or coderef) and verify the result. ๐Ÿ“ž If you pass an arrayref, the first element must be the method name, and the rest of them are the arguments it's gonna be called with.

The coderef form is the move when you need to do something more complex. ๐Ÿ‘‘

my $ref = sub {
  local $SOME::GLOBAL::THING = 3;
  return [shift->get_values_for('thing')];
};

call $ref => ...;

call_list $METHOD_NAME => $RESULT

call_list $METHOD_NAME => $CHECK

call_list [$METHOD_NAME, @METHOD_ARGS] => $RESULT

call_list [$METHOD_NAME, @METHOD_ARGS] => $CHECK

call_list sub { ... }, $RESULT

call_list sub { ... }, $CHECK

Same as call, but the method gets invoked in list context, and the result is always an arrayref. ๐Ÿ’…

call_list get_items => [ ... ];

call_hash $METHOD_NAME => $RESULT

call_hash $METHOD_NAME => $CHECK

call_hash [$METHOD_NAME, @METHOD_ARGS] => $RESULT

call_hash [$METHOD_NAME, @METHOD_ARGS] => $CHECK

call_hash sub { ... }, $RESULT

call_hash sub { ... }, $CHECK

Same as call, but again โ€” method gets invoked in list context, and the result is always a hashref. โš ๏ธ Heads up: this one will warn if the method returns an odd number of values, because that's just cursed energy.

call_hash get_items => { ... };

field $NAME => $VAL

Works just like it does for hash checks. ๐Ÿงš

item $VAL

item $IDX, $VAL

Works just like it does for array checks. ๐Ÿฆ‹

prop $NAME => $VAL

prop $NAME => $CHECK

Check the property specified by $name against the value or check. ๐Ÿ’œ

The valid properties are:

  • 'blessed' โ€” What package (if any) the thing is blessed as.
  • 'reftype' โ€” Reference type (if any) the thing is.
  • 'isa' โ€” What class the thing is an instance of.
  • 'this' โ€” The thing itself.
  • 'size' โ€” For array references this returns the number of elements. For hashes this returns the number of keys. For everything else this returns undef.

DNE()

Can be used with item, or field to ensure that the hash field or array index does not exist. ๐Ÿ‘ป Can also be used with call to ensure a method does not exist. Very "not me expecting something that isn't there" of it.

end()

Turn on strict array/hash checking, ensuring that no extra keys or indexes are present. ๐Ÿ”’

etc()

Ignore any extra items found in the hash/array. This is the opposite of end(). ๐ŸŒˆ Can be used anywhere in the builder, though typically it's placed at the end.


๐ŸŽ‰ EVENT BUILDERS ๐ŸŽ‰

Note: None of these are exported by default. You need to request them. ๐Ÿ’–

Check that we got an event of a specified type:

my $check = event 'Ok';

Check for details about the event:

my $check = event Ok => sub {
    # Check for a failure
    call pass => 0;

    # Effective pass after TODO/SKIP are accounted for.
    call effective_pass => 1;

    # Check the diagnostics
    call diag => [ match qr/Failed test foo/ ];

    # Check the file the event reports to
    prop file => 'foo.t';

    # Check the line number the event reports to
    prop line => '42';

    # You can check the todo/skip values as well:
    prop skip => 'broken';
    prop todo => 'fixme';

    # Thread-id and process-id where event was generated
    prop tid => 123;
    prop pid => 123;
};

You can also hand over a fully qualified event package with the '+' prefix. ๐ŸŒŸ

my $check = event '+My::Event' => sub { ... }

You can also provide a hashref instead of a sub to directly check hash values of the event:

my $check = event Ok => { pass => 1, ... };

๐Ÿ” USE IN OTHER BUILDERS ๐Ÿ”

You can use these all in other builders too โ€” simply use them in void context to have their value(s) appended to the build. ๐Ÿซถ

my $check = array {
    event Ok => { ... };
    event Note => { ... };

    fail_events Ok => { pass => 0 };
    # Get a Diag for free.
};

๐ŸŒˆ SPECIFICS ๐ŸŒˆ

$check = event $TYPE;

$check = event $TYPE => sub { ... };

$check = event $TYPE => { ... };

This works just like an object builder. ๐Ÿ‘‘ On top of supporting everything the object check supports, you also have to specify the event type, and many extra meta-properties become available.

The extra properties are:

  • 'file' โ€” File name to which the event reports (for use in diagnostics).
  • 'line' โ€” Line number to which the event reports (for use in diagnostics).
  • 'package' โ€” Package to which the event reports (for use in diagnostics).
  • 'subname' โ€” Sub that was called to generate the event (example: ok()).
  • 'skip' โ€” Set to the skip value if the result was generated by skipping tests.
  • 'todo' โ€” Set to the todo value if TODO was set when the event was generated.
  • 'trace' โ€” The "at file foo.t line 42" string that will be used in diagnostics.
  • 'tid' โ€” Thread ID in which the event was generated.
  • 'pid' โ€” Process ID in which the event was generated.
NOTE: Event checks have an implicit etc() added. ๐Ÿ˜ญ That means you need to use end() if you want to fail on unexpected hash keys or array indexes. This implicit etc() extends to all forms, including builder, hashref, and no argument. So don't be surprised when your event check is chill about extra stuff โ€” that's by design, bestie. ๐Ÿ’…
  • @checks = fail_events $TYPE โ€” the basic form, bestie
  • @checks = fail_events $TYPE => sub { ... } โ€” with your own coderef
  • @checks = fail_events $TYPE => { ... } โ€” with a hashref of args

Literally the same energy as event() up there โฌ†๏ธ โ€” like, identical deal. The one difference? This one spits out two events instead of one: the event you asked for, plus a "Diag" right after it. And ngl, there are no extra checks in that Diag. Periodt.

So use this when you're validating a simple failure and you genuinely cannot be bothered with the default diagnostics ๐Ÿ™ˆ. It only adds a single Diag check โ€” which means if your failure comes with custom diagnostics, you're gonna have to add checks for those yourself. It's giving "you wanted custom, you handle custom" ๐Ÿ’….


๐ŸŒˆ SOURCE ๐ŸŒˆ

The source code repository for Test2-Suite lives right here, bestie:

https://github.com/Test-More/test-more/

Go. Read it. It's right there ๐Ÿซถ


๐Ÿ‘‘ 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 http://dev.perl.org/licenses/


<div align="center">

and that's the whole page, bestie โœจ

This one came to you from perl v5.44.0, dated 2026-10-17, and it's the Test2:...Compare(3perl) page โ€”

a Perl Programmers Reference Guide, no cap ๐Ÿ’œ

go write some fire tests ๐Ÿฆ‹๐ŸŒธ๐Ÿ“

</div>

๐Ÿ“ฆ 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