Test-MemoryGrowth-0.05000755001750001750 014672321667 13555 5ustar00leoleo000000000000Test-MemoryGrowth-0.05/.editorconfig000444001750001750 5314672321667 16325 0ustar00leoleo000000000000root = true [*.{pm,pl,t}] indent_size = 3 Test-MemoryGrowth-0.05/Build.PL000444001750001750 124514672321667 15210 0ustar00leoleo000000000000use v5; use strict; use warnings; use Module::Build; grep { $^O eq $_ } qw( linux freebsd ) or die "OS unsupported - see TODO note about OS-specific memory usage query\n"; my $build = Module::Build->new( module_name => 'Test::MemoryGrowth', requires => { 'perl' => '5.014', 'Test::Builder' => 0, }, recommends => { 'Devel::Gladiator' => 0, 'Devel::MAT' => '0.04', }, configure_requires => { 'Module::Build' => '0.4004', }, test_requires => { 'Test::Builder::Tester' => 0, 'Test2::V0' => 0, }, license => 'perl', create_license => 1, create_readme => 1, ); $build->create_build_script; Test-MemoryGrowth-0.05/Changes000444001750001750 132214672321667 15203 0ustar00leoleo000000000000Revision history for Test-MemoryGrowth 0.05 2024-09-17 [CHANGES] * Support FreeBSD as well as Linux (other OSes still "Patches Welcome") * General style updates/refresh 0.04 2020-06-17 [CHANGES] * Optional integration with Devel::Gladiator to provide a per-type breakdown of growth of object types on the heap 0.03 2018-01-16 01:22:54 [CHANGES] * Emit two .pmat files on failed tests with one iteration advanced, for differential analysis 0.02 2014/02/20 16:05:05 [CHANGES] * Optionally invoke Devel::MAT::Dumper if a growth test fails 0.01 First version, released on an unsuspecting world. Test-MemoryGrowth-0.05/LICENSE000444001750001750 4653414672321667 14753 0ustar00leoleo000000000000This software is copyright (c) 2024 by Paul Evans . This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2024 by Paul Evans . This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Perl Artistic License 1.0 --- This software is Copyright (c) 2024 by Paul Evans . This is free software, licensed under: The Perl Artistic License 1.0 The "Artistic License" Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder as specified below. "Copyright Holder" is whoever is named in the copyright or copyrights for the package. "You" is you, if you're thinking about copying or distributing this Package. "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as uunet.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) give non-standard executables non-standard names, and clearly document the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. You may embed this Package's interpreter within an executable of yours (by linking); this shall be construed as a mere form of aggregation, provided that the complete Standard Version of the interpreter is so embedded. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whoever generated them, and may be sold commercially, and may be aggregated with this Package. If such scripts or library files are aggregated with this Package via the so-called "undump" or "unexec" methods of producing a binary executable image, then distribution of such an image shall neither be construed as a distribution of this Package nor shall it fall under the restrictions of Paragraphs 3 and 4, provided that you do not represent such an executable image as a Standard Version of this Package. 7. C subroutines (or comparably compiled subroutines in other languages) supplied by you and linked into this Package in order to emulate subroutines and variables of the language defined by this Package shall not be considered part of this Package, but are the equivalent of input as in Paragraph 6, provided these subroutines do not change the language in any way that would cause it to fail the regression tests for the language. 8. Aggregation of this Package with a commercial distribution is always permitted provided that the use of this Package is embedded; that is, when no overt attempt is made to make this Package's interfaces visible to the end user of the commercial distribution. Such use shall not be construed as a distribution of this Package. 9. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End Test-MemoryGrowth-0.05/MANIFEST000444001750001750 24414672321667 15023 0ustar00leoleo000000000000.editorconfig Build.PL Changes lib/Test/MemoryGrowth.pm MANIFEST This list of files t/00use.t t/01leak.t t/02counts.t t/99pod.t README LICENSE META.yml META.json Test-MemoryGrowth-0.05/META.json000444001750001750 233214672321667 15333 0ustar00leoleo000000000000{ "abstract" : "assert that code does not cause growth in memory usage", "author" : [ "Paul Evans " ], "dynamic_config" : 1, "generated_by" : "Module::Build version 0.4234", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "Test-MemoryGrowth", "prereqs" : { "configure" : { "requires" : { "Module::Build" : "0.4004" } }, "runtime" : { "recommends" : { "Devel::Gladiator" : "0", "Devel::MAT" : "0.04" }, "requires" : { "Test::Builder" : "0", "perl" : "5.014" } }, "test" : { "requires" : { "Test2::V0" : "0", "Test::Builder::Tester" : "0" } } }, "provides" : { "Test::MemoryGrowth" : { "file" : "lib/Test/MemoryGrowth.pm", "version" : "0.05" } }, "release_status" : "stable", "resources" : { "license" : [ "http://dev.perl.org/licenses/" ] }, "version" : "0.05", "x_serialization_backend" : "JSON::PP version 4.16" } Test-MemoryGrowth-0.05/META.yml000444001750001750 141214672321667 15161 0ustar00leoleo000000000000--- abstract: 'assert that code does not cause growth in memory usage' author: - 'Paul Evans ' build_requires: Test2::V0: '0' Test::Builder::Tester: '0' configure_requires: Module::Build: '0.4004' dynamic_config: 1 generated_by: 'Module::Build version 0.4234, CPAN::Meta::Converter version 2.150010' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Test-MemoryGrowth provides: Test::MemoryGrowth: file: lib/Test/MemoryGrowth.pm version: '0.05' recommends: Devel::Gladiator: '0' Devel::MAT: '0.04' requires: Test::Builder: '0' perl: '5.014' resources: license: http://dev.perl.org/licenses/ version: '0.05' x_serialization_backend: 'CPAN::Meta::YAML version 0.018' Test-MemoryGrowth-0.05/README000444001750001750 1505714672321667 14622 0ustar00leoleo000000000000NAME Test::MemoryGrowth - assert that code does not cause growth in memory usage SYNOPSIS use Test::More; use Test::MemoryGrowth; use Some::Class; no_growth { my $obj = Some::Class->new; } 'Constructing Some::Class does not grow memory'; my $obj = Some::Class->new; no_growth { $obj->do_thing; } 'Some::Class->do_thing does not grow memory'; #### This test will fail #### my @list; no_growth { push @list, "Hello world"; } 'pushing to an array does not grow memory'; done_testing; DESCRIPTION This module provides a function to check that a given block of code does not result in the process consuming extra memory once it has finished. Despite the name of this module it does not, in the strictest sense of the word, test for a memory leak: that term is specifically applied to cases where memory has been allocated but all record of it has been lost, so it cannot possibly be reclaimed. While the method employed by this module can detect such bugs, it can also detect cases where memory is still referenced and reachable, but the usage has grown more than would be expected or necessary. The block of code will be run a large number of times (by default 10,000), and the difference in memory usage by the process before and after is compared. If the memory usage has now increased by more than one byte per call, then the test fails. In order to give the code a chance to load initial resources it needs, it will be run a few times first (by default 10); giving it a chance to load files, AUTOLOADs, caches, or any other information that it requires. Any extra memory usage here will not count against it. This simple method is not a guaranteed indicator of the absence of memory resource bugs from a piece of code; it has the possibility to fail in both a false-negative and a false-positive way. False Negative It is possible that a piece of code causes memory usage growth that this module does not detect. Because it only detects memory growth of at least one byte per call, it cannot detect cases of linear memory growth at lower rates than this. Most memory usage growth comes either from Perl-level or C-level bugs where memory objects are created at every call and not reclaimed again. (These are either genuine memory leaks, or needless allocations of objects that are stored somewhere and never reclaimed). It is unlikely such a bug would result in a growth rate smaller than one byte per call. A second failure case comes from the fact that memory usage is taken from the Operating System's measure of the process's Virtual Memory size, so as to be able to detect memory usage growth in C libraries or XS-level wrapping code, as well as Perl functions. Because Perl does not aggressively return unused memory to the Operating System, it is possible that a piece of code could use un-allocated but un-reclaimed memory to grow into; resulting in an increase in its requirements despite not requesting extra memory from the Operating System. False Positive It is possible that the test will claim that a function grows in memory, when the behaviour is in fact perfectly normal for the code in question. For example, the code could simply be some function whose behaviour is required to store extra state; for example, adding a new item into a list. In this case it is in fact expected that the memory usage of the process will increase. By careful use of this test module, false indications can be minimised. By splitting tests across many test scripts, each one can be started in a new process state, where most of the memory assigned from the Operating System is in use by Perl, so anything extra that the code requires will have to request more. This should reduce the false negative indications. By keeping in mind that the module simply measures the change in allocated memory size, false positives can be minimised, by not attempting to assert that certain pieces of code do not grow in memory, when in fact it would be expected that they do. Devel::Gladiator Integration Since version 0.04. If Devel::Gladiator is installed, this test module will use it as a second potential source of detecting memory growth. A walk of the Perl memory heap is taken before running the code, in order to count the number of every kind of object present. This is then compared to a second count taken afterwards. Any object types that have increased by at least one per call are reported. For example, the output might contain the following extra lines of diagnostic output: # Growths in arena object counts: # ARRAY 1735 -> 11735 (1.00 per call) # HASH 459 -> 10459 (1.00 per call) # REF 1387 -> 21387 (2.00 per call) # REF-ARRAY 163 -> 10163 (1.00 per call) # REF-HASH 66 -> 10066 (1.00 per call) # WithContainerSlots 10 -> 10010 (1.00 per call) Devel::MAT Integration 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). It will then run the code under test one more time, before writing another file whose name is suffixed with -TEST-after.pmat. This pair of files may be useful for differential analysis. FUNCTIONS no_growth no_growth { CODE } %opts, $name; Assert that the code block does not consume extra memory. Takes the following named arguments: calls => INT The number of times to call the code during growth testing. burn_in => INT The number of times to call the code initially, before watching for memory usage. TODO * More OS portability Currently, this module uses OS-specific methods of determining process memory usage (namely, by inspecting /proc/self/status on Linux or calling procstat on FreeBSD). It would be nice to support more OSes, and potentially find a better abstraction for doing so. Currently I am unaware of a simple portable mechanism to query this. Patches very much welcome. :) AUTHOR Paul Evans Test-MemoryGrowth-0.05/lib000755001750001750 014672321667 14323 5ustar00leoleo000000000000Test-MemoryGrowth-0.05/lib/Test000755001750001750 014672321667 15242 5ustar00leoleo000000000000Test-MemoryGrowth-0.05/lib/Test/MemoryGrowth.pm000444001750001750 3072214672321667 20424 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2010-2024 -- leonerd@leonerd.org.uk package Test::MemoryGrowth 0.05; use v5.14; use warnings; use base qw( Test::Builder::Module ); our @EXPORT = qw( no_growth ); use constant HAVE_DEVEL_GLADIATOR => defined eval { require Devel::Gladiator }; use constant HAVE_DEVEL_MAT_DUMPER => defined eval { require Devel::MAT::Dumper }; =head1 NAME C - assert that code does not cause growth in memory usage =head1 SYNOPSIS =for highlighter language=perl use Test::More; use Test::MemoryGrowth; use Some::Class; no_growth { my $obj = Some::Class->new; } 'Constructing Some::Class does not grow memory'; my $obj = Some::Class->new; no_growth { $obj->do_thing; } 'Some::Class->do_thing does not grow memory'; #### This test will fail #### my @list; no_growth { push @list, "Hello world"; } 'pushing to an array does not grow memory'; done_testing; =head1 DESCRIPTION This module provides a function to check that a given block of code does not result in the process consuming extra memory once it has finished. Despite the name of this module it does not, in the strictest sense of the word, test for a memory leak: that term is specifically applied to cases where memory has been allocated but all record of it has been lost, so it cannot possibly be reclaimed. While the method employed by this module can detect such bugs, it can also detect cases where memory is still referenced and reachable, but the usage has grown more than would be expected or necessary. The block of code will be run a large number of times (by default 10,000), and the difference in memory usage by the process before and after is compared. If the memory usage has now increased by more than one byte per call, then the test fails. In order to give the code a chance to load initial resources it needs, it will be run a few times first (by default 10); giving it a chance to load files, AUTOLOADs, caches, or any other information that it requires. Any extra memory usage here will not count against it. This simple method is not a guaranteed indicator of the absence of memory resource bugs from a piece of code; it has the possibility to fail in both a false-negative and a false-positive way. =over 4 =item False Negative It is possible that a piece of code causes memory usage growth that this module does not detect. Because it only detects memory growth of at least one byte per call, it cannot detect cases of linear memory growth at lower rates than this. Most memory usage growth comes either from Perl-level or C-level bugs where memory objects are created at every call and not reclaimed again. (These are either genuine memory leaks, or needless allocations of objects that are stored somewhere and never reclaimed). It is unlikely such a bug would result in a growth rate smaller than one byte per call. A second failure case comes from the fact that memory usage is taken from the Operating System's measure of the process's Virtual Memory size, so as to be able to detect memory usage growth in C libraries or XS-level wrapping code, as well as Perl functions. Because Perl does not aggressively return unused memory to the Operating System, it is possible that a piece of code could use un-allocated but un-reclaimed memory to grow into; resulting in an increase in its requirements despite not requesting extra memory from the Operating System. =item False Positive It is possible that the test will claim that a function grows in memory, when the behaviour is in fact perfectly normal for the code in question. For example, the code could simply be some function whose behaviour is required to store extra state; for example, adding a new item into a list. In this case it is in fact expected that the memory usage of the process will increase. =back By careful use of this test module, false indications can be minimised. By splitting tests across many test scripts, each one can be started in a new process state, where most of the memory assigned from the Operating System is in use by Perl, so anything extra that the code requires will have to request more. This should reduce the false negative indications. By keeping in mind that the module simply measures the change in allocated memory size, false positives can be minimised, by not attempting to assert that certain pieces of code do not grow in memory, when in fact it would be expected that they do. =head2 Devel::Gladiator Integration I If L is installed, this test module will use it as a second potential source of detecting memory growth. A walk of the Perl memory heap is taken before running the code, in order to count the number of every kind of object present. This is then compared to a second count taken afterwards. Any object types that have increased by at least one per call are reported. For example, the output might contain the following extra lines of diagnostic output: =for highlighter # Growths in arena object counts: # ARRAY 1735 -> 11735 (1.00 per call) # HASH 459 -> 10459 (1.00 per call) # REF 1387 -> 21387 (2.00 per call) # REF-ARRAY 163 -> 10163 (1.00 per call) # REF-HASH 66 -> 10066 (1.00 per call) # WithContainerSlots 10 -> 10010 (1.00 per call) =head2 Devel::MAT Integration If L is installed, this test module will use it to dump the state of the memory after a failure. It will create a F<.pmat> file named the same as the unit test, but with the trailing F<.t> suffix replaced with F<-TEST.pmat> where C is the number of the test that failed (in case there was more than one). It will then run the code under test one more time, before writing another file whose name is suffixed with F<-TEST-after.pmat>. This pair of files may be useful for differential analysis. =cut =head1 FUNCTIONS =for highlighter language=perl =cut sub get_heapcounts { return {} unless HAVE_DEVEL_GLADIATOR; my $counts = Devel::Gladiator::arena_ref_counts(); return $counts; } sub get_memusage_linux { # TODO: This implementation sucks piggie. Write a proper one open( my $statush, "<", "/proc/self/status" ) or die "Cannot open status - $!"; m/^VmSize:\s+([0-9]+) kB/ and return $1 for <$statush>; } sub get_memusage_freebsd { open( my $procstath, "-|", "procstat -v $$" ) or die "Cannot open procstat - $!"; # Sample command output (some parts of it at least): # PID START END PRT RES PRES REF SHD FLAG TP PATH # 18607 0x200000 0x3e5000 r-- 353 729 8 4 CN--- vn /root/perl5/perlbrew/perls/perl-5.40.0/bin/perl # 18607 0x3e5000 0x55c000 r-x 375 729 8 4 CN--- vn /root/perl5/perlbrew/perls/perl-5.40.0/bin/perl # 18607 0x55c000 0x55d000 r-- 1 0 1 0 CN--- vn /root/perl5/perlbrew/perls/perl-5.40.0/bin/perl # 18607 0x55d000 0x55f000 rw- 2 0 1 0 CN--- vn /root/perl5/perlbrew/perls/perl-5.40.0/bin/perl # 18607 0x55f000 0x567000 rw- 8 8 1 0 C---- sw # 18607 0x801148000 0x821128000 --- 0 0 0 0 ----- gd # 18607 0x821128000 0x821148000 rw- 8 8 1 0 C--D- sw # 18607 0x821a0d000 0x821a0e000 r-x 1 1 115 0 ----- ph # 18607 0x82293f000 0x82294c000 r-- 13 32 34 14 CN--- vn /lib/libthr.so.3 # 18607 0x82294c000 0x82295e000 r-x 18 32 34 14 CN--- vn /lib/libthr.so.3 # 18607 0x82794b000 0x82794f000 r-x 4 5 4 2 CN--- vn /root/perl5/perlbrew/perls/perl-5.40.0/lib/5.40.0/amd64-freebsd/auto/mro/mro.so # 18607 0x82794f000 0x827950000 r-- 1 0 1 0 CN--- vn /root/perl5/perlbrew/perls/perl-5.40.0/lib/5.40.0/amd64-freebsd/auto/mro/mro.so # 18607 0x827950000 0x827951000 rw- 1 0 1 0 CN--- vn /root/perl5/perlbrew/perls/perl-5.40.0/lib/5.40.0/amd64-freebsd/auto/mro/mro.so # 18607 0x828599000 0x82859a000 r-- 1 2 4 2 CN--- vn /root/perl5/perlbrew/perls/perl-5.40.0/lib/site_perl/5.40.0/amd64-freebsd/auto/Devel/Gladiator/Gladiator.so # 18607 0x82859a000 0x82859c000 r-x 2 2 4 2 CN--- vn /root/perl5/perlbrew/perls/perl-5.40.0/lib/site_perl/5.40.0/amd64-freebsd/auto/Devel/Gladiator/Gladiator.so my $head = <$procstath>; my @columns = split /\s+/, $head; my ($res_column) = grep { $columns[$_] eq 'RES' } 0 .. $#columns; my ($pres_column) = grep { $columns[$_] eq 'PRES' } 0 .. $#columns; my $pages = 0; while (my $line = <$procstath>) { @columns = split /\s+/, $line; $pages += $columns[$res_column] + $columns[$pres_column]; } # NOTE: FreeBSD wiki states that page size is 4KB *on most platforms*. # I don't know how to query the system for its page size return 4 * $pages if $pages > 0; } BEGIN { my $get_memusage = __PACKAGE__->can( "get_memusage_$^O" ) or die "Unable to find an implementation of get_memusage for OS=$^O"; *get_memusage = $get_memusage; } =head2 no_growth no_growth { CODE } %opts, $name; Assert that the code block does not consume extra memory. Takes the following named arguments: =over 8 =item calls => INT The number of times to call the code during growth testing. =item burn_in => INT The number of times to call the code initially, before watching for memory usage. =back =cut sub no_growth(&@) { my $code = shift; my $name; $name = pop if @_ % 2; my %args = @_; my $tb = __PACKAGE__->builder; my $burn_in = $args{burn_in} || 10; my $calls = $args{calls} || 10_000; my $i = 0; $code->() while $i++ < $burn_in; # Fetch usage twice; first to allocate memory for it to run in so the # second can account for it. my $before_usage = get_memusage; my $before_counts = get_heapcounts; # Fetch a second copy before code, to preallocate memory for it now my $after_counts = get_heapcounts; $before_counts = $after_counts; my $after_usage = get_memusage; $before_usage = $after_usage; $i = 0; $code->() while $i++ < $calls; undef $after_usage; undef $after_counts; $after_usage = get_memusage; $after_counts = get_heapcounts; # Collect up various test results my $ok = 1; my $increase = ( $after_usage - $before_usage ) * 1024; # in bytes # Even if we increased in memory usage, it's OK as long as we didn't gain # more than one byte per call $ok = 0 if $increase >= $calls; my $growth_counts; foreach my $type ( keys %$after_counts ) { my $growth = $after_counts->{$type} - $before_counts->{$type}; next unless $growth >= $calls; $growth_counts->{$type} = sprintf "%d -> %d (%.2f per call)", $before_counts->{$type}, $after_counts->{$type}, $growth / $calls; } $ok = 0 if $growth_counts; $tb->ok( $ok, $name ); return $ok if $ok; if( $increase >= $calls ) { $tb->diag( sprintf "Lost %d bytes of memory over %d calls, average of %.2f per call", $increase, $calls, $increase / $calls ); } if( $growth_counts ) { $tb->diag( "Growths in arena object counts:\n" . join( "\n", map { " $_ $growth_counts->{$_}" } sort keys %$growth_counts ) ); } if( HAVE_DEVEL_MAT_DUMPER ) { my $file = $0; my $num = $tb->current_test; # Trim the .t off first then append -$num.pmat, in case $0 wasn't a .t file $file =~ s/\.(?:t|pm|pl)$//; my $beforefile = "$file-$num.pmat"; my $afterfile = "$file-$num-after.pmat"; # Try to arrange the memory in as similar as state as possible by running # one more iteration now before we take the "before" snapshot $code->(); $tb->diag( "Writing heap dump to $beforefile" ); Devel::MAT::Dumper::dump( $beforefile ); $code->(); $tb->diag( "Writing heap dump after one more iteration to $afterfile" ); Devel::MAT::Dumper::dump( $afterfile ); } return $ok; } =head1 TODO =over 8 =item * More OS portability Currently, this module uses OS-specific methods of determining process memory usage (namely, by inspecting F on Linux or calling F on FreeBSD). It would be nice to support more OSes, and potentially find a better abstraction for doing so. Currently I am unaware of a simple portable mechanism to query this. Patches very much welcome. :) =back =head1 AUTHOR Paul Evans =cut 0x55AA; Test-MemoryGrowth-0.05/t000755001750001750 014672321667 14020 5ustar00leoleo000000000000Test-MemoryGrowth-0.05/t/00use.t000444001750001750 20014672321667 15246 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; require Test::MemoryGrowth; pass( 'Modules loaded' ); done_testing; Test-MemoryGrowth-0.05/t/01leak.t000444001750001750 223414672321667 15420 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use Test::Builder::Tester; use Test::MemoryGrowth; my $l = 10; my $r = 20; my $sum; test_out( "ok 1 - addition does not grow" ); no_growth { $sum = $l + $r } "addition does not grow"; test_test( "no_growth addition succeeds" ); my @arr; test_out( "not ok 1 - push does not grow" ); test_fail( +12 ); # Process memory growth might not be noticable, depending on Perl version, # loaded modules, memory ordering, etc.. test_err( qr/(^# Lost \d+ bytes of memory over \d+ calls, average of \d+\.\d\d per call\n)?/ ); if( Test::MemoryGrowth::HAVE_DEVEL_GLADIATOR ) { test_err( qr/^# Growths in arena object counts:\n/ ); test_err( qr/^# SCALAR \d+ -> \d+ \(1\.00 per call\)\n/ ); } if( Test::MemoryGrowth::HAVE_DEVEL_MAT_DUMPER ) { test_err( qr/^# Writing heap dump to \S+\n/ ); test_err( qr/^# Writing heap dump after one more iteration to \S+\n/ ); } no_growth { push @arr, "hello"; } "push does not grow"; test_test( "no_growth push fails" ); done_testing; END { # Clean up Devel::MAT dumpfile ( my $basename = $0 ) =~ s/\.t$//; -f and unlink for "$basename-1.pmat", "$basename-1-after.pmat"; } Test-MemoryGrowth-0.05/t/02counts.t000444001750001750 50314672321667 15775 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use Test::MemoryGrowth; my $count; $count = 0; no_growth { $count++ }; is( $count, 10010, '$count == 10010 after defaults' ); $count = 0; no_growth { $count++ } burn_in => 5, calls => 5; is( $count, 10, '$count == 10 after burn_in=5, calls=5' ); done_testing; Test-MemoryGrowth-0.05/t/99pod.t000444001750001750 25514672321667 15270 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok();