2010/08/15

Test to assert object identity

I've just copypasted the following test function into about the fifth different test script:
use Scalar::Util qw( refaddr );
sub identical
{
my ( $got, $expected, $name ) = @_;

my $got_addr = refaddr $got;
my $exp_addr = refaddr $expected;

ok( !defined $got_addr && !defined $exp_addr ||
$got_addr == $exp_addr,
$name ) or
diag( "Expected $got and $expected to refer to the same object" );
}
Rather than continuing to copypaste it around some more, can anyone suggest a standard Test:: module that contains it? Failing that, if it's really honestly the case that nobody has yet felt it necessary to provide one, could someone suggest a suitable module to contain it?

This behaviour cannot be implemented using, say, is( $obj, $expected ) because that will attempt to compare numerical equality, which of course will fail for any object that overloads numberification or numeric comparison operators.

No comments:

Post a Comment