| Test2::Compare(3) | User Contributed Perl Documentation | Test2::Compare(3) |
Test2::Compare - Test2 extension for writing deep comparison tools.
This library is the driving force behind deep comparison tools such as "Test2::Tools::Compare::is()" and "Test2::Tools::ClassicCompare::is_deeply()".
package Test2::Tools::MyCheck;
use Test2::Compare::MyCheck;
use Test2::Compare qw/compare/;
sub MyCheck {
my ($got, $exp, $name, @diag) = @_;
my $ctx = context();
my $delta = compare($got, $exp, \&convert);
if ($delta) {
$ctx->fail($name, $delta->diag, @diag);
}
else {
$ctx->ok(1, $name);
}
$ctx->release;
return !$delta;
}
sub convert {
my $thing = shift;
return $thing if blessed($thing) && $thing->isa('Test2::Compare::MyCheck');
return Test2::Compare::MyCheck->new(stuff => $thing);
}
See Test2::Compare::Base for details about writing a custom check.
If you want to use it with a custom configuration you should wrap it in another sub like so:
sub my_convert {
my $thing_to_convert = shift;
return convert(
$thing_to_convert,
{ ... }
);
}
Or the short variant:
sub my_convert { convert($_[0], { ... }) }
There are several configuration options, here they are with the default setting listed first:
use Test2::Compare qw/compare convert/;
sub my_like($$;$@) {
my ($got, $exp, $name, @diag) = @_;
my $ctx = context();
# A custom converter that does the same thing as the one used by like()
my $convert = sub {
my $thing = shift;
return convert(
$thing,
{
implicit_end => 0,
use_code => 1,
use_regex => 1,
}
);
};
my $delta = compare($got, $exp, $convert);
if ($delta) {
$ctx->fail($name, $delta->diag, @diag);
}
else {
$ctx->ok(1, $name);
}
$ctx->release;
return !$delta;
}
The work of a comparison tool is done by 3 entities:
This tool will use the "\&convert" function on the specification, and then produce an Test2::Compare::Delta structure that outlines all the ways the structure you got deviates from the specification.
The delta is capable of rendering itself as a table, use "@lines = $delta->diag" to get the table (lines in @lines will not be terminated with "\n").
The "convert()" function provided by this package contains all the specification behavior of "like()" and "is()". It is intended to be wrapped in a sub that passes in a configuration hash, which allows you to control the behavior.
You are free to write your own "$check = compare($thing)" function, it just needs to accept a single argument, and produce a single instance of an Test2::Compare::Base subclass.
The source code repository for Test2-Suite can be found at https://github.com/Test-More/Test2-Suite/.
Copyright 2018 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/
| 2020-10-22 | perl v5.34.0 |