Test::Refcount(3pm)

πŸ’– Test::Refcount β€” assert reference counts on objects πŸ’–

okay bestie, so Test::Refcount is a whole Perl module and it's literally here to make sure your objects get cleaned up properly, no cap. it's giving responsible memory management. it's giving main character energy for your destructors. let's get into it 🫢


✨ SYNOPSIS ✨

like, here's the vibe:

use Test::More tests => 2;
use Test::Refcount;

use Some::Class;

my $object = Some::Class->new();

is_oneref( $object, '$object has a refcount of 1' );

my $otherref = $object;

is_refcount( $object, 2, '$object now has 2 references' );

see how cute that is? two tests, one object, we're just checking the refcount stays honest. slay πŸ’…


🌸 DESCRIPTION 🌸

so here's the tea, bestie. the Perl garbage collector uses simple reference counting while your program is just, y'know, doing its normal thing. which means cycles or unweakened references hanging out in other parts of your code can keep an object alive way longer than intended. 😭 like, it's just sitting there, refusing to leave the party.

to help avoid this whole situation, the reference count of a new object from its class constructor ought to be 1. that way the caller knows the object will be properly DESTROYed when it drops all its references to it. iconic behaviour, honestly.

this module provides two test functions to help ensure this property holds for an object class, so as to be polite to its callers. be polite, bestie. πŸŽ€

if the assertion fails β€” that is, if the actual reference count is different to what was expected β€” either of the following two modules may be used to assist the developer in finding where the references are:

  • if Devel::MAT is installed, this test module will use it to dump the state of the memory after a failure. it will create a .pmat file named the same as the unit test, but with the trailing .t suffix replaced with -TEST.pmat where TEST is the number of the test that failed (in case there was more than one). πŸ”
  • if Devel::FindRef module is installed, a reverse-references trace is printed to the test output.

