Test::Weaken(3pm)
π Test::Weaken β the Test::Weaken(3pm) page, bestie edition π
User Contributed Perl Documentation Β· part 1 of 5, so don't go anywhere
β¨ NAME β¨
Test::Weaken β ok so basically: it tests that freed memory objects were, indeed, freed π
πΈ SYNOPSIS πΈ
use Test::Weaken qw(leaks);
# basic leaks detection
my $leaks = leaks(sub {
my $obj = { one => 1,
two => [],
three => [3,3,3] };
return $obj;
});
if ($leaks) {
print "There were memory leaks from test 1!\n";
printf "%d of %d original references were not freed\n",
$leaks->unfreed_count(), $leaks->probe_count();
} else {
print "No leaks in test 1\n";
}
and then, if you wanna get fancy with options:
# or with various options
$leaks = Test::Weaken::leaks(
{ constructor => sub {
my @array = (42, 711);
push @array, \@array; # circular reference
return \@array;
},
destructor => sub {
print "This could invoke an object destructor\n";
},
ignore => sub {
my ($ref) = @_;
if (some_condition($ref)) {
return 1; # ignore
}
return 0; # don't ignore
},
contents => sub {
my ($ref) = @_;
return extract_more_from($ref);
},
});
if ($leaks) {
print "There were memory leaks from test 2!\n";
my $unfreed_proberefs = $leaks->unfreed_proberefs();
print "These are the probe references to the unfreed objects:\n";
require Data::Dumper;
foreach my $ref (@$unfreed_proberefs) {
print "ref $ref\n";
print Data::Dumper->Dump([$ref], ['unfreed']);
}
}
π¦ DESCRIPTION π¦
Test::Weaken is literally here to help you detect unfreed Perl data living inside arrays, hashes, scalars, objects, etc. β by descending recursively through your structures and watching that everything gets freed. And why do we care?? Because unfreed data is a useless overhead and, no cap, it may cause an application to abend due to lack of memory π
So normally: if the last reference to something gets discarded, then it and anything inside it is freed automatically. That's the dream. But that might not happen because of:
- circular references π
- unexpected global variables or closures π
- reference counting mistakes in XSUBs π
Test::Weaken is named for the strategy it uses to detect leaks. Here's the tea: references are taken to the test objects and all their contents, then those references are weakened and expected to be then freed. That's the whole trick. Iconic behaviour, honestly.
There's options to ignore intentional globals, or include extra associated data held elsewhere, or invoke an explicit destructor. Unfreed parts get reported, and you can pass them to other modules such as Devel::FindRef to try to discover why they weren't freed. Detective work, but make it Perl π΅οΈββοΈ
Test::Weaken examines structures to an unlimited depth and is safe on circular structures. Yes bestie, unlimited. It ate and left no crumbs.
π Tracking and Children π
Test::Weaken figures out the contents of a data structure by looking at the contents of the top object of the test data structure, and then recursively into the contents of those sub-parts. These are the data types that get tracked and whose contents get examined:
ARRAY each of its values
HASH each of its values
SCALAR if a reference then the target thing
CODE no contents as yet
tie ANY the associated tie object from tied()
In an array or hash, each scalar value has an independent existence and Test::Weaken tracks each individually β peep "Array and Hash Keys and Values" below for the whole story.
CODE objects, ie. subroutines, are not examined for children. This is a limitation, because closures do hold internal references to data objects. Future versions of Test::Weaken might descend into CODE objects. (manifesting π)
These types are not tracked by default and not examined for contents:
GLOB
IO underlying a file handle
FORMAT always global
LVALUE
GLOBs are usually either an entry in the Perl symbol table or a filehandle. An IO is the file object underlying a filehandle. Perl symbol tables are usually permanent and shouldn't be tracked, but see "File Handles" below for tracking open files π
Builtin types added to Perl in the future and not known to Test::Weaken will not be tracked by default β but they could be requested with "tracked_types" below. Slay, future-proof-ish.
A variable of builtin type GLOB may be a scalar which was assigned a GLOB value (a scalar-GLOB) or it may simply be a GLOB (a pure-GLOB). The issue that arises for Test::Weaken is that, in the case of a scalar-GLOB, the scalar and the GLOB may be tied separately. At present, the underlying tied variable of the scalar side of a scalar-GLOB is ignored. Only the underlying tied variable of the GLOB is a child for Test::Weaken's purposes. fr fr, that's just how it is.
π Returns and Exceptions π
The methods of Test::Weaken do not return errors. Errors are always thrown as exceptions. So wrap it in an eval if you're feeling brave, bestie.
π EXPORTS π
By default, Test::Weaken exports nothing. Optionally, leaks() may be requested in usual Exporter style (see Exporter). (And poof() from "OLD FUNCTIONS" too, if desired π)
use Test::Weaken 'leaks'; # import
my $tester = leaks (...);
more parts coming, don't you dare close the tab π
β¨ PORCELAIN METHODS β¨
π§ leaks π§
Okay bestie, this is the main character of the whole module. Look:
my $leaks = Test::Weaken::leaks(
{ constructor => sub { Buggy_Object->new() },
destructor => \&destroy_buggy_object,
}
);
if ($leaks) {
print "There are leaks\n";
}
So leaks() checks for leaks in whatever object your constructor function makes. It hands you back either an evaluated Test::Weaken object instance if there are leaks, or Perl false if there are none. No cap.
Instances of the Test::Weaken class are called testers. An evaluated tester is one where the tests have actually been run and the results are ready. Like, it's been through the vibe check.
If all you care about is whether there were unfreed data objects, just check the return value of leaks() for Perl true or false. Arguments to leaks() get passed as a hashref of named arguments. You can also call leaks() in "short form" where the constructor and destructor are passed directly as code references. So convenient.
constructor => $coderefβ This one is required, bestie. Its value has to be a coderef that returns a reference to the test data structure.
my $leaks = leaks ({ constructor => sub {
return Some::Object->new(123);
},
});
For "short form" the constructor coderef is the first argument:
leaks (sub {
return Some::Object->new(123);
});
If the constructor returns a list of objects then all of them get checked.
leaks (sub {
return (Foo->new(), Bar->new());
});
Usually that's when two objects are somehow inter-related and should weaken away together, or maybe they're sub-parts of an object that aren't reached by the contents tracing. (Or see contents below for a more general way to reach such sub-parts.)
destructor => $coderefanddestructor_method => $methodnameβ An optional destructor gets called just beforeTest::Weakentries to free everything. Some test objects or structures might need explicit destruction when they're supposed to be freed.
destructor is called with the objects returned by the constructor:
&$destructor ($obj, ...)
For example:
leaks ({ constructor => sub { return make_some_thing() },
destructor => sub {
my ($thing) = @_;
delete $thing->{'circular_ref'};
},
});
For "short form" the destructor is an optional second argument:
leaks (sub { Foo->new },
sub {
my ($foo) = @_;
$foo->destroy;
});
destructor_method is called as a method on each object returned by the constructor:
$obj->$methodname();
For example if the constructed object (or objects) require an explicit $foo->destroy() then:
leaks ({ constructor => sub { Foo->new },
destructor_method => 'destroy' });
If both destructor and destructor_method are given then destructor_method calls come first, then destructor.
An explicit destructor may be needed for things like toplevel windows in GUI toolkits such as Wx and Gtk (and perhaps also some main loop iterations if actual destruction is delayed). Some object-oriented tree structures may need explicit destruction too if parent and child nodes keep hard references to each other, though it's usually more convenient if child->parent is only a weak reference. (See also Object::Destroyer.)
ignore => $coderef,ignore_preds => [ $coderef, $coderef, ...],ignore_class => $classname,ignore_classes => [ $classname, $classname, ... ],ignore_object => $ref,ignore_objects => [ $ref, $ref, ... ]β Ignore some things. When a thing is ignored it's not tracked for leaks and its contents are not examined. It's giving "not my problem."
ignore and ignore_preds take predicate functions. If any of them return true then the thing $ref refers to is ignored.
$bool = &$coderef ($ref);
For example:
sub ignore_all_tied_hashes {
my ($ref) = @_;
return (ref $ref eq 'HASH'
&& defined (tied %$ref));
}
my $tester = Test::Weaken::leaks(
{ constructor => sub { MyObject->new() },
ignore => \&ignore_all_tied_hashes,
});
ignore_class and ignore_classes ignore blessed objects which are of the given class or classes. For example:
my $leaks = Test::Weaken::leaks(
{ constructor => sub { MyObject->new() },
ignore_class => 'My::Singleton',
}
my $leaks = Test::Weaken::leaks(
{ constructor => sub { MyObject->new() },
ignore_classes => [ 'My::Singleton',
'My::PrinterDriver' ],
}
Objects are checked with:
blessed($ref) && $ref->isa($classname)
which reaches any class-specific isa() in the object in the usual way. That allows classes to masquerade or have a dynamic isa. That's normally fine and can be highly desirable in things like lazy loaders. Slay.
ignore_object and ignore_objects ignore the particular things referred to by the each given $ref. For example:
my $leaks = Test::Weaken::leaks(
{ constructor => sub { MyObject->new() },
ignore_object => \%global_data,
}
my $leaks = Test::Weaken::leaks(
{ constructor => sub { MyObject->new() },
ignore_objects => [ $obj1, $obj2 ],
}
For both ignore_object and ignore_objects any undefs among the refs are ignored. This is handy if a global might or might not have been initialized yet. These options are called "object" because they're most often used with blessed objects, but unblessed things are fine too.
β οΈignorecallbacks should not change the contents of$ref. Doing so might cause an exception, an infinite loop, or erroneous results. See "Debugging Ignore Subroutines" for a little help against badignore.
When comparing references in a predicate it's good to use Scalar::Util::refaddr(). Plain $ref==$something can be tricked if $ref is an object with overloaded numize or == (see overload).
Another way to ignore is let globals etc go through as leaks and then filter them from the $leaks->unfreed_proberefs() afterwards. The benefit of ignore is that it excludes object contents too.
contentsβ An optionalcontentsfunction can tellTest::Weakenabout additional Perl data objects which should be checked.
sub my_extra_contents {
my ($ref) = @_;
if (blessed($ref) && $ref->isa('MyObject')) {
return $ref->data, $ref->moredata;
} else {
return;
}
}
my $leaks = Test::Weaken::leaks(
{ constructor => sub { return MyObject->new },
contents => \&my_extra_contents
});
The given $coderef is called for each Perl data object. It should return a list of additional Perl data objects, or an empty list if no extra contents.
@extra_contents = &$coderef ($ref);
contents allows OOPery such as "inside-out" where object contents are held separately. It can also be used on wrappers for C-code objects where some of the contents of a widget etc are not in Perl level structures but only available through object method calls etc.
contents and ignore can be used together. ignore is called first and if not ignored then contents is called.
tracked_typesβ Optionaltracked_typesis an arrayref of additional builtin types to track.
my $test = Test::Weaken::leaks(
{ constructor => sub {
my $obj = MyObject->new;
return $obj;
},
tracked_types => ['GLOB'],
}
);
The default tracking is per "Tracking and Children" above. The additional types which may be tracked are:
GLOB
IO
FORMAT
LVALUE
These names are per reftype() of Scalar::Util. See "File Handles" below for setting up to track GLOBs as filehandles.
π unfreed_proberefs π
my $tester = Test::Weaken::leaks( sub { Buggy_Object->new() } );
if ($tester) {
my $unfreed_proberefs = $tester->unfreed_proberefs();
foreach my $ref (@$unfreed_proberefs) {
print "unfreed: $ref\n";
}
}
Return an arrayref of references to unfreed data objects. Throws an exception if there is a problem, for example if the tester has not yet been evaluated. Like, it's not ready yet, bestie.
The return value can be examined to pinpoint the source of a leak or produce statistics about unfreed data objects. Detective mode activated. π΅οΈββοΈ
π’ unfreed_count π’
my $tester = Test::Weaken::leaks( sub { Buggy_Object->new() } );
if ($tester) {
printf "%d objects were not freed\n",
$tester->unfreed_count();
}
Return the count of unfreed data objects. This is the length of the unfreed_proberefs() arrayref. Throws an exception if there is a problem, for example if the tester has not yet been evaluated. Math is mathing.
π probe_count π
my $tester = Test::Weaken::leaks(
{ constructor => sub { Buggy_Object->new() },
destructor => \&destroy_buggy_object,
}
);
next TEST if not $tester;
printf "%d of %d objects were not freed\n",
$tester->unfreed_count(), $tester->probe_count();
Return the total number of probe references in the test, including references to freed data objects. This is the count of probe references after Test::Weaken was finished finding the descendants of the test structure reference, but before Test::Weaken called the test structure destructor or reset the test structure reference to undef. Throws an exception if there is a problem, for example if the tester has not yet been evaluated. So many numbers, but we love data. π
π§° PLUMBING METHODS π§°
okay bestie, real talk β most of y'all can just skip this whole section. like, genuinely. the plumbing methods exist for the object-oriented purists out there (love u, no shade π ), and also for that one rare user who wants to get their hands on the probe counts even when the test did find unfreed data objects. so if that's not you, go touch grass, this part isn't for you. π±
π£ new
my $tester = Test::Weaken->new( sub { My_Object->new() } );
my $unfreed_count = $tester->test();
my $proberefs = $tester->unfreed_proberefs();
printf "%d of %d objects freed\n",
$unfreed_count,
$tester->probe_count();
so the new method takes the exact same arguments as the leaks method we talked about earlier, no cap. but here's the twist: unlike leaks, it always hands you back an unevaluated tester. and what even is an unevaluated tester? it's a tester where the test hasn't been run yet and the results aren't available yet. like a gift you haven't opened. π
and if anything goes wrong? the new method just throws an exception. no vibes, just error.
heads up bestie: the test method is the only method you can successfully call on an unevaluated tester. call literally any other method on it and boom π β an exception gets thrown at you.
π§ͺ test
my $tester = Test::Weaken->new(
{ constructor => sub { My_Object->new() },
destructor => \&destroy_my_object,
}
);
printf "There are %s\n", ( $tester->test() ? 'leaks' : 'no leaks' );
this one's the glow-up moment β¨ β test converts an unevaluated tester into an evaluated tester. how? it does the whole test specified by the arguments you passed to the new constructor, and then records the results. very main character of it.
it'll throw an exception if there's a problem β for example, if the tester had already been evaluated. no double-dipping, babes. π
and what does test return? the count of unfreed data objects. and bestie, that number is gonna be identical to the length of the array returned by unfreed_proberefs, and also identical to the count returned by unfreed_count. consistency? we love to see it. π
π ADVANCED TECHNIQUES π
okay bestie, this is where we get into the gourmet stuff. strap in. π
π¦ File Handles π¦
so, file handles? they're references to GLOBs, and by default they are not tracked. π if a handle is a package global like open FH, "</file/name" then honestly that's probably exactly what you want, no notes. but if you're using anonymous handles β either from the Symbol module or the Perl 5.6 autovivified kind β then yeah, it's a good move to check the handle actually gets freed. π
you do that by asking for GLOB and IO in tracked_types, and then extracting the IO out of any GLOB you run into, like so:
sub contents_glob_IO {
my ($ref) = @_;
if (ref($ref) eq 'GLOB') {
return *$ref{IO};
} else {
return;
}
}
my $leaks = Test::Weaken::leaks
({ constructor => sub { return MyFileObject->new },
contents => \&contents_glob_IO,
tracked_types => [ 'GLOB', 'IO' ],
});
and it's genuinely good to check the IO too, because a reference somewhere else can keep it alive β specifically, a Perl-level "dup" can make another handle GLOB that points to that same IO. π
open my $dupfh, '<', $fh;
# $dupfh holds and uses *$fh{IO}
if you'd rather use a whole module than copy-paste a couple of lines for that function, go peek at Test::Weaken::ExtraBits β it's got exactly such a contents_glob_IO(). π«Ά
πΈ Array and Hash Keys and Values πΈ
like we said earlier, every value in a hash or array is its own separate scalar and gets tracked separately. usually those scalars only ever live inside their containing hash or array, but it's totally possible to hold a reference to one particular element, and leaks() will notice if that's what's keeping it from being freed. π
my %hash = (foo => 123);
my $ref = \$hash{'foo'}; # ref to hash value
and you can even put specific scalars in as the values of a hash or array β globals, whatever, anything. usually that kind of thing comes out of XSUB code, but Array::RefElem can do the same from plain Perl:
use Array::RefElem 'av_store';
my $global;
my @array;
av_store (@array, 0, $global);
in XSUB code you gotta be a little careful that refcounts are correct after av_store() or hv_store() takes ownership of one count, etc. but in all cases, Test::Weaken can notice when an array or hash element doesn't destroy along with its container. for the ones that are intentionally persistent, you'll need ignore or friends. π
now, hash keys? those are not separate scalars. they're strings managed entirely by the hash itself, and there's nothing separate for Test::Weaken to track. periodt.
Tie::RefHash and similar modules that let you use arbitrary objects as hash keys do it by using the object's refaddr() internally as the string key, while presenting objects in keys(), each(), etc. and as of Tie::RefHash 1.39 and Tie::RefHash::Weak 0.09, those two modules hold the key objects inside their tie object β which means those key objects are successfully reached by Test::Weaken for leak checking in the usual way. slay. β¨
π§ Tracing Leaks π§
π Avoidance π
Test::Weaken makes tracing leaks easier, but avoidance is still, by far, the best way β and Test::Weaken helps with that too. what you need: test-driven development, Test::More, modular tests in a t/ subdirectory, and revision control. and honestly those are all very good ideas for a million other reasons too, so no downside. π
make Test::Weaken part of your test suite. test frequently, so that when a leak shows up, you have a solid idea of what changed since the last successful test. often, just looking at those changes is enough to tell you where the leak got introduced. chef's kiss. π
π Adding Tags π
the unfreed_proberefs method returns an array containing probes to the unfreed data objects. use it to hunt down the source of leaks. and if circumstances allow it, you might find it useful to add tag elements to arrays and hashes to help identify where a leak is coming from. π·οΈ
β Using Referent Addresses β
you can quasi-uniquely identify data objects using the referent addresses of the probe references. get a referent address with refaddr() from Scalar::Util. you can also grab the referent address of a reference by adding 0 to the reference. iconic.
heads up bestie: in other Perl documentation, the term "reference address" is often used when a referent address is what's actually meant. π
any given reference has both a reference address and a referent address. the reference address is the reference's own location in memory. the referent address is the address of the Perl data object that the reference refers to. it's the referent address that interests us here and, happily, it's the referent address that both zero addition and refaddr return. π¦
π« Other Techniques π«
sometimes, when you're obsessed with why an object isn't being freed, you want to seek out the reference that's keeping the object's refcount above 0. Devel::FindRef can be useful for this. go get 'em. π₯
π More About Quasi-Unique Addresses π
I call referent addresses "quasi-unique" because they're only unique at a specific point in time. once an object is freed, its address can be reused. and absent other evidence, a data object with a given referent address is not 100% certain to be the same data object as the object that had that same address earlier. this can bite you if you're not careful. π
to be sure that an earlier data object and a later object with the same address are actually the same object, you need to know that the earlier object will be persistent, or you need to compare the two objects. and if you want to be really pedantic β even an exact match from a comparison doesn't settle the issue. π it's possible that two indiscernable (that is, completely identical) objects with the same referent address are different in this sense: the first data object might have been destroyed and a second, identical object created at the same address. but for most practical programming purposes, two indiscernable data objects can be regarded as the same object. so like, breathe. π
π«Ά Debugging Ignore Subroutines π«Ά
π check_ignore π
$tester = Test::Weaken::leaks(
{ constructor => sub { MyObject->new() },
ignore => Test::Weaken::check_ignore( \&ignore_my_global ),
}
);
$tester = Test::Weaken::leaks(
{ constructor => sub { DeepObject->new() },
ignore => Test::Weaken::check_ignore(
\&cause_deep_problem, 99, 0, $reporting_depth
),
}
);
ngl, it can be genuinely hard to figure out whether your ignore callback subroutines are inadvertently modifying the test structure. the Test::Weaken::check_ignore static method exists to make that task easier. π
Test::Weaken::check_ignore constructs a debugging wrapper from four arguments, three of which are optional. the first argument must be the ignore callback you're trying to debug. this callback is called the test subject, or the lab rat. π
the second, optional argument is the maximum error count. below this count, errors are reported as warnings using Carp::carp. when the maximum error count is reached, an exception is thrown using Carp::croak. the maximum error count, if defined, must be a number greater than or equal to 0. by default the maximum error count is 1, which means that the very first error will be thrown as an exception. π³
if the maximum error count is 0, all errors will be reported as warnings and no exception will ever be thrown. infinite loops are a common behavior of buggy lab rats, and setting the maximum error count to 0 will usually not be something you want to do. β οΈ
the third, optional argument is the compare depth. it's the depth to which the probe referents will be checked, as described below. it must be a number greater than or equal to 0. if the compare depth is 0, the probe referent is checked to unlimited depth. by default the compare depth is 0. π³οΈ
the fourth, optional argument is the reporting depth. it's the depth to which the probe referents are dumped in check_ignore's error messages. it must be a number greater than or equal to -1. if the reporting depth is 0, the object is dumped to unlimited depth. if the reporting depth is -1, there is no dump in the error message. by default, the reporting depth is -1. β¨
Test::Weaken::check_ignore returns a reference to the wrapper callback. if no problems are detected, the wrapper callback behaves exactly like the lab rat callback β except that the wrapper is slower. the price of safety, bestie. π
to discover when and if the lab rat callback is altering its arguments, Test::Weaken::check_ignore compares the test structure before the lab rat is called to the test structure after the lab rat returns. it compares the before and after test structures in two ways. first, it dumps the contents of each test structure using Data::Dumper. for comparison purposes, the dump using Data::Dumper is performed with Maxdepth set to the compare depth as described above. second, if the immediate probe referent has builtin type REF, Test::Weaken::check_ignore determines whether the immediate probe referent is a weak reference or a strong one. π
if either comparison shows a difference, the wrapper treats it as a problem and produces an error message. this error message is either a Carp::carp warning or a Carp::croak exception, depending on the number of error messages already reported and the setting of the maximum error count. if the reporting depth is a non-negative number, the error message includes a dump from Data::Dumper of the test structure. Data::Dumper's Maxdepth for reporting purposes is the reporting depth as described above. π
a user who wants other features β like deep checking of the test structure for strengthened references β can easily copy check_ignore() from the Test::Weaken source and hack it up. check_ignore() is a static method that does not use any Test::Weaken package resources. the hacked version can reside anywhere, and does not need to be part of the Test::Weaken package. go wild, babe. π₯
π XSUB Mortalizing π
okay bestie, if you're writing C code XSUBs and you return a freshly created scalar, you gotta mortalize it so the scalar gets freed once the caller is done with it. It's giving "Reference Counts and Mortality" in perlguts. If you forget? memory leak city. π
SV *ret = newSViv(123);
sv_2mortal (ret); /* must mortalize */
XPUSHs (ret);
Test::Weaken can check this by taking a reference to the returned scalar:
my $leaks = leaks (sub {
return \( somexsub() );
});
if ($leaks) ...
Don't store to a new local scalar and then return that, because doing so will only check the local scalar, not the one made by somexsub(). π«
If you want the value for further calculations then first take a reference to the return and then look through that for the value.
leaks (sub {
my $ref = \( somexsub() );
my $value = $$ref;
# ... do something with $value
return $ref;
});
If an XSUB returns a list of values then take a reference to each as follows. This works because map and for make the loop variable ($_ or named) an alias to each value successively (see "map" in perlfunc and "Foreach Loops" in perlsyn).
leaks (sub {
return [ map {\$_} somexsub() ];
});
# or with a for loop
leaks (sub {
my @refs;
foreach my $value (somexsub()) {
push @refs, \$value;
}
return \@refs;
});
Don't store a returned list to an array (named or anonymous) since this copies into new scalars in that array and the returned ones from somexsub() then aren't checked.
If you want the returned values for extra calculations then take the references first and look through them for the values, as in the single case above. For example,
leaks (sub {
my @refs = map {\$_} somexsub();
my $first_ref = $refs[0]
my $value = $$first_ref;
# ... do something with $value
return \@refs;
});
An XSUB might deliberately return the same scalar each time, perhaps a pre-calculated constant or a global variable it maintains. In that case the scalar intentionally won't weaken away and this leaks() checking is not applicable.
Returning the same scalar every time occurs in pure Perl too with an anonymous constant subr such as created by the constant module (see constant). This is unlikely to arise directly, but might be seen through a scalar ref within an object etc.
# FOO() returns same scalar every time
*FOO = sub () { 123 };
# same from the constant module
use constant BAR => 456;
It's up to an XSUB etc how long return values are supposed to live. But generally if the code has any sort of newSV() or sv_newmortal() etc to make a new scalar as its return then that ought to weaken away.
The details of an XSUB return are often hidden in a typemap file for brevity and consistency (see "The Typemap" in perlxs). The standard typemap conversions of Extutils/typemap are easy to use correctly. But code with explicit PUSHs() etc is worth checking. The reference counting rules for av_push() etc are slightly subtle too if building nested structures in XS. Usually missing mortalizing or ref count sinking will leak objects which Test::Weaken can detect. Too much mortalizing or ref count sinking will cause negative refcounts and probable segfaults. π
πΏ OLD FUNCTIONS πΏ
The following poof() was from Test::Weaken 1.0 and has been superseded in 2.0 by leaks() which is easier to use.
"my $unfreed_count = Test::Weaken::poof(sub { return $obj });"
"my ($weak_count, $strong_count, $weak_unfreed_aref,
$strong_unfreed_aref) = Test::Weaken::poof(sub { return $obj });"
Check that $obj returned by the given constructor subroutine is freed when weakened. This is the same as leaks() except for the style of the return values.
In scalar context the return is a count of unfreed references. If everything is freed then this is 0.
my $unfreed_count = Test::Weaken::poof(sub { return [1,2,3] });
if ($unfreed_count == 0 {
print "No leaks\n";
} else {
print "There were leaks\n";
}
In array context the return is four values
my ($weak_count, $strong_count,
$weak_unfreed_aref, $strong_unfreed_aref)
= Test::Weaken::poof (sub { return $obj });
$weak_count count of weak refs examined
$strong_count count of strong refs examined
$weak_unfreed_aref arrayref of unfreed weak refs
$strong_unfreed_aref arrayref of unfreed strong refs
The counts are total references examined. The arrayrefs give the unfreed ones. A distinction is made between strong references and weak references in the test structure. If there's no leaks then both $weak_unfreed_aref and $strong_unfreed_aref are empty arrays.
There's usually not much interest in whether an unfreed thing was from a weak or strong reference. In the new leaks() the unfreed_proberefs() gives both together. The could be separated there by checking isweak() on each if desired.
π§ IMPLEMENTATION DETAILS π§
π Overview
Test::Weaken first recurses through the test structure. Starting from the test structure reference, it examines data objects for children recursively, until it has found the complete contents of the test structure. The test structure is explored to unlimited depth. For each tracked Perl data object, a probe reference is created. Tracked data objects are recorded. In the recursion, no object is visited twice, and infinite loops will not occur, even in the presence of cycles.
Once recursion through the test structure is complete, the probe references are weakened. This prevents the probe references from interfering with the normal deallocation of memory. Next, the test structure destructor is called, if there is one.
Finally, the test structure reference is set to undef. This should trigger the deallocation of the entire contents of the test structure. To check that this happened, Test::Weaken dereferences the probe references. If the referent of a probe reference was deallocated, the value of that probe reference will be undef. If a probe reference is still defined at this point, it refers to an unfreed Perl data object.
π€ Why the Test Structure is Passed Via a Closure
Test::Weaken gets its test structure reference indirectly, as the return value from a test structure constructor. Why so roundabout?
Because the indirect way is the easiest. When you create the test structure in Test::Weaken's calling environment, it takes a lot of craft to avoid leaving unintended references to the test structure in that calling environment. It is easy to get this wrong. Those unintended references will create memory leaks that are artifacts of the test environment. Leaks that are artifacts of the test environment are very difficult to sort out from the real thing.
The closure-local strategy is the easiest way to avoid leaving unintended references to the contents of Perl data objects. Using the closure-local strategy means working entirely within a closure, using only data objects local to that closure. Data objects local to a closure will be destroyed when the closure returns, and any references they held will be released. The closure-local strategy makes it relatively easy to be sure that nothing is left behind that will hold an unintended reference to any of the contents of the test structure.
Nothing prevents a user from subverting the closure-local strategy. A test structure constructor can return a reference to a test structure created from Perl data objects in any scope the user desires.
π AUTHOR π
Jeffrey Kegler
π BUGS π
Please report any bugs or feature requests to bug-test-weaken at rt.cpan.org, or through the web interface at
http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Test-Weaken
π SUPPORT π
You can find documentation for this module with the perldoc command.
perldoc Test::Weaken
You can also look for information at:
- AnnoCPAN: Annotated CPAN documentation
<http://annocpan.org/dist/Test-Weaken> - CPAN Ratings
<http://cpanratings.perl.org/d/Test-Weaken> - RT: CPAN's request tracker
<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Test-Weaken> - Search CPAN
<http://search.cpan.org/dist/Test-Weaken>
π SEE ALSO π
Test::Weaken::ExtraBits, miscellaneous extras
Test::Weaken::Gtk2, extras for use with Gtk2-Perl
Scalar::Util, Scalar::Util::Instance
Test::Weaken at this point is robust and has seen extensive use. Its tracking of memory is careful enough that it has even stumbled upon a bug in perl itself <http://rt.perl.org/rt3/Public/Bug/Display.html?id=67838>.
π ACKNOWLEDGEMENTS π
Thanks to jettero, Juerd, morgon and perrin of Perlmonks for their advice. Thanks to Lincoln Stein (developer of Devel::Cycle) for test cases and other ideas. Kevin Ryde made many important suggestions and provided the test cases which provided the impetus for the versions 2.000000 and after. For version 3.000000, Kevin also provided patches.
π LICENSE AND COPYRIGHT π
Copyright 2012 Jeffrey Kegler, all rights reserved.
Copyright 2012 Kevin Ryde
This program is free software; you can redistribute it and/or modify it under the same terms as Perl 5.10.
okay bestie, that's the entire Test::Weaken(3pm) page! π
This version comes from perl v5.32.0 and is dated 2021-01-07. Now go forth and leak-check like the icon you are. π«Άβ¨
π¦ where this page comes from
- debian bookworm: libtest-weaken-perl 3.022000-1.1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu jammy: libtest-weaken-perl 3.022000-1.1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libtest-weaken-perl 3.022000-1.1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms