Venerable Monks,

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.