Test-MockModule-v0.177.0000755000000000000 014115711576 14137 5ustar00rootroot000000000000Test-MockModule-v0.177.0/Build.PL000444000000000000 174114115711576 15573 0ustar00rootroot000000000000use strict; use warnings; use Module::Build; my $builder = Module::Build->new( module_name => 'Test::MockModule', create_license => 1, license => 'perl', dist_author => [q{Current Maintainer: Geoff Franks }, q{Original Author: Simon Flack }], meta_merge => { resources => { homepage => 'https://github.com/geofffranks/test-mockmodule', bugtracker => 'https://github.com/geofffranks/test-mockmodule/issues', repository => 'git://github.com/geofffranks/test-mockmodule.git', }, }, configure_requires => { 'Module::Build' => '0.38', }, requires => { 'perl' => 5.006, 'Carp' => 0, 'Scalar::Util' => 0, 'SUPER' => '1.20', }, test_requires => { 'Test::More' => 0.88, 'Test::Warnings' => 0 }, add_to_cleanup => [ 'Test-MockModule-*', 'cover_db', '*.rpm', '*.deb', ] ); $builder->create_build_script(); Test-MockModule-v0.177.0/Changes000444000000000000 1102314115711576 15604 0ustar00rootroot000000000000Revision history for Test::MockModule v0.177.0 - 35f0d0b Update changelog - Geoff Franks - 1d5b485 Move test modules from build to test requires - Olaf Alders - 78afe10 Clean up changelog - Geoff Franks v0.277.0 - Move test modules from build to test requires - Olaf Alders v0.176.0 - 3ba8bc7 lexically scoped strictness - David Cantrell - e57fc5a Update ci with dockerhub auth - Geoff Franks - bfe1e63 Update GitHub workflow with deprecated add-path - Nicolas R v0.175.0 - 964aa2a Ignore CI files and whitesource - Nicolas R v0.174.0 - cf65e7c Fix typo in pod - nima v0.173.0 - 4dacd82 Add warning when 'unmock' called without arguments - Matthew Hughes - b20dc7c import warns when using unknown argument - Nicolas R - 3b217ba Fix windows CI by installing SUPER - Nicolas R - 0ef70c5 Add .whitesource configuration file - whitesource-bolt-for-github[bot] v0.172.0 - 7558aa9 Make sure we can redefine a function in 'main' - Nicolas R - 0538fe1 Plug GitHub workflow as additional CI - Nicolas R - 0e9d90b update parallel to use in_parallel instead ofaggregate - Geoff Franks v0.171.0 - 89dc5c0 Fixes #25 - mocking core::global no longer fails trying to load the module - Geoff Franks - 9bb081a update ci for fewer infinite loops - Geoff Franks - 289d014 Update release notes for all the newly merged PRs - Geoff Franks - fef9e74 Allow chaining of new with mock, redefine, define - Nicolas Rochelemagne - e136131 Prevent redefine() from triggering DESTROY. - Felipe Gasper - 311f6b4 Adjust Travis CI configuration to use travis-perl.github.io - Nicolas Rochelemagne - 2bed3e2 Add strict mode to ban the use of noop and mock. - Todd Rinaldo - 0298d8d Provide define method so the mock method is unneeded in tests. - Todd Rinaldo v0.171.0 - allow chaining of new with mock, redefine, define - redefine() no longer triggers errors if the object being mocked is not a hashref - Adds a define() method for mocking new functions that do not exist. Throws an error if a function does exist. - Adds `strict` mode to prevent usage of noop() and mock() functions, and force the usage of define/redefine if desired.: ``` use Test::MockModule qw/strict/; ``` - Mocking CORE::GLOBAL no longer throws errors indicating CORE::GLOBAL should have been installed/loaded v0.170.0 - 182d066 Fix versioning for semver conversion + PAUSE - Geoff Franks - 4afeedf release v0.17.0 - CI Bot - 9df8ac4 Add CI pipeline for releasing to cpan - Geoff Franks - 577350e Pod - provide a code snippet for original usage - Nicolas R - 3e4ec72 Add missing pod entries - Geoff Franks v0.16 - Fixes an issue where warnings were thrown for mismatched prototypes, when mocking a prototyped function. Thanks @toddr for the fix! v0.15 - Fixes a minor bug in the release tarball v0.14 - Fixes a bug where the `redefine()` function was dying when attempting to mock a function that was defined further up a module's inheritance chain. It now only dies when the mocked function does not exist in the module being mocked, or any of its parent modules. Thanks @atoomic for the improvement! v0.13 - Added the `redefine()` function. It works just like `mock()`, except if the method being mocked doesn't exist, it causes a panic. Many thanks to Felipe Gasper for this feature! v0.12 - Added the `noop()` function to make mocking noops easier. Thanks for the PR, Ali Zia! v0.11 2016-10-27 - Various housekeeping, testing and minor fixes, courtesy of Paul Cochrane, thanks! v0.10 2015-05-30 - Updated docs for mocking when using exported functions v0.09 2015-03-15 - Ensure LICENSE autogenerates for distribution, fixed license issues in Build.PL v0.08 2015-03-14 - Updated README with correct instructions now that we use Build.PL v0.07 2015-03-14 - Updated docs for more clarity when handling objects of mocked classes. v0.06 2015-03-07 - unmock() on inherited subroutines will dispatch to the parent module, rather than replace the local subroutine with the parent's subroutine from the time of mocking (RT77439) v0.05 2004-03-24 - unmock() accepts a list of subroutines to unmock. Thanks to David Wheeler for the suggestion and patch - Added t/pod_coverage.t v0.04 2004-12-12 - You can now mock a subroutine with a scalar value or a reference (install sub that returns the value). Thanks to Ovid for the suggestion. v0.03 2004-12-05 - Restores subs/methods that previously didn't exist (undefine them) v0.02 2004-11-28 - Fixed restoring inherited methods v0.01 2004-11-28 - Initial revision Test-MockModule-v0.177.0/LICENSE000444000000000000 4431214115711576 15325 0ustar00rootroot000000000000This software is copyright (c) 2021 by Current Maintainer: Geoff Franks & Original Author: Simon Flack . 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) 2021 by Current Maintainer: Geoff Franks & Original Author: Simon Flack . 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 Artistic License 1.0 --- This software is Copyright (c) 2021 by Current Maintainer: Geoff Franks & Original Author: Simon Flack . This is free software, licensed under: The 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. - "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 ftp.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) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting 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. 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 whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End Test-MockModule-v0.177.0/MANIFEST000444000000000000 66114115711576 15410 0ustar00rootroot000000000000Build.PL Changes lib/Test/MockModule.pm LICENSE MANIFEST This list of files MANIFEST.SKIP README.md t/chaining.t t/define.t t/inheritance.t t/lib/ExampleModule.pm t/lib/ScopedStrict/Mockee1.pm t/lib/ScopedStrict/Mockee2.pm t/lib/ScopedStrict/NonStrictMocker.pm t/lib/ScopedStrict/StrictMocker.pm t/main.t t/mock_strict.t t/mockmodule.t t/pod.t t/pod_coverage.t t/prototype.t t/redefine.t t/strict_scoped_files.t META.yml META.json Test-MockModule-v0.177.0/MANIFEST.SKIP000444000000000000 245214115711576 16175 0ustar00rootroot000000000000 #!start included /usr/share/perl/5.14/ExtUtils/MANIFEST.SKIP # Avoid version control files. \bRCS\b \bCVS\b \bSCCS\b ,v$ \B\.svn\b \B\.git\b \B\.github\b \B\.gitignore\b \b_darcs\b \B\.cvsignore$ # ignore ci files ^ci\b # ignore whitesource \B\.whitesource # Avoid VMS specific MakeMaker generated files \bDescrip.MMS$ \bDESCRIP.MMS$ \bdescrip.mms$ # Avoid Makemaker generated and utility files. \bMANIFEST\.bak \bMakefile$ \bblib/ \bMakeMaker-\d \bpm_to_blib\.ts$ \bpm_to_blib$ \bblibdirs\.ts$ # 6.18 through 6.25 generated this # Avoid Module::Build generated and utility files. \bBuild$ \b_build/ \bBuild.bat$ \bBuild.COM$ \bBUILD.COM$ \bbuild.com$ # Avoid temp and backup files. ~$ \.old$ \#$ \b\.# \.bak$ \.tmp$ \.# \.rej$ # Avoid OS-specific files/dirs # Mac OSX metadata \B\.DS_Store # Mac OSX SMB mount metadata files \B\._ # Avoid Devel::Cover and Devel::CoverX::Covered files. \bcover_db\b \bcovered\b # Avoid MYMETA files ^MYMETA\. #!end included /usr/share/perl/5.14/ExtUtils/MANIFEST.SKIP # Avoid configuration metadata file ^MYMETA\. # Avoid Module::Build generated and utility files. \bBuild$ \bBuild.bat$ \b_build \bBuild.COM$ \bBUILD.COM$ \bbuild.com$ #^MANIFEST\.SKIP # Avoid archives of this distribution ^Test-MockModule-* ^t/tmp # Avoid Travis-CI configuration file \.travis.yml Test-MockModule-v0.177.0/META.json000444000000000000 300414115711576 15712 0ustar00rootroot000000000000{ "abstract" : "Override subroutines in a module for unit testing", "author" : [ "Current Maintainer: Geoff Franks ", "Original Author: Simon Flack " ], "dynamic_config" : 1, "generated_by" : "Module::Build version 0.4224", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Test-MockModule", "prereqs" : { "configure" : { "requires" : { "Module::Build" : "0.38" } }, "runtime" : { "requires" : { "Carp" : "0", "SUPER" : "1.20", "Scalar::Util" : "0", "perl" : "5.006" } }, "test" : { "requires" : { "Test::More" : "0.88", "Test::Warnings" : "0" } } }, "provides" : { "Test::MockModule" : { "file" : "lib/Test/MockModule.pm", "version" : "v0.177.0" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/geofffranks/test-mockmodule/issues" }, "homepage" : "https://github.com/geofffranks/test-mockmodule", "license" : [ "http://dev.perl.org/licenses/" ], "repository" : { "url" : "git://github.com/geofffranks/test-mockmodule.git" } }, "version" : "v0.177.0", "x_serialization_backend" : "JSON::PP version 2.27400_02" } Test-MockModule-v0.177.0/META.yml000444000000000000 175214115711576 15552 0ustar00rootroot000000000000--- abstract: 'Override subroutines in a module for unit testing' author: - 'Current Maintainer: Geoff Franks ' - 'Original Author: Simon Flack ' build_requires: Test::More: '0.88' Test::Warnings: '0' configure_requires: Module::Build: '0.38' dynamic_config: 1 generated_by: 'Module::Build version 0.4224, 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-MockModule provides: Test::MockModule: file: lib/Test/MockModule.pm version: v0.177.0 requires: Carp: '0' SUPER: '1.20' Scalar::Util: '0' perl: '5.006' resources: bugtracker: https://github.com/geofffranks/test-mockmodule/issues homepage: https://github.com/geofffranks/test-mockmodule license: http://dev.perl.org/licenses/ repository: git://github.com/geofffranks/test-mockmodule.git version: v0.177.0 x_serialization_backend: 'CPAN::Meta::YAML version 0.018' Test-MockModule-v0.177.0/README.md000444000000000000 77514115711576 15544 0ustar00rootroot000000000000# Test::MockModule - mock subroutines in a module See the LICENSE section in `lib/Test/MockModule.pm` for usage and distribution rights. ## Installation Run these commands in the source directory: perl Build.PL ./Build ./Build test ./Build install Then delete the source directory tree since it's no longer needed. Alternatively, you can simply install the module via `cpanm`: cpanm Test::MockModule ## Documentation Run `perldoc Test::MockModule` to read the full documentation. Test-MockModule-v0.177.0/lib000755000000000000 014115711576 14705 5ustar00rootroot000000000000Test-MockModule-v0.177.0/lib/Test000755000000000000 014115711576 15624 5ustar00rootroot000000000000Test-MockModule-v0.177.0/lib/Test/MockModule.pm000444000000000000 3760014115711576 20404 0ustar00rootroot000000000000package Test::MockModule; use warnings; use strict qw/subs vars/; use vars qw/$VERSION/; use Scalar::Util qw/reftype weaken/; use Carp; use SUPER; $VERSION = '0.177.0'; sub import { my ( $class, @args ) = @_; # default if no args $^H{'Test::MockModule/STRICT_MODE'} = 0; foreach my $arg (@args) { if ( $arg eq 'strict' ) { $^H{'Test::MockModule/STRICT_MODE'} = 1; } elsif ( $arg eq 'nostrict' ) { $^H{'Test::MockModule/STRICT_MODE'} = 0; } else { warn "Test::MockModule unknown import option '$arg'"; } } return; } sub _strict_mode { my $depth = 0; while(my @fields = caller($depth++)) { my $hints = $fields[10]; if($hints && grep { /^Test::MockModule\// } keys %{$hints}) { return $hints->{'Test::MockModule/STRICT_MODE'}; } } return 0; } my %mocked; sub new { my $class = shift; my ($package, %args) = @_; if ($package && (my $existing = $mocked{$package})) { return $existing; } croak "Cannot mock $package" if $package && $package eq $class; unless (_valid_package($package)) { $package = 'undef' unless defined $package; croak "Invalid package name $package"; } unless ($package eq "CORE::GLOBAL" || $package eq 'main' || $args{no_auto} || ${"$package\::VERSION"}) { (my $load_package = "$package.pm") =~ s{::}{/}g; TRACE("$package is empty, loading $load_package"); require $load_package; } TRACE("Creating MockModule object for $package"); my $self = bless { _package => $package, _mocked => {}, }, $class; $mocked{$package} = $self; weaken $mocked{$package}; return $self; } sub DESTROY { my $self = shift; $self->unmock_all; } sub get_package { my $self = shift; return $self->{_package}; } sub redefine { my ($self, @mocks) = (shift, @_); while ( my ($name, $value) = splice @mocks, 0, 2 ) { my $sub_name = $self->_full_name($name); my $coderef = *{$sub_name}{'CODE'}; next if 'CODE' eq ref $coderef; if ( $sub_name =~ qr{^(.+)::([^:]+)$} ) { my ( $pkg, $sub ) = ( $1, $2 ); next if $pkg->can( $sub ); } if ('CODE' ne ref $coderef) { croak "$sub_name does not exist!"; } } return $self->_mock(@_); } sub define { my ($self, @mocks) = (shift, @_); while ( my ($name, $value) = splice @mocks, 0, 2 ) { my $sub_name = $self->_full_name($name); my $coderef = *{$sub_name}{'CODE'}; if ('CODE' eq ref $coderef) { croak "$sub_name exists!"; } } return $self->_mock(@_); } sub mock { my ($self, @mocks) = (shift, @_); croak "mock is not allowed in strict mode. Please use define or redefine" if($self->_strict_mode()); return $self->_mock(@mocks); } sub _mock { my $self = shift; while (my ($name, $value) = splice @_, 0, 2) { my $code = sub { }; if (ref $value && reftype $value eq 'CODE') { $code = $value; } elsif (defined $value) { $code = sub {$value}; } TRACE("$name: $code"); croak "Invalid subroutine name: $name" unless _valid_subname($name); my $sub_name = _full_name($self, $name); if (!$self->{_mocked}{$name}) { TRACE("Storing existing $sub_name"); $self->{_mocked}{$name} = 1; if (defined &{$sub_name}) { $self->{_orig}{$name} = \&$sub_name; } else { $self->{_orig}{$name} = undef; } } TRACE("Installing mocked $sub_name"); _replace_sub($sub_name, $code); } return $self; } sub noop { my $self = shift; croak "noop is not allowed in strict mode. Please use define or redefine" if($self->_strict_mode()); $self->_mock($_,1) for @_; return; } sub original { my $self = shift; my ($name) = @_; return carp _full_name($self, $name) . " is not mocked" unless $self->{_mocked}{$name}; return defined $self->{_orig}{$name} ? $self->{_orig}{$name} : $self->{_package}->super($name); } sub unmock { my $self = shift; carp 'Nothing to unmock' unless @_; for my $name (@_) { croak "Invalid subroutine name: $name" unless _valid_subname($name); my $sub_name = _full_name($self, $name); unless ($self->{_mocked}{$name}) { carp $sub_name . " was not mocked"; next; } TRACE("Restoring original $sub_name"); _replace_sub($sub_name, $self->{_orig}{$name}); delete $self->{_mocked}{$name}; delete $self->{_orig}{$name}; } return $self; } sub unmock_all { my $self = shift; foreach (keys %{$self->{_mocked}}) { $self->unmock($_); } return; } sub is_mocked { my $self = shift; my ($name) = shift; return $self->{_mocked}{$name}; } sub _full_name { my ($self, $sub_name) = @_; sprintf "%s::%s", $self->{_package}, $sub_name; } sub _valid_package { defined($_[0]) && $_[0] =~ /^[a-z_]\w*(?:::\w+)*$/i; } sub _valid_subname { $_[0] =~ /^[a-z_]\w*$/i; } sub _replace_sub { my ($sub_name, $coderef) = @_; no warnings 'redefine'; no warnings 'prototype'; if (defined $coderef) { *{$sub_name} = $coderef; } else { TRACE("removing subroutine: $sub_name"); my ($package, $sub) = $sub_name =~ /(.*::)(.*)/; my %symbols = %{$package}; # save a copy of all non-code slots my %slot; foreach (qw(ARRAY FORMAT HASH IO SCALAR)) { next unless defined(my $elem = *{$symbols{$sub}}{$_}); $slot{$_} = $elem; } # clear the symbol table entry for the subroutine undef *$sub_name; # restore everything except the code slot return unless keys %slot; foreach (keys %slot) { *$sub_name = $slot{$_}; } } } # Log::Trace stubs sub TRACE {} sub DUMP {} 1; =pod =head1 NAME Test::MockModule - Override subroutines in a module for unit testing =head1 SYNOPSIS use Module::Name; use Test::MockModule; { my $module = Test::MockModule->new('Module::Name'); $module->mock('subroutine', sub { ... }); Module::Name::subroutine(@args); # mocked # Same effect, but this will die() if other_subroutine() # doesn't already exist, which is often desirable. $module->redefine('other_subroutine', sub { ... }); # This will die() if another_subroutine() is defined. $module->define('another_subroutine', sub { ... }); } { # you can also chain new/mock/redefine/define Test::MockModule->new('Module::Name') ->mock( one_subroutine => sub { ... }) ->redefine( other_subroutine => sub { ... } ) ->define( a_new_sub => 1234 ); } Module::Name::subroutine(@args); # original subroutine # Working with objects use Foo; use Test::MockModule; { my $mock = Test::MockModule->new('Foo'); $mock->mock(foo => sub { print "Foo!\n"; }); my $foo = Foo->new(); $foo->foo(); # prints "Foo!\n" } # If you want to prevent noop and mock from working, you can # load Test::MockModule in strict mode. use Test::MockModule qw/strict/; my $module = Test::MockModule->new('Module::Name'); # Redefined the other_subroutine or dies if it's not there. $module->redefine('other_subroutine', sub { ... }); # Dies since you specified you wanted strict mode. $module->mock('subroutine', sub { ... }); # Turn strictness off in this lexical scope { use Test::MockModule 'nostrict'; # ->mock() works now $module->mock('subroutine', sub { ... }); } # Back in the strict scope, so mock() dies here $module->mock('subroutine', sub { ... }); =head1 DESCRIPTION C lets you temporarily redefine subroutines in other packages for the purposes of unit testing. A C object is set up to mock subroutines for a given module. The object remembers the original subroutine so it can be easily restored. This happens automatically when all MockModule objects for the given module go out of scope, or when you C the subroutine. =head1 STRICT MODE One of the weaknesses of testing using mocks is that the implementation of the interface that you are mocking might change, while your mocks get left alone. You are not now mocking what you thought you were, and your mocks might now be hiding bugs that will only be spotted in production. To help prevent this you can load Test::MockModule in 'strict' mode: use Test::MockModule qw(strict); This will disable use of the C method, making it a fatal runtime error. You should instead define mocks using C, which will only mock things that already exist and die if you try to redefine something that doesn't exist. Strictness is lexically scoped, so you can do this in one file: use Test::MockModule qw(strict); ...->redefine(...); and this in another: use Test::MockModule; # the default is nostrict ...->mock(...); You can even mix n match at different places in a single file thus: use Test::MockModule qw(strict); # here mock() dies { use Test::MockModule qw(nostrict); # here mock() works } # here mock() goes back to dieing use Test::MockModule qw(nostrict); # and from here on mock() works again NB that strictness must be defined at compile-time, and set using C. If you think you're going to try and be clever by calling Test::MockModule's C method at runtime then what happens in undefined, with results differing from one version of perl to another. What larks! =head1 METHODS =over 4 =item new($package[, %options]) Returns an object that will mock subroutines in the specified C<$package>. If there is no C<$VERSION> defined in C<$package>, the module will be automatically loaded. You can override this behaviour by setting the C option: my $mock = Test::MockModule->new('Module::Name', no_auto => 1); =item get_package() Returns the target package name for the mocked subroutines =item is_mocked($subroutine) Returns a boolean value indicating whether or not the subroutine is currently mocked =item mock($subroutine =E \Ecoderef) Temporarily replaces one or more subroutines in the mocked module. A subroutine can be mocked with a code reference or a scalar. A scalar will be recast as a subroutine that returns the scalar. Returns the current C object, so you can chain L with L. my $mock = Test::MockModule->new->(...)->mock(...); The following statements are equivalent: $module->mock(purge => 'purged'); $module->mock(purge => sub { return 'purged'}); When dealing with references, things behave slightly differently. The following statements are B equivalent: # Returns the same arrayref each time, with the localtime() at time of mocking $module->mock(updated => [localtime()]); # Returns a new arrayref each time, with up-to-date localtime() value $module->mock(updated => sub { return [localtime()]}); The following statements are in fact equivalent: my $array_ref = [localtime()] $module->mock(updated => $array_ref) $module->mock(updated => sub { return $array_ref }); However, C is a special case. If you mock a subroutine with C it will install an empty subroutine $module->mock(purge => undef); $module->mock(purge => sub { }); rather than a subroutine that returns C: $module->mock(purge => sub { undef }); You can call C for the same subroutine many times, but when you call C, the original subroutine is restored (not the last mocked instance). B If you are trying to mock a subroutine exported from another module, this may not behave as you initially would expect, since Test::MockModule is only mocking at the target module, not anything importing that module. If you mock the local package, or use a fully qualified function name, you will get the behavior you desire: use Test::MockModule; use Test::More; use POSIX qw/strftime/; my $posix = Test::MockModule->new("POSIX"); $posix->mock("strftime", "Yesterday"); is strftime("%D", localtime(time)), "Yesterday", "`strftime` was mocked successfully"; # Fails is POSIX::strftime("%D", localtime(time)), "Yesterday", "`strftime` was mocked successfully"; # Succeeds my $main = Test::MockModule->new("main", no_auto => 1); $main->mock("strftime", "today"); is strftime("%D", localtime(time)), "today", "`strftime` was mocked successfully"; # Succeeds If you are trying to mock a subroutine that was exported into a module that you're trying to test, rather than mocking the subroutine in its originating module, you can instead mock it in the module you are testing: package MyModule; use POSIX qw/strftime/; sub minus_twentyfour { return strftime("%a, %b %d, %Y", localtime(time - 86400)); } package main; use Test::More; use Test::MockModule; my $posix = Test::MockModule->new("POSIX"); $posix->mock("strftime", "Yesterday"); is MyModule::minus_twentyfour(), "Yesterday", "`minus-twentyfour` got mocked"; # fails my $mymodule = Test::MockModule->new("MyModule", no_auto => 1); $mymodule->mock("strftime", "Yesterday"); is MyModule::minus_twentyfour(), "Yesterday", "`minus-twentyfour` got mocked"; # succeeds =item redefine($subroutine) The same behavior as C, but this will preemptively check to be sure that all passed subroutines actually exist. This is useful to ensure that if a mocked module's interface changes the test doesn't just keep on testing a code path that no longer behaves consistently with the mocked behavior. Note that redefine is also now checking if one of the parent provides the sub and will not die if it's available in the chain. Returns the current C object, so you can chain L with L. my $mock = Test::MockModule->new->(...)->redefine(...); =item define($subroutine) The reverse of redefine, this will fail if the passed subroutine exists. While this use case is rare, there are times where the perl code you are testing is inspecting a package and adding a missing subroutine is actually what you want to do. By using define, you're asserting that the subroutine you want to be mocked should not exist in advance. Note: define does not check for inheritance like redefine. Returns the current C object, so you can chain L with L. my $mock = Test::MockModule->new->(...)->define(...); =item original($subroutine) Returns the original (unmocked) subroutine Here is a sample how to wrap a function with custom arguments using the original subroutine. This is useful when you cannot (do not) want to alter the original code to abstract one hardcoded argument pass to a function. package MyModule; sub sample { return get_path_for("/a/b/c/d"); } sub get_path_for { ... # anything goes there... } package main; use Test::MockModule; my $mock = Test::MockModule->new("MyModule"); # replace all calls to get_path_for using a different argument $mock->redefine("get_path_for", sub { return $mock->original("get_path_for")->("/my/custom/path"); }); # or $mock->redefine("get_path_for", sub { my $path = shift; if ( $path && $path eq "/a/b/c/d" ) { # only alter calls with path set to "/a/b/c/d" return $mock->original("get_path_for")->("/my/custom/path"); } else { # preserve the original arguments return $mock->original("get_path_for")->($path, @_); } }); =item unmock($subroutine [, ...]) Restores the original C<$subroutine>. You can specify a list of subroutines to C in one go. =item unmock_all() Restores all the subroutines in the package that were mocked. This is automatically called when all C objects for the given package go out of scope. =item noop($subroutine [, ...]) Given a list of subroutine names, mocks each of them with a no-op subroutine. Handy for mocking methods you want to ignore! # Neuter a list of methods in one go $module->noop('purge', 'updated'); =back =over 4 =item TRACE A stub for Log::Trace =item DUMP A stub for Log::Trace =back =head1 SEE ALSO L L =head1 AUTHORS Current Maintainer: Geoff Franks Original Author: Simon Flack Esimonflk _AT_ cpan.orgE Lexical scoping of strictness: David Cantrell Edavid@cantrell.org.ukE =head1 COPYRIGHT Copyright 2004 Simon Flack Esimonflk _AT_ cpan.orgE. All rights reserved You may distribute under the terms of either the GNU General Public License or the Artistic License, as specified in the Perl README file. =cut Test-MockModule-v0.177.0/t000755000000000000 014115711576 14402 5ustar00rootroot000000000000Test-MockModule-v0.177.0/t/chaining.t000444000000000000 125714115711576 16511 0ustar00rootroot000000000000use warnings; use strict; use Test::More; use Test::Warnings; use Test::MockModule; my $mocker = Test::MockModule->new('Mockee')->mock( good => 51 ) ->redefine( to_redefine => sub { 42 } )->define( something => 1234 ); isa_ok $mocker, 'Test::MockModule'; is( Mockee::good(), 51, 'mock() works when chaining with new' ); is( Mockee::to_redefine(), 42, 'redefine() works when chaining with new' ); is( Mockee::something(), 1234, 'something() works when chaining with new' ); done_testing(); #---------------------------------------------------------------------- package Mockee; our $VERSION; BEGIN { $VERSION = 1 } sub good { 1 } sub to_redefine { 1 } 1; Test-MockModule-v0.177.0/t/define.t000444000000000000 164414115711576 16163 0ustar00rootroot000000000000use warnings; use strict; use Test::More; use Test::Warnings; use Test::MockModule; my $mocker = Test::MockModule->new('Mockee'); $mocker->define( 'doesnt_exist', 2 ); is( Mockee::doesnt_exist(), 2, 'define() allows us to mock nonexistant subroutines.' ); eval { $mocker->define( 'existing_subroutine', 6 ) }; like( $@, qr/Mockee::existing_subroutine exists\!/, 'exception when define()ing an existing subroutine' ); undef $mocker; is( Mockee->can('doesnt_exist'), undef, "the defined sub went away after mocker is undeffed" ); $mocker = Test::MockModule->new('Mockee'); $mocker->define( 'doesnt_exist', 3 ); is( Mockee::doesnt_exist(), 3, 'The subroutine can be defined again after the mock object goes out of scope and is re-instantiated.' ); done_testing(); #---------------------------------------------------------------------- package Mockee; our $VERSION; BEGIN { $VERSION = 1 } sub existing_subroutine { 1 } 1; Test-MockModule-v0.177.0/t/inheritance.t000444000000000000 526114115711576 17221 0ustar00rootroot000000000000use warnings; use strict; use Test::MockModule; use Test::More; use Test::Warnings; @Bar::ISA = 'Foo'; @Baz::ISA = 'Bar'; sub Foo::motto { 'Foo!' }; is(Foo->motto(), "Foo!", "pre-mock: Foo original motto is correct"); is(Bar->motto(), "Foo!", "pre-mock: Bar inherit's Foo's motto"); is(Baz->motto(), "Foo!", "pre-mock: Baz inherit's Bar's inheritance of Foo's motto"); { my $mock_bar = Test::MockModule->new('Bar', no_auto => 1); $mock_bar->mock('motto', sub { 'Bar!' }); is(Foo->motto(), "Foo!", "Foo motto is unchanged post-Bar mock"); is(Bar->motto(), "Bar!", "Bar motto has been mocked"); is(Baz->motto(), "Bar!", "Baz inherits from Bar's mocked motto"); is($mock_bar->original("motto")->(), "Foo!", "Bar's original function can still be reached correctly"); ok($mock_bar->is_mocked("motto"), "Baz's motto is really mocked"); my $mock_baz = Test::MockModule->new('Baz', no_auto => 1); $mock_baz->mock('motto', sub { 'Baz!' }); is(Foo->motto(), "Foo!", "Foo motto is unchanged post-Baz mock"); is(Bar->motto(), "Bar!", "Bar motto is unchanged post-Baz mock"); is(Baz->motto(), "Baz!", "Baz motto has been mocked"); is($mock_baz->original("motto")->(), "Bar!", "Baz's original function is Bar's mocked function"); ok($mock_baz->is_mocked("motto"), "Baz's motto is really mocked"); $mock_bar->unmock("motto"); is(Bar->motto, "Foo!", "Bar's motto is unmocked"); is($mock_baz->original("motto")->(), "Foo!", "Baz's original function is now magically inherited up to Foo"); } is(Foo->motto(), "Foo!", "post-unmock: Foo original motto is correct"); is(Bar->motto(), "Foo!", "post-unmock: Bar inherit's Foo's motto"); is(Baz->motto(), "Foo!", "post-unmock: Baz inherit's Bar's inheritance of Foo's motto"); { BEGIN { $INC{'Mother.pm'} = '__MOCKED__'; $INC{'InvalidChild.pm'} = '__MOCKED__'; $INC{'ValidChild.pm'} = '__MOCKED__'; } package Mother; sub do_something { 1 } package InvalidChild; sub abcd { 1 } package ValidChild; use parent q{Mother}; sub abcd { 1 } } package main; { my $mock_child = Test::MockModule->new( 'InvalidChild' ); local $@; ok ! eval { $mock_child->redefine( 'do_something', sub { 42 } ); 1 }, "cannot redefine do_something"; like $@, qr{InvalidChild::do_something does not exist!}, "throw a die"; } { my $mock_child = Test::MockModule->new( 'ValidChild' ); local $@; ok eval { $mock_child->redefine( 'do_something', sub { 42 } ); 1 }, "cann redefine do_something when parent define this function"; is $@, '', 'no warnings'; my $object = bless {}, 'ValidChild'; is $object->do_something(), 42, "mocked value from do_something"; $mock_child->unmock( 'do_something' ); is $object->do_something(), 1, "do_something is now unmocked"; } done_testing; Test-MockModule-v0.177.0/t/main.t000444000000000000 42214115711576 15626 0ustar00rootroot000000000000use warnings; use strict; use Test::More; use Test::Warnings; use Test::MockModule; sub fourofour { 404 } my $mocker = Test::MockModule->new('main')->redefine( fourofour => 200 ); is fourofour(), 200, "can mock a function in main # need SUPER > 1.17"; done_testing(); Test-MockModule-v0.177.0/t/mock_strict.t000444000000000000 373714115711576 17257 0ustar00rootroot000000000000use warnings; use strict; use Test::More; use Test::Warnings; use Test::MockModule qw/strict/; my $mocker = Test::MockModule->new('Mockee'); is( Test::MockModule->_strict_mode(), 1, "use Test::MockModule qw/strict/; sets strict mode" ); eval { $mocker->mock( 'foo', 2 ) }; like( "$@", qr/^mock is not allowed in strict mode. Please use define or redefine at/, "mock croaks in strict mode." ); eval { $mocker->noop('foo') }; like( "$@", qr/^noop is not allowed in strict mode. Please use define or redefine at/, "noop croaks in strict mode." ); $mocker->define( 'foo', "abc" ); is( Mockee->foo, "abc", "define is allowed in strict mode." ); $mocker->redefine( 'existing_subroutine', "def" ); is( Mockee->existing_subroutine, "def", "redefine is allowed in strict mode." ); { use Test::MockModule 'nostrict'; # no strictness in this lexical scope is( Test::MockModule->_strict_mode(), 0, "nostrict turns strictness off"); $mocker->mock( 'foo', 123 ); is( Mockee->foo, 123, "mock is allowed when strict mode is turned off." ); { use Test::MockModule 'strict'; # but we are strict here again eval { $mocker->mock( 'foo', 2 ) }; like( "$@", qr/^mock is not allowed in strict mode/, "we can nest alternating strict/nostrict soooo deeply"); } $mocker->mock('foo', 456); pass("Back in a non-strict scope, the intervening strict scope didn't make ->mock() crash"); } eval { $mocker->mock( 'foo', 2 ) }; like( "$@", qr/^mock is not allowed in strict mode. Please use define or redefine at/, "Finally, back in the original scope, and we return to being strict"); use Test::MockModule 'nostrict'; # same lexical scope as we opened in, but change how strict it is $mocker->mock('foo', 94); pass("Changed to nostrict in a previously strict scope, mock() didn't crash"); done_testing(); #---------------------------------------------------------------------- package Mockee; our $VERSION; BEGIN { $VERSION = 1 } sub existing_subroutine { 1 } 1; Test-MockModule-v0.177.0/t/mockmodule.t000444000000000000 1306214115711576 17105 0ustar00rootroot000000000000use warnings; use strict; use Test::More; use Test::Warnings; use lib "t/lib"; BEGIN { use_ok('Test::MockModule') or BAIL_OUT "Could not load Test::MockModule. Giving up"; } package Test_Package; our $VERSION=1; sub listify { my ($lower, $upper) = @_; return ($lower .. $upper); } package main; # new() ok(Test::MockModule->can('new'), 'new()'); eval {Test::MockModule->new('Test::MockModule')}; like($@, qr/Cannot mock Test::MockModule/, '... cannot mock itself'); eval {Test::MockModule->new('12Monkeys')}; like($@, qr/Invalid package name/, ' ... croaks if package looks invalid'); eval {Test::MockModule->new()}; like($@, qr/Invalid package name/, ' ... croaks if package is undefined'); { { Test::MockModule->new('ExampleModule', no_auto => 1); ok(!$INC{'ExampleModule.pm'}, '... no_auto prevents module being loaded'); } my $mcgi = Test::MockModule->new('ExampleModule'); ok($INC{'ExampleModule.pm'}, '... module loaded if !$VERSION'); ok($mcgi->isa('Test::MockModule'), '... returns a Test::MockModule object'); my $mcgi2 = Test::MockModule->new('ExampleModule'); is($mcgi, $mcgi2, "... returns existing object if there's already one for the package"); # get_package() ok($mcgi->can('get_package'), 'get_package'); is($mcgi->get_package, 'ExampleModule', '... returns the package name'); # mock() ok($mcgi->can('mock'), 'mock()'); eval {$mcgi->mock(q[p-ram])}; like($@, qr/Invalid subroutine name: /, '... dies if a subroutine name is invalid'); my $orig_param = \&ExampleModule::param; $mcgi->mock('param', sub {return qw(abc def)}); my @params = ExampleModule::param(); is_deeply(\@params, ['abc', 'def'], '... replaces the subroutine with a mocked sub'); $mcgi->mock('param' => undef); @params = ExampleModule::param(); is_deeply(\@params, [], '... which is an empty sub if !defined'); $mcgi->mock(param => 'The quick brown fox jumped over the lazy dog'); my $a2z = ExampleModule::param(); is($a2z, 'The quick brown fox jumped over the lazy dog', '... or a subroutine returning the supplied value'); my $ref = [1,2,3]; $mcgi->mock(param => $ref); @params = ExampleModule::param(); is($params[0], $ref, '... given a reference, install a sub that returns said reference'); my $blessed_code = bless sub { return 'Hello World' }, 'FOO'; $mcgi->mock(param => $blessed_code); @params = ExampleModule::param(); is($params[0], 'Hello World', '... a blessed coderef is properly detected'); $mcgi->mock(Just => 'another', Perl => 'Hacker'); @params = (ExampleModule::Just(), ExampleModule::Perl()); is_deeply(\@params, ['another', 'Hacker'], '... can mock multiple subroutines at a time'); # original() ok($mcgi->can('original'), 'original()'); is($mcgi->original('param'), $orig_param, '... returns the original subroutine'); my ($warn); local $SIG{__WARN__} = sub {$warn = shift}; $mcgi->original('Vars'); like($warn, qr/ is not mocked/, "... warns if a subroutine isn't mocked"); # unmock() ok($mcgi->can('unmock'), 'unmock()'); eval {$mcgi->unmock('V@rs')}; like($@, qr/Invalid subroutine name/, '... dies if the subroutine is invalid'); $warn = ''; $mcgi->unmock('Vars'); like($warn, qr/ was not mocked/, "... warns if a subroutine isn't mocked"); $mcgi->unmock(); like($warn, qr/Nothing to unmock/, '... warns if no arguments passed to unmock'); $mcgi->unmock('param'); is(\&{"ExampleModule::param"}, $orig_param, '... restores the original subroutine'); # unmock_all() ok($mcgi->can('unmock_all'), 'unmock_all'); $mcgi->mock('Vars' => sub {1}, param => sub {2}); ok(ExampleModule::Vars() == 1 && ExampleModule::param() == 2, 'mock: can mock multiple subroutines'); my @orig = ($mcgi->original('Vars'), $mcgi->original('param')); $mcgi->unmock_all(); ok(\&ExampleModule::Vars eq $orig[0] && \&ExampleModule::param eq $orig[1], '... removes all mocked subroutines'); # is_mocked() ok($mcgi->can('is_mocked'), 'is_mocked'); ok(!$mcgi->is_mocked('param'), '... returns false for non-mocked sub'); $mcgi->mock('param', sub { return 'This sub is mocked' }); is(ExampleModule::param(), 'This sub is mocked', '... mocked params'); ok($mcgi->is_mocked('param'), '... returns true for non-mocked sub'); # noop() is(ExampleModule::cookie(), 'choc-chip', 'cookie does default behaviour'); $mcgi->noop('cookie'); ok($mcgi->is_mocked('cookie'), 'cookie is mocked using noop'); $mcgi->unmock('cookie'); $mcgi->unmock('Vars'); $mcgi->noop('cookie', 'Vars'); is(ExampleModule::cookie(), 1, 'now cookie does nothing'); is(ExampleModule::Vars(), 1, 'now Vars does nothing'); } isnt(ExampleModule::param(), 'This sub is mocked', '... params is unmocked when object goes out of scope'); # test inherited methods package Test_Parent; sub method { 1 } package Test_Child; @Test_Child::ISA = 'Test_Parent'; package main; my $test_mock = Test::MockModule->new('Test_Child', no_auto => 1); ok(Test_Child->can('method'), 'test class inherits from parent'); $test_mock->mock('method' => sub {2}); is(Test_Child->method, 2, 'mocked subclass method'); $test_mock->unmock('method'); ok(Test_Child->can('method'), 'unmocked subclass method still exists'); is(Test_Child->method, 1, 'mocked subclass method'); # test restoring non-existant functions $test_mock->mock(ISA => sub {'basic test'}); can_ok(Test_Child => 'ISA'); is(Test_Child::ISA(), 'basic test', "testing a mocked sub that didn't exist before"); $test_mock->unmock('ISA'); ok(!Test_Child->can('ISA') && $Test_Child::ISA[0] eq 'Test_Parent', "restoring an undefined sub doesn't clear out the rest of the symbols"); # ensure mocking CORE::GLOBAL works ok(Test::MockModule->new("CORE::GLOBAL")); done_testing; Test-MockModule-v0.177.0/t/pod.t000444000000000000 23514115711576 15466 0ustar00rootroot000000000000use warnings; use strict; use Test::More; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok(); Test-MockModule-v0.177.0/t/pod_coverage.t000444000000000000 35514115711576 17344 0ustar00rootroot000000000000use warnings; use strict; use Test::More; eval "use Test::Pod::Coverage 1.00"; plan skip_all => "Test::Pod::Coverage 1.00 required for testing pod coverage" if $@; all_pod_coverage_ok({also_private => [qr/^TRACE(?:F|_HERE)?|DUMP$/]}); Test-MockModule-v0.177.0/t/prototype.t000444000000000000 63614115711576 16756 0ustar00rootroot000000000000use warnings; use strict; use Test::More; use Test::Warnings; package Mockee; sub good ($$); sub good ($$) { my ( $bar, $baz ) = @_; return ( $bar + 1, $baz + 2 ); } 1; package main; use Test::MockModule; $INC{'Mockee.pm'} = 1; my $mocker = Test::MockModule->new('Mockee'); $mocker->redefine( 'good', 2 ); done_testing(); #---------------------------------------------------------------------- Test-MockModule-v0.177.0/t/redefine.t000444000000000000 143514115711576 16510 0ustar00rootroot000000000000use warnings; use strict; use Test::More; use Test::Warnings; use Test::MockModule; my $mocker = Test::MockModule->new('Mockee'); $mocker->redefine('good', 2); is( Mockee::good(), 2, 'redefine() redefines the function' ); eval { $mocker->redefine('bad', 6) }; like( $@, qr/Mockee::bad/, 'exception when redefine()ing a nonexistent function' ); my $mocker2 = Test::MockModule->new('MockeeWithDestroy'); eval { $mocker2->redefine('what', 2) }; done_testing(); #---------------------------------------------------------------------- package Mockee; our $VERSION; BEGIN { $VERSION = 1 }; sub good { 1 } #---------------------------------------------------------------------- package MockeeWithDestroy; our $VERSION; BEGIN { $VERSION = 1 }; sub DESTROY { print 'bad' if $_[0][1] }; 1; Test-MockModule-v0.177.0/t/strict_scoped_files.t000444000000000000 72014115711576 20732 0ustar00rootroot000000000000use strict; use warnings; use Test::More; use lib 't/lib'; # things we're going to mock use ScopedStrict::Mockee1; use ScopedStrict::Mockee2; # mock one of them in strict mode use ScopedStrict::StrictMocker; # this doesn't turn on strict mode, and tries to use ->mock(). It # shouldn't crash use ScopedStrict::NonStrictMocker; # yay, we didn't crash! pass "Using 'strict' mode in one module that we use didn't prevent ->mock()ing in another"; done_testing(); Test-MockModule-v0.177.0/t/lib000755000000000000 014115711576 15150 5ustar00rootroot000000000000Test-MockModule-v0.177.0/t/lib/ExampleModule.pm000444000000000000 32014115711576 20357 0ustar00rootroot000000000000package ExampleModule; use strict; use warnings; # This is an example module used by Test::MockModule for testing. sub Vars { return; } sub param { return; } sub cookie { return 'choc-chip'; } 1; Test-MockModule-v0.177.0/t/lib/ScopedStrict000755000000000000 014115711576 17556 5ustar00rootroot000000000000Test-MockModule-v0.177.0/t/lib/ScopedStrict/Mockee1.pm000444000000000000 17514115711576 21520 0ustar00rootroot000000000000package ScopedStrict::Mockee1; use strict; use warnings; sub gonna_mock_this { return "you're not going to see this" } 1; Test-MockModule-v0.177.0/t/lib/ScopedStrict/Mockee2.pm000444000000000000 21114115711576 21510 0ustar00rootroot000000000000package ScopedStrict::Mockee2; use strict; use warnings; sub also_gonna_mock_this { return "you're not going to see this either" } 1; Test-MockModule-v0.177.0/t/lib/ScopedStrict/NonStrictMocker.pm000444000000000000 32014115711576 23310 0ustar00rootroot000000000000package ScopedStrict::NonStrictMocker; use strict; use warnings; use Test::MockModule; Test::MockModule->new('ScopedStrict::Mockee2')->mock( also_gonna_mock_this => sub { "another mocked sub" } ); 1; Test-MockModule-v0.177.0/t/lib/ScopedStrict/StrictMocker.pm000444000000000000 31714115711576 22643 0ustar00rootroot000000000000package ScopedStrict::StrictMocker; use strict; use warnings; use Test::MockModule qw(strict); Test::MockModule->new('ScopedStrict::Mockee1')->redefine( gonna_mock_this => sub { "mocked sub" } ); 1;