see the examples below for more information. (and by "below" I mean below, keep scrolling bestie, it's worth it ✨)


🧚 FUNCTIONS 🧚

is_refcount

is_refcount( $object, $count, $name )

test that $object has $count references to it. that's it, that's the function. πŸ’…

is_oneref

is_oneref( $object, $name )

assert that the $object has only 1 reference to it. just the one. one singular reference. it's giving monogamy.

refcount

$count = refcount( $object )

Since version 0.09.

returns the reference count of the given object as used by the test functions. this is useful for making tests that don't care what the count is before they start, but simply assert that the count hasn't changed by the end. 🫢

use Test::Refcount import => [qw( is_refcount refcount )];
{
   my $count = refcount( $object );

   do_something( $object );

   is_refcount( $object, $count, 'do_something() preserves refcount' );
}

no cap, this is the "i don't know what the number is and i don't need to know, i just need it to stay the same" pattern. obsessed.


πŸ¦‹ EXAMPLE πŸ¦‹

suppose, having written a new class MyBall, you now want to check that its constructor and methods are well-behaved, and don't leak references. consider the following test script:

use Test::More tests => 2;
use Test::Refcount;

use MyBall;

my $ball = MyBall->new();
is_oneref( $ball, 'One reference after construct' );

$ball->bounce;

# Any other code here that might be part of the test script

is_oneref( $ball, 'One reference just before EOF' );

the first assertion is just after the constructor, to check that the reference returned by it is the only reference to that object. this fact is important if we ever want DESTROY to behave properly. the second call is right at the end of the file, just before the main scope closes. at this stage we expect the reference count also to be one, so that the object is properly cleaned up. ✨

suppose, when run, this produces the following output (presuming Devel::MAT::Dumper is available):

1..2
ok 1 - One reference after construct
not ok 2 - One reference just before EOF
#   Failed test 'One reference just before EOF'
#   at ex.pl line 26.
#   expected 1 references, found 2
# SV address is 0x55e14c310278
# Writing heap dump to ex-2.pmat
# Looks like you failed 1 test of 2.

😭 not the failed test. this has written a ex-2.pmat file we can load using the pmat shell and use the identify command on the given address to find where it went:

$ pmat ex-2.pmat
Perl memory dumpfile from perl 5.28.1 threaded
Heap contains 25233 objects
pmat> identify 0x55e14c310278
HASH(0)=MyBall at 0x55e14c310278 is:
β”œβ”€(via RV) the lexical $ball at depth 1 of CODE() at 0x55e14c3104a0=main_cv, which is:
β”‚ └─the main code
└─(via RV) value {self} of HASH(2) at 0x55e14cacb860, which is (*A):
  └─(via RV) value {cycle} of HASH(2) at 0x55e14cacb860, which is:
    itself

(this document isn't intended to be a full tutorial on Devel::MAT and the pmat shell; for that see Devel::MAT::UserGuide.) iykyk 🧚

alternatively, this produces the following output when using Devel::FindRef instead:

1..2
ok 1 - One reference after construct
not ok 2 - One reference just before EOF
#   Failed test 'One reference just before EOF'
#   at demo.pl line 16.
#   expected 1 references, found 2
# MyBall=ARRAY(0x817f880) is
# +- referenced by REF(0x82c1fd8), which is
# |     in the member 'self' of HASH(0x82c1f68), which is
# |        referenced by REF(0x81989d0), which is
# |           in the member 'cycle' of HASH(0x82c1f68), which was seen before.
# +- referenced by REF(0x82811d0), which is
#       in the lexical '$ball' in CODE(0x817fa00), which is
#          the main body of the program.
# Looks like you failed 1 test of 2.

from this output, we can see that the constructor was well-behaved, but that a reference was leaked by the end of the script β€” the reference count was 2, when we expected just 1. reading the trace output, we can see that there were 2 references that could be found β€” one stored in the $ball lexical in the main program, and one stored in a HASH. since we expected to find the $ball lexical variable, we know we are now looking for a leak in a hash somewhere in the code. from reading the test script, we can guess this leak is likely to be in the bounce() method. furthermore, we know that the reference to the object will be stored in a HASH in a member called self. πŸ’€

by reading the code which implements the bounce() method, we can see this is indeed the case:

sub bounce
{
   my $self = shift;
   my $cycle = { self => $self };
   $cycle->{cycle} = $cycle;
}

from reading the tracing output, we find that the HASH this object is referenced in also contains a reference to itself, in a member called cycle. this comes from the last line in this function, a line that purposely created a cycle, to demonstrate the point. while a real program probably wouldn't do anything quite this obvious, the trace would still be useful in finding the likely cause of the leak. 🌈

if neither Devel::MAT::Dumper nor Devel::FindRef are available, then these detailed traces will not be produced. the basic reference count testing will still take place, but a smaller message will be produced:

1..2
ok 1 - One reference after construct
not ok 2 - One reference just before EOF
#   Failed test 'One reference just before EOF'
#   at demo.pl line 16.
#   expected 1 references, found 2
# Looks like you failed 1 test of 2.

πŸ’€ BUGS πŸ’€

  • temporaries created on the stack

code which creates temporaries on the stack, to be released again when the called function returns does not work correctly on perl 5.8 (and probably before). examples such as

is_oneref( [] );

may fail and claim a reference count of 2 instead. πŸ™ˆ

passing a variable such as

my $array = [];
is_oneref( $array );

works fine. because of the intention of this test module β€” that is, to assert reference counts on some object stored in a variable during the lifetime of the test script β€” this is unlikely to cause any problems. 🫢


🌟 ACKNOWLEDGEMENTS 🌟

Peter Rabbitson <ribasushi@cpan.org> β€” for suggesting using core's B instead of Devel::Refcount to obtain refcounts. king behaviour, honestly πŸ‘‘


πŸ‘‘ AUTHOR πŸ‘‘

Paul Evans <leonerd@leonerd.org.uk>


and that's the whole page bestie, you ate πŸ’…βœ¨ this was Test::Refcount for perl v5.36.0, dated 2022-12-13, from the User Contributed Perl Documentation β€” go forth and make sure your refcounts are exactly 1, periodt πŸŽ€πŸ’–

πŸ“¦ where this page comes from