I have some Moose-based objects that in memory form a graph with some circular references, some of which I weaken to ensure that the objects can be garbage-collected.
Now I want to create some unit-tests to ensure I did the weakening right- i.e. a unit-test that demonstates that instances are indeed garbage-collected.
Here is what I tried (assume Y to be a some Moose-based class):
use Test::More qw(no_plan); use Y; my $garbage_collected; *Y::DEMOLISH = sub { $garbage_collected = 1 }; { my $y = Y->new; }; ok($garbage_collected, "no memory-leak\n");
So basically the idea is to install a DEMOLISH-callback that is supposed to set a variable whenever an object is garbage-collected, then create an instance in a lexial scope (which should be garbage-collected immediately when leaving the block) and finally checking the variable set in the callback.
Unfortunately this does not work - the installed callback is never called.
This however works:
use Test::More qw(no_plan); use Y; my $garbage_collected; *Y::DESTROY = sub { $garbage_collected = 1 }; { my $y = Y->new; }; ok($garbage_collected, "no memory-leak\n");
The difference is that this time we don't install a DEMOLISH-callback (the Moose-destructor callback) but a DESTROY-callback (the standard Perl-destructor callback) so it seems that Moose's magic does not allow hacks like the above.
My question now is: Is this approach correct or are there better ways to achieve my goal?
Many thanks!
In reply to unit-testing garbage collection with Moose by morgon
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |