Test-MockModule-v0.185.0000755001751001751 015177114646 15052 5ustar00runnerrunner000000000000Test-MockModule-v0.185.0/Build.PL000444001751001751 340115177114646 16501 0ustar00runnerrunner000000000000use strict; use warnings; use Module::Build; # Subclass to add a `./Build critic` action that runs Perl::Critic # against lib/ and t/ at the project's --gentle severity. Same check # as the author-mode test in t/author-perlcritic.t -- this just lets # you invoke it standalone without running the full test suite. my $class = Module::Build->subclass( class => 'Test::MockModule::Builder', code => <<'CRITIC_ACTION', sub ACTION_critic { my $self = shift; eval { require Test::Perl::Critic; 1 } or die "./Build critic requires Test::Perl::Critic. " . "Install it with: cpanm Test::Perl::Critic\n"; Test::Perl::Critic->import(-severity => 'gentle'); Test::Perl::Critic::all_critic_ok('lib', 't'); } CRITIC_ACTION ); my $builder = $class->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.4234', }, requires => { 'perl' => 5.006, 'Carp' => 0, 'Scalar::Util' => 0, 'SUPER' => '1.20', }, test_requires => { 'Test::More' => 0.88, 'Test::Warnings' => 0, 'Test::Exception' => 0, 'Class::Load' => 0, 'Moose' => 0, 'Mouse' => 0, }, add_to_cleanup => [ 'Test-MockModule-*', 'cover_db', '*.rpm', '*.deb', ] ); $builder->create_build_script(); Test-MockModule-v0.185.0/Changes000444001751001751 2343515177114646 16531 0ustar00runnerrunner000000000000## 0.185.0 — 2026-05-07 ## What's Changed * Fix GH #83: Reverts to pre v0.181.0 behavior. new() returns singleton-per-package by default again. pass distinct => 1 for v0.181's fresh-object-per-call behavior. * New: Test::MockModule->original_for($pkg, $sub) — call the original sub from inside a mock closure without capturing $mock. **Full Changelog**: https://github.com/geofffranks/test-mockmodule/compare/0.184.0...0.185.0 ## 0.184.0 — 2026-05-04 ## What's Changed * fix: restore noop() to return 1 for backward compatibility by @Koan-Bot in https://github.com/geofffranks/test-mockmodule/pull/80 **Full Changelog**: https://github.com/geofffranks/test-mockmodule/compare/0.183.0...0.184.0 ## 0.183.0 — 2026-05-01 ## What's Changed * Followup to PR #77 by @geofffranks in https://github.com/geofffranks/test-mockmodule/pull/79 * Thanks @Koan-Bot @atoomic for providing a fix for #48 ! **Full Changelog**: https://github.com/geofffranks/test-mockmodule/compare/0.181.0...0.183.0 ## 0.182.0 — 2026-05-01 ## What's Changed * Provide a global way to assure nostrict ever happens by @toddr in https://github.com/geofffranks/test-mockmodule/pull/66 * Fix define() + unmock() bug, CI modernization, prototype tests by @Koan-Bot in https://github.com/geofffranks/test-mockmodule/pull/69 * feat: mocked_subs() introspection + original() fix (GH #52, #42) by @Koan-Bot in https://github.com/geofffranks/test-mockmodule/pull/70 * fix: align noop() return value with mock_all(noop=>1) by @Koan-Bot in https://github.com/geofffranks/test-mockmodule/pull/71 * fix: add strict mode guard to mock_all() by @Koan-Bot in https://github.com/geofffranks/test-mockmodule/pull/72 * ci: add Perl 5.40 and 5.42 to test matrix by @Koan-Bot in https://github.com/geofffranks/test-mockmodule/pull/75 * docs: fix POD typos and syntax errors by @Koan-Bot in https://github.com/geofffranks/test-mockmodule/pull/76 * perf: optimize _strict_mode() with exists check by @Koan-Bot in https://github.com/geofffranks/test-mockmodule/pull/73 * fix: skip special Perl subs in mock_all() by @Koan-Bot in https://github.com/geofffranks/test-mockmodule/pull/74 ## New Contributors * @Koan-Bot made their first contribution in https://github.com/geofffranks/test-mockmodule/pull/69 **Full Changelog**: https://github.com/geofffranks/test-mockmodule/compare/0.180.0...0.182.0 ## 0.181.0 — 2026-04-30 ## What's Changed * Provide a global way to assure nostrict ever happens by @toddr in https://github.com/geofffranks/test-mockmodule/pull/66 * Fix define() + unmock() bug, CI modernization, prototype tests by @Koan-Bot in https://github.com/geofffranks/test-mockmodule/pull/69 * feat: mocked_subs() introspection + original() fix (GH #52, #42) by @Koan-Bot in https://github.com/geofffranks/test-mockmodule/pull/70 * fix: align noop() return value with mock_all(noop=>1) by @Koan-Bot in https://github.com/geofffranks/test-mockmodule/pull/71 * fix: add strict mode guard to mock_all() by @Koan-Bot in https://github.com/geofffranks/test-mockmodule/pull/72 * ci: add Perl 5.40 and 5.42 to test matrix by @Koan-Bot in https://github.com/geofffranks/test-mockmodule/pull/75 * docs: fix POD typos and syntax errors by @Koan-Bot in https://github.com/geofffranks/test-mockmodule/pull/76 * perf: optimize _strict_mode() with exists check by @Koan-Bot in https://github.com/geofffranks/test-mockmodule/pull/73 * fix: skip special Perl subs in mock_all() by @Koan-Bot in https://github.com/geofffranks/test-mockmodule/pull/74 ## Moose & Mouse meta-class aware mocking (#55) `Test::MockModule` now registers mocks on the target's Moose/Mouse meta-class via `add_method` (in addition to the symbol table) when the target uses `Class::MOP::Class` or `Mouse::Meta::Class`. This fixes: - Role `requires` checks failing after mocking (incl. dynamic `apply_all_roles`). - `The method 'foo' was not found in the inheritance hierarchy` errors when loading a subclass with `around foo` after mocking the parent's `foo`. `unmock` restores via `add_method`, or `remove_method` (Moose) / internal cache purge (Mouse) for inherited originals. Immutable classes fall back to symbol-table-only with a one-time warning. Moo is not supported (no MOP). No public API change. Moose/Mouse/Class::MOP are not auto-loaded for non-Moose users. **Full Changelog**: https://github.com/geofffranks/test-mockmodule/compare/0.181.0...0.182.0 ## New Contributors * @Koan-Bot made their first contribution in https://github.com/geofffranks/test-mockmodule/pull/69 **Full Changelog**: https://github.com/geofffranks/test-mockmodule/compare/0.180.0...0.181.0 ## 0.180.0 — 2025-07-03 ## What's Changed * Remove Software::License from runtime dependencies by @bbrtj in https://github.com/geofffranks/test-mockmodule/pull/68 ## New Contributors * @bbrtj made their first contribution in https://github.com/geofffranks/test-mockmodule/pull/68 **Full Changelog**: https://github.com/geofffranks/test-mockmodule/compare/0.179.0...0.180.0 # NOTE: Automated tracking resumed 2026-05-04. See https://github.com/geofffranks/test-mockmodule/releases for any older entries pre-0.180.0. # Revision history for Test::MockModule pre Aug 29, 2024 v0.179.0 - 82881df - Bump Module::Build requirement by @atoomic in #65 v0.178.0 - 6724a30 - Simplify CI workflow - Nicolas R - 1801372 - Multiple improvements - Nicolas R - e97e316 - Add protection to _replace_sub - Nicolas R 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.185.0/LICENSE000444001751001751 4673615177114646 16254 0ustar00runnerrunner000000000000This software is copyright (c) 2026 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) 2026 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. 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, see . 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 Moe Ghoul, President of Vice That's all there is to it! --- The Perl Artistic License 1.0 --- This software is Copyright (c) 2026 by Current Maintainer: Geoff Franks & Original Author: Simon Flack . 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-MockModule-v0.185.0/MANIFEST000444001751001751 155315177114646 16344 0ustar00runnerrunner000000000000Build.PL Changes lib/Test/MockModule.pm LICENSE MANIFEST This list of files MANIFEST.SKIP README.md t/author-perlcritic.t t/chaining.t t/define.t t/distinct_opt_in.t t/gh_83_no_leak.t t/global_strict_mode.t t/import_options.t t/inheritance.t t/introspection.t t/lib/ExampleModule.pm t/lib/Issue55/MooseAroundChild.pm t/lib/Issue55/MooseAroundChildOrig.pm t/lib/Issue55/MooseAroundParent.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_all.t t/mock_strict.t t/mockmodule.t t/moose_around.t t/moose_immutable.t t/moose_meta_for.t t/moose_multi.t t/moose_redefine.t t/moose_role_requires.t t/moose_unmock.t t/mouse_basic.t t/mouse_multi.t t/multiple_objects.t t/original_for.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.185.0/MANIFEST.SKIP000444001751001751 253715177114646 17114 0ustar00runnerrunner000000000000 #!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 # Avoid maintainer-only docs ^RELEASING\.md ^docs\b Test-MockModule-v0.185.0/META.json000444001751001751 317215177114646 16633 0ustar00runnerrunner000000000000{ "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.4234", "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.4234" } }, "runtime" : { "requires" : { "Carp" : "0", "SUPER" : "1.20", "Scalar::Util" : "0", "perl" : "5.006" } }, "test" : { "requires" : { "Class::Load" : "0", "Moose" : "0", "Mouse" : "0", "Test::Exception" : "0", "Test::More" : "0.88", "Test::Warnings" : "0" } } }, "provides" : { "Test::MockModule" : { "file" : "lib/Test/MockModule.pm", "version" : "v0.185.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.185.0", "x_serialization_backend" : "JSON::PP version 4.16" } Test-MockModule-v0.185.0/META.yml000444001751001751 206015177114646 16456 0ustar00runnerrunner000000000000--- abstract: 'Override subroutines in a module for unit testing' author: - 'Current Maintainer: Geoff Franks ' - 'Original Author: Simon Flack ' build_requires: Class::Load: '0' Moose: '0' Mouse: '0' Test::Exception: '0' Test::More: '0.88' Test::Warnings: '0' configure_requires: Module::Build: '0.4234' 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-MockModule provides: Test::MockModule: file: lib/Test/MockModule.pm version: v0.185.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.185.0 x_serialization_backend: 'CPAN::Meta::YAML version 0.018' Test-MockModule-v0.185.0/README.md000444001751001751 77515177114646 16457 0ustar00runnerrunner000000000000# 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.185.0/lib000755001751001751 015177114646 15620 5ustar00runnerrunner000000000000Test-MockModule-v0.185.0/lib/Test000755001751001751 015177114646 16537 5ustar00runnerrunner000000000000Test-MockModule-v0.185.0/lib/Test/MockModule.pm000444001751001751 10562615177114646 21343 0ustar00runnerrunner000000000000package Test::MockModule; use warnings; use strict qw/subs vars/; use vars qw/$VERSION/; use Scalar::Util qw/reftype refaddr weaken/; use Carp; use SUPER; # This is now auto-updated at release time by the github action $VERSION = '0.185.0'; our $GLOBAL_STRICT_MODE; sub import { my ( $class, @args ) = @_; # default if no args $^H{'Test::MockModule/STRICT_MODE'} = 0; foreach my $arg (@args) { if($arg eq 'global-strict' ) { $GLOBAL_STRICT_MODE=1; $^H{'Test::MockModule/STRICT_MODE'} = 1; } elsif ( $arg eq 'strict' ) { $^H{'Test::MockModule/STRICT_MODE'} = 1; } elsif ( $arg eq 'nostrict' ) { $GLOBAL_STRICT_MODE && die "use Test::MockModule qw(nostrict) is illegal when GLOBAL_STRICT_MODE is being enforced"; $^H{'Test::MockModule/STRICT_MODE'} = 0; } else { carp "Test::MockModule unknown import option '$arg'"; } } return; } sub _strict_mode { my $depth = 0; while(my @fields = caller($depth++)) { my $hints = $fields[10]; if($hints && exists $hints->{'Test::MockModule/STRICT_MODE'}) { $GLOBAL_STRICT_MODE && !$hints->{'Test::MockModule/STRICT_MODE'} && die "use Test::MockModule qw(nostrict) is illegal when GLOBAL_STRICT_MODE is being enforced"; return $hints->{'Test::MockModule/STRICT_MODE'}; } } return 0; } # Per-sub stack of live mock layers. Each entry: # { id, orig, installed, is_meta, meta_orig } # # id = refaddr of the mock object owning the layer. # orig = coderef at *Pkg::sub immediately before this layer was pushed # (or undef if no sub existed). On mid-stack unmock, the popped # entry's orig cascades down to the next layer so the eventual # stack-empty restore sees the right "pre-mock" state. # installed = coderef this layer most recently installed. Updated on # re-mock by the same object so that an above-layer unmock, # or a mid-stack splice, can re-install the latest coderef. # is_meta = true if this layer was pushed while the package's metaclass # was mutable (Moose Class::MOP::Class or Mouse::Meta::Class). # Drives whether unmock restores via meta->add_method or via # the symbol table. # meta_orig = Method object (or undef) returned by $meta->get_method($name) # immediately before this layer was pushed; only meaningful # when is_meta is true. Cascaded on mid-stack unmock the same # way as orig, so the bottom-of-stack restore can use the # correct pre-any-mock meta state. my %mock_subs; # Per-package weak registry: keeps the singleton-per-package behavior # that was the default prior to v0.181 (and the documented contract for # the `$mock->original` from-inside-closure pattern). new() returns # the existing object for a package if one is alive; weak ref so a # cleanly-destroyed mock releases the slot naturally. Pass # `distinct => 1` to opt out and get a fresh object per call (the # v0.181+ GH #48 behavior). my %singleton; sub new { my ($class, $package, %args) = @_; croak "Cannot mock $package" if $package && $class && $package eq $class; unless (_valid_package($package)) { $package = 'undef' unless defined $package; croak "Invalid package name $package"; } # Auto-load the package BEFORE consulting the singleton cache. # Otherwise a singleton seeded by an earlier `no_auto => 1` caller # would silently deny later default-mode callers the module load # they expect from `new()` (Koan-Bot review on PR #85). 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; } if (!$args{distinct} && $singleton{$package}) { TRACE("Reusing singleton MockModule object for $package"); return $singleton{$package}; } TRACE("Creating MockModule object for $package"); my $self = bless { _package => $package, _mocked => {}, }, $class; if (!$args{distinct}) { $singleton{$package} = $self; weaken($singleton{$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) = (@_); my @mocks_copy = @mocks; while ( my ($name, $value) = splice @mocks_copy, 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(@mocks); } sub define { my ($self, @mocks) = @_; my @mocks_copy = @mocks; while ( my ($name, $value) = splice @mocks_copy, 0, 2 ) { my $sub_name = $self->_full_name($name); my $coderef = *{$sub_name}{'CODE'}; if ('CODE' eq ref $coderef) { croak "$sub_name exists!"; } } my $ret = $self->_mock(@mocks); # Mark defined subs so _mock() can update _orig on redefine (GH #64) while ( my ($name, $value) = splice @mocks, 0, 2 ) { $self->{_defined}{$name} = 1; } return $ret; } sub mock { my ($self, @mocks) = @_; 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; # Lazily load Class::MOP::Method once if the target is a Moose class. # Class::MOP is already loaded transitively whenever the target uses Moose, # so this require is essentially a hash-lookup; we still hoist it out of # the per-name install loop for clarity. { my $meta = _meta_for($self->{_package}); require Class::MOP::Method if $meta && $meta->isa('Class::MOP::Class'); } 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); my $meta = _meta_for($self->{_package}); my $can_meta = $meta && !$meta->is_immutable; if (!$self->{_mocked}{$name}) { TRACE("Storing existing $sub_name"); $self->{_mocked}{$name} = 1; my $orig = defined &{$sub_name} ? \&$sub_name : undef; $self->{_orig}{$name} = $orig; # get_method() can return an empty list (rather than undef) for # methods that aren't locally defined; force scalar context so # the anonymous hash gets exactly one value here. my $meta_orig = $can_meta ? scalar $meta->get_method($name) : undef; $mock_subs{$sub_name} ||= []; push @{$mock_subs{$sub_name}}, { id => refaddr($self), orig => $orig, installed => $code, is_meta => $can_meta ? 1 : 0, meta_orig => $meta_orig, }; } else { my $is_redefine_after_define = $self->{_defined}{$name}; delete $self->{_defined}{$name} if $is_redefine_after_define; # Re-mock by same object: update our stack entry's installed # coderef so an above-layer unmock cascades to the correct # (current) coderef. GH #64: when this is a redefine of a sub # created via define(), also update _orig and the entry's orig # so unmock() restores the originally-defined sub. Use this # layer's PRIOR installed coderef rather than \&{$sub_name} -- # with stacking, the symbol may currently hold another mock # object's installed coderef rather than ours. if (my $stack = $mock_subs{$sub_name}) { my $my_id = refaddr($self); for my $entry (@$stack) { if ($entry->{id} == $my_id) { if ($is_redefine_after_define) { my $prior = $entry->{installed}; $self->{_orig}{$name} = $prior; $entry->{orig} = $prior; } $entry->{installed} = $code; last; } } } } if ($can_meta) { TRACE("Installing mocked $sub_name via meta->add_method"); if ($meta->isa('Class::MOP::Class')) { $meta->add_method( $name, Class::MOP::Method->wrap( $code, name => $name, package_name => $self->{_package}, ), ); } else { # Mouse: add_method accepts a plain coderef and wraps internally $meta->add_method($name, $code); } } else { if ($meta && $meta->is_immutable && !$self->{_warned_immutable}{$name}) { $self->{_warned_immutable}{$name} = 1; carp sprintf( "Test::MockModule: package %s is immutable; mocking %s via symbol table only. " . "Moose role/modifier resolution will not see the mock. " . "Call %s->meta->make_mutable before mocking if MOP-aware behavior is needed.", $self->{_package}, $name, $self->{_package}, ); } TRACE("Installing mocked $sub_name"); _replace_sub($sub_name, $code); } } return $self; } # Install $entry->{installed} at *Pkg::$name, using the meta path when the # entry was originally pushed via meta and the metaclass is currently mutable; # otherwise fall back to the symbol table. sub _install_layer { my ($self, $sub_name, $name, $entry) = @_; my $meta = _meta_for($self->{_package}); if ($entry->{is_meta} && $meta && !$meta->is_immutable) { if ($meta->isa('Class::MOP::Class')) { $meta->add_method( $name, Class::MOP::Method->wrap( $entry->{installed}, name => $name, package_name => $self->{_package}, ), ); } else { $meta->add_method($name, $entry->{installed}); } } else { _replace_sub($sub_name, $entry->{installed}); } } # Restore the pre-any-mock state for the bottom-most (and now only) layer # being popped. Uses the entry's meta_orig when the layer was pushed via # meta, otherwise its symbol-table orig coderef. sub _restore_pre_mock { my ($self, $sub_name, $name, $entry) = @_; my $meta = _meta_for($self->{_package}); my $can_meta = $meta && !$meta->is_immutable; if ($entry->{is_meta} && $can_meta) { my $orig_method = $entry->{meta_orig}; if (defined $orig_method) { TRACE("Restoring original $sub_name via meta->add_method"); # Older Mouse versions require a coderef and reject a # Mouse::Meta::Method object; extract the body for Mouse. # Moose accepts either a coderef or a Class::MOP::Method. my $arg = $meta->isa('Mouse::Meta::Class') ? (ref($orig_method) eq 'CODE' ? $orig_method : $orig_method->body) : $orig_method; $meta->add_method($name, $arg); } else { TRACE("Removing mocked $sub_name from meta (was inherited or absent)"); if ($meta->can('remove_method')) { $meta->remove_method($name); } else { # Mouse::Meta::Class has no remove_method; purge the # internal methods cache entry directly so that # get_method() no longer finds the mocked entry. delete $meta->{methods}{$name}; } # remove_method does not always clear the symbol table. # When the layer captured a symbol-table orig (e.g. an earlier # layer pushed via the symbol table while meta was immutable, # then make_mutable purged the cached meta entry), restore that # coderef so the method continues to resolve. When orig is # undef the slot is cleared, so direct calls fall through to # AUTOLOAD/parent. _replace_sub($sub_name, $entry->{orig}); } } else { # Either the layer was a symbol-table push, or meta became immutable # between mock and unmock. Fall back to the captured orig coderef. _replace_sub($sub_name, $entry->{orig}); } } 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 mock_all { my ($self, %opts) = @_; croak "mock_all is not allowed in strict mode. Please use redefine" if $self->_strict_mode(); my $package = $self->{_package}; my @subs; { no strict 'refs'; ## no critic (TestingAndDebugging::ProhibitNoStrict) @subs = sort grep { defined &{"${package}::$_"} } keys %{"${package}::"}; } my $make_handler = exists $opts{handler} ? sub { $opts{handler} } : $opts{noop} ? sub { sub { 1 } } : sub { my $n = shift; sub { croak "$n was not mocked" } }; # Skip special Perl subs that should never be blindly mocked: # - Phase blocks (BEGIN, END, INIT, CHECK, UNITCHECK) run at compile/exit time # - DESTROY is called during object cleanup # - AUTOLOAD handles missing method dispatch # - import handles use/import semantics # - Overload subs start with '(' (e.g. '(""', '(+', '(==') my %_skip = map { $_ => 1 } qw( import DESTROY BEGIN END INIT CHECK UNITCHECK AUTOLOAD ); my @to_mock; for my $name (@subs) { next if $_skip{$name}; next if $name =~ /^\(/; # overload subs next if $self->{_mocked}{$name}; push @to_mock, $name, $make_handler->("${package}::${name}"); } return $self->_mock(@to_mock) if @to_mock; return $self; } sub original { my ($self, $name) = @_; carp 'Please provide a valid function name' unless _valid_subname($name); unless ($self->{_mocked}{$name}) { # GH #42: when not mocked, return the actual sub instead of warning my $sub_name = _full_name($self, $name); return \&$sub_name if defined &{$sub_name}; return $self->{_package}->super($name); } return defined $self->{_orig}{$name} ? $self->{_orig}{$name} : $self->{_package}->super($name); } # Class-method counterpart to $mock->original(). Takes strings, returns # the truly-original coderef from the per-package registry (or the live # sub if not mocked). Lets user closures reach the original sub without # capturing $mock -- the closure-capture pattern that drives the GH #83 # DESTROY-leak under `distinct => 1` mode. sub original_for { my ($class, $package, $name) = @_; croak "Invalid package name " . (defined $package ? $package : 'undef') unless _valid_package($package); croak 'Please provide a valid function name' unless _valid_subname($name); my $sub_name = "${package}::${name}"; my $stack = $mock_subs{$sub_name}; if ($stack && @$stack) { # Bottom-of-stack orig is the truly-original. May be undef when # the sub was created via define() -- that is expected. Falling # through to \&$sub_name would hand back the active mock (an # infinite-recursion footgun for closures wrapping their orig). return $stack->[0]{orig}; } no strict 'refs'; ## no critic (TestingAndDebugging::ProhibitNoStrict) return \&$sub_name if defined &{$sub_name}; return; } sub unmock { my ( $self, @names ) = @_; carp 'Nothing to unmock' unless @names; for my $name (@names) { 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"); my $stack = $mock_subs{$sub_name}; if ($stack) { my $my_id = refaddr($self); my $idx; for my $i (0 .. $#$stack) { if ($stack->[$i]{id} == $my_id) { $idx = $i; last; } } if (defined $idx) { if ($idx == $#$stack) { # Top of stack: restore the prior layer's installed # coderef (via meta or symbol as the layer dictates), # or fully restore the pre-mock state if no prior # layer remains. my $popped = pop @$stack; if (@$stack) { $self->_install_layer($sub_name, $name, $stack->[-1]); } else { $self->_restore_pre_mock($sub_name, $name, $popped); } } else { # Mid-stack: cascade our orig (and meta_orig, when the # layer above also used the meta path) down to the next # entry so a later stack-empty restore sees the correct # pre-any-mock state. Then remove ourselves and re-install # the new top's installed coderef -- the symbol/meta may # currently hold OUR installed coderef if we re-mocked # after a higher layer was pushed, so we must explicitly # restore the layer that should now be active. $stack->[$idx + 1]{orig} = $stack->[$idx]{orig}; $stack->[$idx + 1]{meta_orig} = $stack->[$idx]{meta_orig} if $stack->[$idx + 1]{is_meta}; splice @$stack, $idx, 1; $self->_install_layer($sub_name, $name, $stack->[-1]); } } else { # Defensive: not found in stack (shouldn't happen). _replace_sub($sub_name, $self->{_orig}{$name}); } delete $mock_subs{$sub_name} unless @$stack; } else { _replace_sub($sub_name, $self->{_orig}{$name}); } delete $self->{_mocked}{$name}; delete $self->{_orig}{$name}; delete $self->{_defined}{$name}; delete $self->{_warned_immutable}{$name}; } return $self; } sub unmock_all { my $self = shift; foreach my $name (keys %{$self->{_mocked}}) { $self->unmock($name); } return; } sub is_mocked { my ($self, $name) = @_; return unless _valid_subname($name); return $self->{_mocked}{$name}; } sub mocked_subs { my $self = shift; my @subs = sort keys %{$self->{_mocked}}; return @subs; } sub _full_name { my ($self, $sub_name) = @_; return sprintf( "%s::%s", $self->{_package}, $sub_name ); } sub _valid_package { my $name = shift; return unless defined $name && length $name; return $name =~ /^[a-z_]\w*(?:::\w+)*$/i; } sub _valid_subname { my $name = shift; return unless defined $name && length $name; return $name =~ /^[a-z_]\w*$/i; } sub _meta_for { my $package = shift; return unless defined $package && length $package; return unless $package->can('meta'); my $meta = eval { $package->meta }; return unless ref $meta; return $meta if $meta->isa('Class::MOP::Class'); # Moose return $meta if $meta->isa('Mouse::Meta::Class'); # Mouse return; } sub _replace_sub { my ($sub_name, $coderef) = @_; no warnings qw< redefine 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 my $slot_name (qw(ARRAY FORMAT HASH IO SCALAR)) { next unless defined $symbols{$sub}; next unless defined(my $elem = *{$symbols{$sub}}{$slot_name}); $slot{$slot_name} = $elem; } # clear the symbol table entry for the subroutine undef *$sub_name; # restore everything except the code slot return unless scalar 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 { ... }); } # Assure strict is ALWAYS used. use Test::MockModule 'global-strict'; # 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 GLOBAL STRICT MODE If your particular test suite needs to assure that no developer ever accidentally turns off strict, this is the mode for you use Test::MockModule 'global-strict'; Setting this mode will cause any later invocation of nostrict to fail on compile. Further, any use of mock at runtime will die if the 'nostrict' mode was invoked prior to global-strict being initially set. While this seems like it might be overkill, this can be important as the number of simultaneous developers increases over time. =head1 METHODS =over 4 =item new($package[, %options]) Returns a singleton-per-package mock object. Two calls to C<< Test::MockModule->new('Foo') >> return the same object as long as the first one is still alive; this preserves the long-standing pre-v0.181 contract that the documented C<< $mock->original >> from-inside-closure pattern depends on (see GH #83). Pass C<< distinct => 1 >> to opt into the v0.181 GH #48 semantics -- each call returns a fresh object, multiple mock objects coexist on the same package, and the per-sub stack handles multi-mock layering: my $m1 = Test::MockModule->new('Module::Name', distinct => 1); my $m2 = Test::MockModule->new('Module::Name', distinct => 1); # $m1 and $m2 are independent. Tests that need this layering must # opt in explicitly. Under C mode the most recent C/C call wins regardless of stack position; when a mock object is destroyed, the layer below it on the stack is reactivated; when all mock objects for a subroutine are destroyed, the original subroutine is restored. 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); B: a closure that captures C<$mock> (typically by calling C<< $mock->original(...) >> inside the mock body) prevents C from firing when C<$mock> goes out of scope, so the mock leaks past its lexical scope. The default (singleton) mode makes this leak harmless by re-using the same object on subsequent C calls. Under C<< distinct => 1 >>, prefer the class-method form C<< Test::MockModule->original_for($pkg, $sub) >> from inside closures so they capture only strings, or capture C<< $mock->original(...) >> in a lexical B calling C. =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 mocked_subs() Returns a sorted list of the subroutine names that are currently mocked for this module. Useful for debugging complex test setups. my $mock = Test::MockModule->new('Module::Name'); $mock->mock('foo', sub { 1 }); $mock->mock('bar', sub { 2 }); my @mocked = $mock->mocked_subs; # ('bar', 'foo') =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. If the subroutine is not currently mocked, returns the existing subroutine directly instead of warning. This makes it safe to call C before or after mocking. 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"); # capture the original before mocking to avoid closing over $mock my $orig_get_path = $mock->original("get_path_for"); # replace all calls to get_path_for using a different argument $mock->redefine("get_path_for", sub { return $orig_get_path->("/my/custom/path"); }); # or my $orig_get_path = $mock->original("get_path_for"); $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 $orig_get_path->("/my/custom/path"); } else { # preserve the original arguments return $orig_get_path->($path, @_); } }); =item original_for($package, $subroutine) Class-method counterpart to C. Returns the truly-original coderef for C<$package::$subroutine> from the per-package registry, or the live sub via the symbol table if not currently mocked. Returns C if no sub by that name exists. Croaks on invalid package or sub names. The motivating use case is letting closures reach the original sub without capturing C<$mock> -- the closure-capture pattern that drives the GH #83 leak under C<< distinct => 1 >> mode: my $mock = Test::MockModule->new('MyModule', distinct => 1); $mock->mock('greet', sub { # Closure captures only strings -- $mock can be GC'd at scope end return Test::MockModule ->original_for('MyModule', 'greet')->(@_) . '_suffix'; }); For stacked mocks, returns the truly-original (pre-any-mock) coderef, not the layer below. =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 that returns C<1>. Handy for mocking methods you want to ignore! The C<1> return value is part of the public contract of this method (see GH #81) -- callers in the wild rely on it being truthy. # Neuter a list of methods in one go $module->noop('purge', 'updated'); =item mock_all(%options) Mocks all subroutines in the target package that are not already mocked. By default, each mocked subroutine will die when called, making it easy to catch unexpected calls during testing. my $module = Test::MockModule->new('Foo'); $module->mock_all(); Foo->bar(); # dies: "Foo::bar was not mocked" The C subroutine is always skipped. Options: =over 4 =item noop =E 1 Mock all subroutines with a no-op sub that returns C<1> instead of dying. This is consistent with C. $module->mock_all(noop => 1); Foo->bar(); # returns 1 =item handler =E \&coderef Provide a custom handler for all mocked subroutines. $module->mock_all(handler => sub { warn "unexpected call" }); =back Returns the current C object for chaining. =back =over 4 =item TRACE A stub for Log::Trace =item DUMP A stub for Log::Trace =back =head1 MOOSE AND MOUSE SUPPORT When the target package's metaclass is a C (Moose) or C (Mouse), C registers mocks with the meta-object via C in addition to installing them in the symbol table. This makes mocked methods visible to: =over 4 =item * Moose role C checks (including dynamic role application via L). =item * Method modifier resolution (C, C, C) on subclasses loaded after the mock is installed. =item * Other MOP-driven introspection that walks C / C. =back C reverses the registration: if the original method existed on the class itself, it is restored via C; if the method was inherited (or absent) before mocking, it is removed via C so inheritance lookup falls back to the parent. For Mouse classes (which lack a public C on C), the mock entry is purged from the meta-class's internal method cache directly to achieve the same effect. If the target class is immutable (C<< $meta->is_immutable >> is true), C falls back to symbol-table-only behavior and emits a warning. Call C<< Pkg->meta->make_mutable >> before mocking if you need MOP-aware behavior on an immutable class. =head2 Moo and other MOP-less object systems L, L, and L are not detected and not specially handled. Mocks on Moo classes still work for direct calls but will not be seen by role-application or method-modifier resolution for classes that consume Moo roles. As a workaround, mock the underlying package directly with C 1> and explicit load ordering, or convert the affected class to Moose. =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.185.0/t000755001751001751 015177114646 15315 5ustar00runnerrunner000000000000Test-MockModule-v0.185.0/t/author-perlcritic.t000444001751001751 70615177114646 21262 0ustar00runnerrunner000000000000#!perl use strict; use warnings; use Test::More; # Author/develop test: runs Perl::Critic against lib/ and t/ at the # project's --gentle severity. Skipped on machines without # Test::Perl::Critic so random CPAN testers do not fail because of an # author-only dep. eval { require Test::Perl::Critic }; plan skip_all => 'Test::Perl::Critic not installed (author dep)' if $@; Test::Perl::Critic->import(-severity => 'gentle'); all_critic_ok('lib', 't'); Test-MockModule-v0.185.0/t/chaining.t000444001751001751 134515177114646 17422 0ustar00runnerrunner000000000000use 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; ## no critic (Modules::RequireFilenameMatchesPackage) our $VERSION; BEGIN { $VERSION = 1 } sub good { 1 } sub to_redefine { 1 } 1; Test-MockModule-v0.185.0/t/define.t000444001751001751 315015177114646 17070 0ustar00runnerrunner000000000000use 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.' ); # GH #64: define() then redefine() then unmock() should restore the defined sub { my $m = Test::MockModule->new('Mockee64', no_auto => 1); $m->define( 'wrapper', sub { 'defined_value' } ); is( Mockee64::wrapper(), 'defined_value', 'define() installs the sub' ); $m->redefine( 'wrapper', sub { 'redefined_value' } ); is( Mockee64::wrapper(), 'redefined_value', 'redefine() replaces the defined sub' ); $m->unmock( 'wrapper' ); is( Mockee64::wrapper(), 'defined_value', 'unmock() restores the originally defined sub (GH #64)' ); } done_testing(); #---------------------------------------------------------------------- package Mockee; ## no critic (Modules::RequireFilenameMatchesPackage) our $VERSION; BEGIN { $VERSION = 1 } sub existing_subroutine { 1 } 1; package Mockee64; ## no critic (Modules::RequireFilenameMatchesPackage) our $VERSION; BEGIN { $VERSION = 1 } 1; Test-MockModule-v0.185.0/t/distinct_opt_in.t000444001751001751 1076315177114646 21057 0ustar00runnerrunner000000000000use warnings; use strict; use Test::More; use Test::MockModule; use Scalar::Util qw(refaddr); package Tgt::DistinctOptIn; ## no critic (Modules::RequireFilenameMatchesPackage) our $VERSION = 1; sub greet { 'hello' } package main; ## no critic (Modules::RequireFilenameMatchesPackage) # 1. Default behavior: singleton-per-package (pre-v0.181, GH #83 fix) { my $a = Test::MockModule->new('Tgt::DistinctOptIn'); my $b = Test::MockModule->new('Tgt::DistinctOptIn'); is(refaddr($a), refaddr($b), 'default new(): singleton-per-package (pre-v0.181 behavior)'); } # 2. distinct => 1: fresh object per call (GH #48 opt-in) { my $a = Test::MockModule->new('Tgt::DistinctOptIn', distinct => 1); my $b = Test::MockModule->new('Tgt::DistinctOptIn', distinct => 1); isnt(refaddr($a), refaddr($b), 'distinct => 1: fresh object per call (GH #48 opt-in)'); } # 3. distinct => 1 enables independent multi-mock layering { package Tgt::DistinctMulti; ## no critic (Modules::RequireFilenameMatchesPackage) our $VERSION = 1; sub foo { 'orig_foo' } sub bar { 'orig_bar' } package main; ## no critic (Modules::RequireFilenameMatchesPackage) my $m1 = Test::MockModule->new('Tgt::DistinctMulti', distinct => 1); $m1->mock('foo', sub { 'm1_foo' }); is(Tgt::DistinctMulti::foo(), 'm1_foo', 'm1 mocks foo'); { my $m2 = Test::MockModule->new('Tgt::DistinctMulti', distinct => 1); $m2->mock('bar', sub { 'm2_bar' }); is(Tgt::DistinctMulti::foo(), 'm1_foo', 'foo still mocked by m1'); is(Tgt::DistinctMulti::bar(), 'm2_bar', 'bar mocked by m2'); } is(Tgt::DistinctMulti::bar(), 'orig_bar', 'bar restored after m2 destroyed'); $m1->unmock_all; is(Tgt::DistinctMulti::foo(), 'orig_foo', 'foo restored after m1 unmock'); } # 4. Singleton-default mode keeps the same object across run scopes, # which is exactly what makes the documented `$mock->original` from- # inside-closure pattern work without leaking. { package Tgt::DistinctRun; ## no critic (Modules::RequireFilenameMatchesPackage) our $VERSION = 1; sub greet { 'run' } package main; ## no critic (Modules::RequireFilenameMatchesPackage) my @results; my $run = sub { my ($label) = @_; my $mock = Test::MockModule->new('Tgt::DistinctRun', no_auto => 1); $mock->mock('greet', sub { return $mock->original('greet')->() . "_$label"; }); push @results, Tgt::DistinctRun::greet(); }; $run->('first'); $run->('second'); is_deeply \@results, ['run_first', 'run_second'], 'closure-captures-$mock pattern works under singleton default'; Test::MockModule->new('Tgt::DistinctRun', no_auto => 1)->unmock_all; } # 5. Mixing distinct and non-distinct: distinct always returns fresh, # non-distinct returns the existing singleton if alive. { my $s = Test::MockModule->new('Tgt::DistinctOptIn'); my $d = Test::MockModule->new('Tgt::DistinctOptIn', distinct => 1); isnt(refaddr($s), refaddr($d), 'distinct => 1 returns a fresh object even when singleton exists'); my $s2 = Test::MockModule->new('Tgt::DistinctOptIn'); is(refaddr($s), refaddr($s2), 'subsequent default new() still returns the singleton'); } # 6. Regression for Koan-Bot review on PR #85: a singleton seeded by an # earlier `no_auto => 1` call must NOT deny later default-mode # callers the module-load they expect. The autoload check runs # before the singleton cache is consulted. { # Use a fresh package name so no prior subtest seeded the singleton. # The package has no $VERSION and no .pm on disk; a default new() # call would normally die trying to require it. We seed a singleton # with no_auto => 1, then verify the second default-mode call still # tries to load the module. my $pkg = 'Tgt::AutoloadAfterSingleton'; { my $first = Test::MockModule->new($pkg, no_auto => 1); ok($first, "no_auto seed: singleton created without loading $pkg"); } # Second call WITHOUT no_auto should attempt the require and die # because the package has no .pm. If the autoload-bypass bug is # present, this would silently return the cached object instead. my $err; eval { Test::MockModule->new($pkg) }; $err = $@; # require turns Pkg::Sub into Pkg/Sub.pm in its error message (my $path = $pkg) =~ s{::}{/}g; like($err, qr/Can't locate \Q$path\E\.pm/, 'default new() after no_auto-seed singleton still attempts autoload'); } done_testing; Test-MockModule-v0.185.0/t/gh_83_no_leak.t000444001751001751 1235115177114646 20261 0ustar00runnerrunner000000000000#!/usr/bin/env perl # GH #83 regression suite. Proves the bug pattern from the issue does # NOT leak under the default (singleton-per-package) mode, and that # original_for is the documented escape hatch under distinct => 1. use warnings; use strict; use Test::More; use Test::MockModule; use Scalar::Util qw(refaddr); sub make_pkg { my ($pkg) = @_; no strict 'refs'; ## no critic (TestingAndDebugging::ProhibitNoStrict) *{"${pkg}::greet"} = sub { 'hello' }; *{"${pkg}::other"} = sub { 'other' }; } sub installed_code { my ($pkg, $name) = @_; no strict 'refs'; ## no critic (TestingAndDebugging::ProhibitNoStrict) return defined &{"${pkg}::${name}"} ? \&{"${pkg}::${name}"} : undef; } # 1. The literal reporter reproducer from GH #83. Used to fail in # v0.181-0.184 where distinct-objects became the default; passes # under singleton-default because the second new() returns the same # $mock and the second mock() overwrites the leaked closure in the # symbol table. subtest 'GH #83 reporter reproducer (default mode)' => sub { package Tgt_Reporter; ## no critic (Modules::RequireFilenameMatchesPackage) our $VERSION = 1; sub greet { 'hello' } package main; ## no critic (Modules::RequireFilenameMatchesPackage) my @results; my $run = sub { my ($label) = @_; my $mock = Test::MockModule->new('Tgt_Reporter', no_auto => 1); $mock->mock('greet', sub { return $mock->original('greet')->() . "_$label"; }); push @results, Tgt_Reporter::greet(); }; $run->('first'); $run->('second'); is_deeply \@results, ['hello_first', 'hello_second'], 'reporter pattern: each iteration sees fresh mock'; Test::MockModule->new('Tgt_Reporter', no_auto => 1)->unmock_all; }; # 2. redefine() variant of the reporter pattern, default mode. subtest 'redefine + $mock->original closure (default mode)' => sub { make_pkg('Tgt_Redef'); my @results; my $run = sub { my ($label) = @_; my $mock = Test::MockModule->new('Tgt_Redef', no_auto => 1); $mock->redefine('other', sub { return $mock->original('other')->() . "_$label"; }); push @results, Tgt_Redef::other(); }; $run->('a'); $run->('b'); is_deeply \@results, ['other_a', 'other_b'], 'redefine path'; Test::MockModule->new('Tgt_Redef', no_auto => 1)->unmock_all; }; # 3. Nested scope: under singleton default, the inner-scope mock is # overwritten on the next mock() call rather than leaked. subtest 'nested scope (default mode)' => sub { make_pkg('Tgt_Nested'); { my $mock = Test::MockModule->new('Tgt_Nested', no_auto => 1); $mock->mock('greet', sub { $mock->original('greet')->() . '_inner' }); is(Tgt_Nested::greet(), 'hello_inner', 'inside scope: mock active'); } # Singleton mode: the leaked closure is still installed, but the # singleton survived too. The next mock() call (or unmock_all) is # what restores. Use unmock_all to restore for this regression test. Test::MockModule->new('Tgt_Nested', no_auto => 1)->unmock_all; is(Tgt_Nested::greet(), 'hello', 'after unmock_all: original restored'); }; # 4. Under `distinct => 1`, the closure-captures-$mock pattern WOULD # leak. The recommended workaround is original_for. Verify it works. subtest 'original_for under distinct => 1 (no leak)' => sub { make_pkg('Tgt_Distinct'); my @results; my $run = sub { my ($label) = @_; my $mock = Test::MockModule->new( 'Tgt_Distinct', no_auto => 1, distinct => 1 ); $mock->mock('greet', sub { # No $mock capture -- only strings return Test::MockModule ->original_for('Tgt_Distinct', 'greet')->() . "_$label"; }); push @results, Tgt_Distinct::greet(); }; $run->('first'); $run->('second'); is_deeply \@results, ['hello_first', 'hello_second'], 'original_for pattern under distinct mode does not leak'; }; # 5. Symbol-table refaddr probe: proves the singleton-default mode # actually sees the same closure replaced (not stacked) across # iterations. Strongest direct evidence for the GH #83 fix. subtest 'symbol-table behavior under singleton default' => sub { make_pkg('Tgt_SymProbe'); my $orig_addr = refaddr(installed_code('Tgt_SymProbe', 'greet')); my @addrs_during; { my $mock = Test::MockModule->new('Tgt_SymProbe', no_auto => 1); $mock->mock('greet', sub { $mock->original('greet')->() . '_x' }); push @addrs_during, refaddr(installed_code('Tgt_SymProbe', 'greet')); # Re-mock: under singleton mode, the existing stack entry is # updated; the symbol table holds the new closure. $mock->mock('greet', sub { $mock->original('greet')->() . '_y' }); push @addrs_during, refaddr(installed_code('Tgt_SymProbe', 'greet')); } isnt($addrs_during[0], $orig_addr, 'first mock changes the symbol table'); isnt($addrs_during[0], $addrs_during[1], 're-mock installs a different closure'); Test::MockModule->new('Tgt_SymProbe', no_auto => 1)->unmock_all; is(refaddr(installed_code('Tgt_SymProbe', 'greet')), $orig_addr, 'symbol table restored after unmock_all'); }; done_testing; Test-MockModule-v0.185.0/t/global_strict_mode.t000444001751001751 141415177114646 21473 0ustar00runnerrunner000000000000use strict; use warnings; use Test::More; use lib 't/lib'; use Test::MockModule 'nostrict'; sub runtime_loose_mock { my $m = Test::MockModule->new("lib"); $m->mock( "abc" => 1 ); # Should fail under T::MM strict mode. return 1; } use Test::MockModule 'global-strict'; sub strict_off { eval { Test::MockModule->import('nostrict') }; like( "$@", qr/is illegal when GLOBAL_STRICT_MODE /, "An import of Test::MockModule fails if they try to turn off strict after global-strict has been set." ); } strict_off(); is( eval { runtime_loose_mock() }, undef, "runtime_loose_mock() fails at runtime" ); like( "$@", qr/is illegal when GLOBAL_STRICT_MODE/, "Runtime mock is caught even if nostrict is defined before global-strict is invoked" ); done_testing(); Test-MockModule-v0.185.0/t/import_options.t000444001751001751 177715177114646 20740 0ustar00runnerrunner000000000000use warnings; use strict; use Test::More; use Test::Warnings qw(warning warnings); use Test::MockModule; # Unknown import options should carp (line 30 in import()) { my $w = warning { Test::MockModule->import('not_a_real_option') }; like("$w", qr/Test::MockModule unknown import option 'not_a_real_option'/, 'unknown import option triggers carp'); } # Multiple bad options each carp { my @w = warnings { Test::MockModule->import('bogus1', 'bogus2') }; is(scalar @w, 2, 'two unknown options produce two warnings'); like("$w[0]", qr/unknown import option 'bogus1'/, 'first warning names first option'); like("$w[1]", qr/unknown import option 'bogus2'/, 'second warning names second option'); } # Mixing valid + invalid: valid still applies, invalid still warns { my @w = warnings { Test::MockModule->import('strict', 'huh') }; is(scalar @w, 1, 'valid option does not warn, only invalid one does'); like("$w[0]", qr/unknown import option 'huh'/, 'invalid option in mixed list still warns'); } done_testing(); Test-MockModule-v0.185.0/t/inheritance.t000444001751001751 552315177114646 20135 0ustar00runnerrunner000000000000use 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; ## no critic (Modules::RequireFilenameMatchesPackage) sub do_something { 1 } package InvalidChild; ## no critic (Modules::RequireFilenameMatchesPackage) sub abcd { 1 } package ValidChild; ## no critic (Modules::RequireFilenameMatchesPackage) 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.185.0/t/introspection.t000444001751001751 756115177114646 20550 0ustar00runnerrunner000000000000use warnings; use strict; use Test::More; use Test::Warnings qw(warning); BEGIN { use_ok('Test::MockModule') or BAIL_OUT "Could not load Test::MockModule"; } package Test_Intro_Parent; ## no critic (Modules::RequireFilenameMatchesPackage) our $VERSION = 1; sub inherited_only { 'inherited_value' } package Test_Intro; ## no critic (Modules::RequireFilenameMatchesPackage) our @ISA = ('Test_Intro_Parent'); our $VERSION = 1; sub foo { 'real_foo' } sub bar { 'real_bar' } sub baz { 'real_baz' } package main; # --- mocked_subs() --- # GH #52: introspection of what's currently mocked ok(Test::MockModule->can('mocked_subs'), 'mocked_subs() exists'); { my $mock = Test::MockModule->new('Test_Intro', no_auto => 1); my @empty = $mock->mocked_subs; is_deeply(\@empty, [], 'mocked_subs returns empty list when nothing mocked'); $mock->mock('foo', sub { 'mocked' }); my @one = $mock->mocked_subs; is_deeply(\@one, ['foo'], 'mocked_subs returns single mocked sub'); $mock->mock('baz', sub { 'mocked' }); $mock->mock('bar', sub { 'mocked' }); my @multi = $mock->mocked_subs; is_deeply(\@multi, ['bar', 'baz', 'foo'], 'mocked_subs returns sorted list'); $mock->unmock('baz'); my @after_unmock = $mock->mocked_subs; is_deeply(\@after_unmock, ['bar', 'foo'], 'mocked_subs reflects unmock'); $mock->unmock_all; my @after_all = $mock->mocked_subs; is_deeply(\@after_all, [], 'mocked_subs is empty after unmock_all'); } # mocked_subs after scope exit (DESTROY calls unmock_all) { my $mock = Test::MockModule->new('Test_Intro', no_auto => 1); $mock->mock('foo', sub { 'mocked' }); my @before = $mock->mocked_subs; is(scalar @before, 1, 'one sub mocked before scope exit'); } # After scope exit, a new mock object should have nothing mocked { my $mock = Test::MockModule->new('Test_Intro', no_auto => 1); my @fresh = $mock->mocked_subs; is_deeply(\@fresh, [], 'new object after scope exit has no mocked_subs'); } # --- original() when not mocked (GH #42) --- { my $mock = Test::MockModule->new('Test_Intro', no_auto => 1); # original() on an unmocked sub should return the real sub my $orig = $mock->original('foo'); is(ref $orig, 'CODE', 'original() returns coderef when not mocked'); is($orig->(), 'real_foo', 'original() returns the actual sub when not mocked'); # Now mock it, check original still works $mock->mock('foo', sub { 'mocked_foo' }); my $orig_after_mock = $mock->original('foo'); is(ref $orig_after_mock, 'CODE', 'original() returns coderef when mocked'); is($orig_after_mock->(), 'real_foo', 'original() returns the real sub when mocked'); # After unmock, original() should still work $mock->unmock('foo'); my $orig_after_unmock = $mock->original('foo'); is(ref $orig_after_unmock, 'CODE', 'original() returns coderef after unmock'); is($orig_after_unmock->(), 'real_foo', 'original() returns real sub after unmock'); } # original() with closure over $mock doesn't leak (GH #42 example) { my $mock = Test::MockModule->new('Test_Intro', no_auto => 1); # Get original before mocking (new behavior: no warning) my $orig = $mock->original('bar'); $mock->mock('bar', sub { 'prefix_' . $orig->() }); is(Test_Intro::bar(), 'prefix_real_bar', 'original() before mock enables safe wrapping'); } # original() carps on invalid subroutine name { my $mock = Test::MockModule->new('Test_Intro', no_auto => 1); my $w = warning { eval { $mock->original('123bad') } }; like("$w", qr/Please provide a valid function name/, 'original() carps when subroutine name is invalid'); } # original() falls through to SUPER for inherited subs not in target package (GH covers line 238) { my $mock = Test::MockModule->new('Test_Intro', no_auto => 1); my $orig = $mock->original('inherited_only'); is(ref $orig, 'CODE', 'original() returns coderef for inherited (parent-only) sub'); is($orig->(), 'inherited_value', 'original() returns parent sub when target package has no own copy'); } done_testing; Test-MockModule-v0.185.0/t/main.t000444001751001751 42215177114646 16541 0ustar00runnerrunner000000000000use 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.185.0/t/mock_all.t000444001751001751 1374315177114646 17450 0ustar00runnerrunner000000000000use warnings; use strict; use Test::More; use Test::Warnings; use Test::MockModule; # Set up test package with multiple subs { package MockAllTarget; ## no critic (Modules::RequireFilenameMatchesPackage) our $VERSION = 1; sub alpha { return 'alpha' } sub beta { return 'beta' } sub gamma { return 'gamma' } sub _private { return 'private' } sub import { return 'import' } # should be skipped } # 1. Default behavior: die on unmocked call { my $mock = Test::MockModule->new('MockAllTarget'); $mock->mock_all(); eval { MockAllTarget::alpha() }; like( $@, qr/MockAllTarget::alpha was not mocked/, 'mock_all dies on unmocked call (alpha)' ); eval { MockAllTarget::beta() }; like( $@, qr/MockAllTarget::beta was not mocked/, 'mock_all dies on unmocked call (beta)' ); # import should NOT be mocked is( MockAllTarget::import(), 'import', 'mock_all skips import()' ); } # Verify unmocking restores originals is( MockAllTarget::alpha(), 'alpha', 'alpha restored after mock object goes out of scope' ); is( MockAllTarget::beta(), 'beta', 'beta restored after mock object goes out of scope' ); # 2. noop mode # GH #81 contract: mock_all(noop => 1) MUST return 1 (truthy), to stay consistent # with noop() — see lib/Test/MockModule.pm POD. Do not "fix" these assertions to # undef without auditing the public-API impact. { my $mock = Test::MockModule->new('MockAllTarget'); $mock->mock_all(noop => 1); is( MockAllTarget::alpha(), 1, 'noop mode returns 1 (alpha) (GH #81 contract — DO NOT CHANGE)' ); is( MockAllTarget::beta(), 1, 'noop mode returns 1 (beta) (GH #81 contract — DO NOT CHANGE)' ); } is( MockAllTarget::alpha(), 'alpha', 'alpha restored after noop mock goes out of scope' ); # 3. Custom handler { my $mock = Test::MockModule->new('MockAllTarget'); $mock->mock_all(handler => sub { return 'handled' }); is( MockAllTarget::alpha(), 'handled', 'custom handler works (alpha)' ); is( MockAllTarget::gamma(), 'handled', 'custom handler works (gamma)' ); } is( MockAllTarget::gamma(), 'gamma', 'gamma restored after handler mock goes out of scope' ); # 4. Already-mocked subs are skipped { my $mock = Test::MockModule->new('MockAllTarget'); $mock->redefine('alpha', sub { return 'custom_alpha' }); $mock->mock_all(); is( MockAllTarget::alpha(), 'custom_alpha', 'already-mocked sub keeps its mock' ); eval { MockAllTarget::beta() }; like( $@, qr/MockAllTarget::beta was not mocked/, 'non-mocked sub gets mock_all treatment' ); } # 5. Chaining works { my $mock = Test::MockModule->new('MockAllTarget'); my $ret = $mock->mock_all(noop => 1); is( $ret, $mock, 'mock_all returns $self for chaining' ); } # 6. Private subs are mocked too { my $mock = Test::MockModule->new('MockAllTarget'); $mock->mock_all(); eval { MockAllTarget::_private() }; like( $@, qr/MockAllTarget::_private was not mocked/, 'private subs are mocked by mock_all' ); } # 7. Selective unmocking after mock_all { my $mock = Test::MockModule->new('MockAllTarget'); $mock->mock_all(); $mock->unmock('alpha'); is( MockAllTarget::alpha(), 'alpha', 'unmock restores individual sub after mock_all' ); eval { MockAllTarget::beta() }; like( $@, qr/MockAllTarget::beta was not mocked/, 'other subs remain mocked' ); } # 8. mock_all + redefine specific subs { my $mock = Test::MockModule->new('MockAllTarget'); $mock->mock_all(); $mock->redefine('alpha', sub { return 'real_mock' }); is( MockAllTarget::alpha(), 'real_mock', 'redefine after mock_all works' ); eval { MockAllTarget::beta() }; like( $@, qr/MockAllTarget::beta was not mocked/, 'mock_all still covers other subs' ); } # 9. Special Perl subs are skipped by mock_all { package SpecialSubTarget; our $VERSION = 1; sub new { return bless {}, shift } sub alpha { return 'alpha' } sub DESTROY { } sub AUTOLOAD { our $AUTOLOAD; return "auto:$AUTOLOAD" } sub BEGIN { } # technically already ran, but the symbol exists sub import { return 'import' } # Simulate overloaded operator subs (these appear in the stash with '(' prefix) use overload '""' => sub { 'stringified' }, fallback => 1; } { # Create object BEFORE mocking so new() works my $obj = SpecialSubTarget->new(); my $mock = Test::MockModule->new('SpecialSubTarget'); $mock->mock_all(); # alpha should be mocked (normal sub) eval { SpecialSubTarget::alpha() }; like( $@, qr/SpecialSubTarget::alpha was not mocked/, 'normal sub is mocked by mock_all' ); # DESTROY should NOT be mocked — mocking it causes crashes during cleanup # If DESTROY were mocked, this would croak when $obj goes out of scope undef $obj; pass('DESTROY is skipped by mock_all — no crash on object cleanup'); # import should NOT be mocked is( SpecialSubTarget::import(), 'import', 'import is skipped by mock_all' ); } # Verify the skip list by inspecting which subs got mocked { my $mock = Test::MockModule->new('SpecialSubTarget'); $mock->mock_all(noop => 1); ok( !$mock->is_mocked('DESTROY'), 'DESTROY is not mocked by mock_all' ); ok( !$mock->is_mocked('AUTOLOAD'), 'AUTOLOAD is not mocked by mock_all' ); ok( !$mock->is_mocked('import'), 'import is not mocked by mock_all' ); # Overload subs (starting with '(') should be skipped my $has_overload_sub = 0; { no strict 'refs'; ## no critic (TestingAndDebugging::ProhibitNoStrict) for my $name (keys %{'SpecialSubTarget::'}) { if ($name =~ /^\(/ && defined &{"SpecialSubTarget::$name"}) { ok( !$mock->is_mocked($name), "overload sub '$name' is not mocked by mock_all" ); $has_overload_sub = 1; } } } ok( $has_overload_sub, 'SpecialSubTarget has at least one overload sub to test' ); # But normal subs ARE mocked ok( $mock->is_mocked('alpha'), 'normal sub alpha IS mocked' ); ok( $mock->is_mocked('new'), 'new IS mocked' ); } done_testing(); Test-MockModule-v0.185.0/t/mock_strict.t000444001751001751 425215177114646 20163 0ustar00runnerrunner000000000000use 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." ); eval { $mocker->mock_all() }; like( "$@", qr/^mock_all is not allowed in strict mode. Please use redefine at/, "mock_all 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; ## no critic (Modules::RequireFilenameMatchesPackage) our $VERSION; BEGIN { $VERSION = 1 } sub existing_subroutine { 1 } 1; Test-MockModule-v0.185.0/t/mockmodule.t000444001751001751 1405315177114646 20021 0ustar00runnerrunner000000000000use 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; ## no critic (Modules::RequireFilenameMatchesPackage) 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 the same singleton object on a subsequent call (default behavior)"); # 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'); # GH #42: original() on unmocked sub returns the actual sub my $vars_orig = $mcgi->original('Vars'); is(ref $vars_orig, 'CODE', '... returns coderef for unmocked sub (GH #42)'); is($vars_orig, \&ExampleModule::Vars, '... returns the actual sub when not mocked'); # unmock() ok($mcgi->can('unmock'), 'unmock()'); eval {$mcgi->unmock('V@rs')}; like($@, qr/Invalid subroutine name/, '... dies if the subroutine is invalid'); my ($warn); local $SIG{__WARN__} = sub {$warn = shift}; $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'); # GH #81 contract: noop() mocked subs MUST return 1 (truthy). # Downstream callers (e.g. openSUSE packaging) depend on this — do not # "fix" the assertion to undef without auditing the public-API impact. is(ExampleModule::cookie(), 1, 'noop subs return 1 (GH #81 contract — DO NOT CHANGE)'); is(ExampleModule::Vars(), 1, 'noop subs return 1 (GH #81 contract — DO NOT CHANGE)'); } 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.185.0/t/moose_around.t000444001751001751 261515177114646 20335 0ustar00runnerrunner000000000000use strict; use warnings; use FindBin; use lib "$FindBin::Bin/lib"; use Test::More; BEGIN { eval { require Moose; 1 } or plan skip_all => "Moose not installed"; eval { require Class::Load; 1 } or plan skip_all => "Class::Load not installed"; eval { require Test::Exception; 1 } or plan skip_all => "Test::Exception not installed"; } use Test::Exception; use Class::Load qw/load_class/; use Test::MockModule; # Pre-load parent so the mock has a target. Child is loaded LATER (post-mock) # to reproduce the bug: Moose's `around` resolves the parent method via the # meta-class, which would not see the mock if the mock only patched the glob. load_class('Issue55::MooseAroundParent'); my $mock = Test::MockModule->new('Issue55::MooseAroundParent'); $mock->mock( foo => sub { 3 } ); lives_ok { load_class('Issue55::MooseAroundChild'); } "loading Moose subclass with around-modifier on mocked parent does not die"; is(Issue55::MooseAroundChild->new->foo, 2, "child's around modifier still wins (returns 2, ignoring \$orig)"); # Variant where child's around invokes $orig -- proves the mock is reachable # through the Moose modifier chain. lives_ok { load_class('Issue55::MooseAroundChildOrig'); } "loading second subclass post-mock also lives"; is(Issue55::MooseAroundChildOrig->new->foo, 'wrapped(3)', "child's around can reach mocked parent foo via \$orig"); done_testing; Test-MockModule-v0.185.0/t/moose_immutable.t000444001751001751 163115177114646 21021 0ustar00runnerrunner000000000000use strict; use warnings; use Test::More; BEGIN { eval { require Moose; 1 } or plan skip_all => "Moose not installed"; } use Test::Warnings ':all'; use Test::MockModule; { package Issue55::Immutable; ## no critic (Modules::RequireFilenameMatchesPackage) use Moose; sub foo { 'real' } __PACKAGE__->meta->make_immutable; } my $mock = Test::MockModule->new('Issue55::Immutable'); # Mocking an immutable class still works (falls back to glob), but emits a warning. my @warnings = warnings(sub { $mock->mock( foo => sub { 'mocked' } ); }); is(Issue55::Immutable->foo, 'mocked', "mock works on immutable class via glob fallback"); ok( (grep { /immutable/i && /Issue55::Immutable/ } @warnings), "fallback emits an immutable-class warning" ) or diag explain \@warnings; $mock->unmock('foo'); is(Issue55::Immutable->foo, 'real', "unmock restores original on immutable class"); done_testing; Test-MockModule-v0.185.0/t/moose_meta_for.t000444001751001751 237715177114646 20646 0ustar00runnerrunner000000000000use strict; use warnings; use Test::More; BEGIN { eval { require Moose; 1 } or plan skip_all => "Moose not installed"; eval { require Mouse; 1 } or plan skip_all => "Mouse not installed"; } use Test::MockModule; # Plain (non-Moose) package { package PlainPkg; ## no critic (Modules::RequireFilenameMatchesPackage) sub new { bless {}, shift } } # Moose package { package MoosePkg; ## no critic (Modules::RequireFilenameMatchesPackage) use Moose; } # Mouse package { package MousePkg; ## no critic (Modules::RequireFilenameMatchesPackage) use Mouse; } is(Test::MockModule::_meta_for('PlainPkg'), undef, "plain package returns undef"); ok(Test::MockModule::_meta_for('MoosePkg'), "Moose package returns truthy meta"); isa_ok(Test::MockModule::_meta_for('MoosePkg'), 'Class::MOP::Class', "Moose meta type"); ok(Test::MockModule::_meta_for('MousePkg'), "Mouse package returns truthy meta"); isa_ok(Test::MockModule::_meta_for('MousePkg'), 'Mouse::Meta::Class', "Mouse meta type"); is(Test::MockModule::_meta_for(undef), undef, "undef package returns undef"); is(Test::MockModule::_meta_for(''), undef, "empty package returns undef"); is(Test::MockModule::_meta_for('Does::Not::Exist'), undef, "nonexistent package returns undef"); done_testing; Test-MockModule-v0.185.0/t/moose_multi.t000444001751001751 1600115177114646 20211 0ustar00runnerrunner000000000000use strict; use warnings; use Test::More; BEGIN { eval { require Moose; 1 } or plan skip_all => "Moose not installed"; } use Test::MockModule; # Two mock objects on the same Moose method must coexist correctly: each # mocks independently, layering is LIFO, non-LIFO destruction is safe, and # tearing down one layer must not leak a sibling layer's saved state into # the meta-class. { package MooseMulti::Local; ## no critic (Modules::RequireFilenameMatchesPackage) use Moose; sub greet { 'orig_greet' } sub other { 'orig_other' } } # LIFO unmock: top layer pops first, then bottom layer pops. { my $m1 = Test::MockModule->new('MooseMulti::Local', distinct => 1); $m1->mock('greet', sub { 'A' }); is(MooseMulti::Local->greet, 'A', 'LIFO: m1 mock active'); my $m2 = Test::MockModule->new('MooseMulti::Local', distinct => 1); $m2->mock('greet', sub { 'B' }); is(MooseMulti::Local->greet, 'B', 'LIFO: m2 mock takes over'); $m2->unmock('greet'); is(MooseMulti::Local->greet, 'A', 'LIFO: m1 mock restored after m2 unmocks'); $m1->unmock('greet'); is(MooseMulti::Local->greet, 'orig_greet', 'LIFO: original restored after m1 unmocks'); ok(MooseMulti::Local->meta->get_method('greet'), 'LIFO: meta has greet again after full teardown'); } # Non-LIFO unmock: bottom layer pops first, then top layer pops. The # pre-PR singleton implementation hid this case; the new design must keep # m2's mock active after m1 unmocks, and restore the original after both. { my $m1 = Test::MockModule->new('MooseMulti::Local', distinct => 1); $m1->mock('greet', sub { 'A' }); my $m2 = Test::MockModule->new('MooseMulti::Local', distinct => 1); $m2->mock('greet', sub { 'B' }); is(MooseMulti::Local->greet, 'B', 'non-LIFO: m2 active'); $m1->unmock('greet'); is(MooseMulti::Local->greet, 'B', 'non-LIFO: m2 still mocking after m1 (mid-stack) unmocks'); $m2->unmock('greet'); is(MooseMulti::Local->greet, 'orig_greet', 'non-LIFO: original restored after m2 unmocks'); } # Non-top re-mock under Moose: when a non-top object re-mocks, its newest # install must take effect immediately (per the documented contract), and # subsequent mid-stack unmock must hand control back to the still-living # top layer rather than leaving the stale install in the meta. { my $m1 = Test::MockModule->new('MooseMulti::Local', distinct => 1); $m1->mock('greet', sub { 'A' }); my $m2 = Test::MockModule->new('MooseMulti::Local', distinct => 1); $m2->mock('greet', sub { 'B' }); $m1->mock('greet', sub { 'C' }); is(MooseMulti::Local->greet, 'C', 'non-top re-mock takes effect via meta'); $m1->unmock('greet'); is(MooseMulti::Local->greet, 'B', 'mid-stack unmock after non-top re-mock hands meta back to top'); $m2->unmock('greet'); is(MooseMulti::Local->greet, 'orig_greet', 'non-top re-mock cleanup: original restored'); } # Destructor path on Moose: ensure DESTROY-driven mid-stack unmock leaves # the surviving top layer in control of meta. { my $m2; { my $m1 = Test::MockModule->new('MooseMulti::Local', distinct => 1); $m1->mock('greet', sub { 'A' }); $m2 = Test::MockModule->new('MooseMulti::Local', distinct => 1); $m2->mock('greet', sub { 'B' }); # m1 destructed here. } is(MooseMulti::Local->greet, 'B', 'destructor: mid-stack DESTROY leaves top in control of meta'); undef $m2; is(MooseMulti::Local->greet, 'orig_greet', 'destructor: cleanup ok'); } # Independent mocks on different methods: m1 mocks one method, m2 mocks a # different method. Each unmock must only affect its own method. { my $m1 = Test::MockModule->new('MooseMulti::Local', distinct => 1); $m1->mock('greet', sub { 'AA' }); my $m2 = Test::MockModule->new('MooseMulti::Local', distinct => 1); $m2->mock('other', sub { 'BB' }); is(MooseMulti::Local->greet, 'AA', 'independent: greet from m1'); is(MooseMulti::Local->other, 'BB', 'independent: other from m2'); $m1->unmock('greet'); is(MooseMulti::Local->greet, 'orig_greet', 'independent: greet restored when m1 unmocks'); is(MooseMulti::Local->other, 'BB', 'independent: other untouched when m1 unmocks'); $m2->unmock('other'); is(MooseMulti::Local->other, 'orig_other', 'independent: other restored when m2 unmocks'); } # Inherited method, two mock objects: child has no local foo; both objects # mock it; after full teardown, the local meta entry must be gone so # inheritance lookup falls back to the parent. { package MooseMulti::Parent; ## no critic (Modules::RequireFilenameMatchesPackage) use Moose; sub bar { 'parent_bar' } } { package MooseMulti::Child; ## no critic (Modules::RequireFilenameMatchesPackage) use Moose; extends 'MooseMulti::Parent'; } { my $m1 = Test::MockModule->new('MooseMulti::Child', distinct => 1); $m1->mock('bar', sub { 'child_A' }); my $m2 = Test::MockModule->new('MooseMulti::Child', distinct => 1); $m2->mock('bar', sub { 'child_B' }); is(MooseMulti::Child->bar, 'child_B', 'inherited: m2 mock visible'); $m1->unmock('bar'); is(MooseMulti::Child->bar, 'child_B', 'inherited: m2 mock still visible after m1 (mid-stack) unmocks'); $m2->unmock('bar'); is(MooseMulti::Child->bar, 'parent_bar', 'inherited: parent method restored after both unmock'); ok(!MooseMulti::Child->meta->get_method('bar'), 'inherited: child meta entry removed after full teardown'); } # Edge case: immutable -> mutable transition between two mock objects. # m1 mocks while the class is immutable (symbol-table-only path), then the # user makes the class mutable, then m2 mocks via the meta path. On # mid-stack unmock of m1, the popped layer's meta_orig (undef, since m1 # was symbol-only) must NOT clobber m2's captured meta_orig. Otherwise # the eventual top-of-stack restore removes the method instead of # restoring the original. { package MooseMulti::Toggle; ## no critic (Modules::RequireFilenameMatchesPackage) use Moose; sub greet { 'orig_greet' } __PACKAGE__->meta->make_immutable; } { my $m1 = Test::MockModule->new('MooseMulti::Toggle', distinct => 1); { local $SIG{__WARN__} = sub {}; # swallow the immutable carp $m1->mock('greet', sub { 'A' }); } is(MooseMulti::Toggle->greet, 'A', 'toggle: m1 mock active (symbol-only)'); MooseMulti::Toggle->meta->make_mutable; my $m2 = Test::MockModule->new('MooseMulti::Toggle', distinct => 1); $m2->mock('greet', sub { 'B' }); is(MooseMulti::Toggle->greet, 'B', 'toggle: m2 mock active (meta path)'); $m1->unmock('greet'); is(MooseMulti::Toggle->greet, 'B', 'toggle: m2 mock still active after mid-stack m1 unmock'); $m2->unmock('greet'); is(MooseMulti::Toggle->greet, 'orig_greet', 'toggle: original restored after full teardown'); ok(MooseMulti::Toggle->meta->get_method('greet'), 'toggle: meta has greet again after full teardown'); } done_testing; Test-MockModule-v0.185.0/t/moose_redefine.t000444001751001751 643715177114646 20634 0ustar00runnerrunner000000000000use strict; use warnings; use Test::More; BEGIN { eval { require Moose; 1 } or plan skip_all => "Moose not installed"; eval { require Test::Exception; 1 } or plan skip_all => "Test::Exception not installed"; } use Test::Exception; use Test::MockModule; # Local method on a Moose class { package Issue55::RedefineLocal; ## no critic (Modules::RequireFilenameMatchesPackage) use Moose; sub foo { 'real_foo' } } # Inherited method (child has no local foo) { package Issue55::RedefineParent; ## no critic (Modules::RequireFilenameMatchesPackage) use Moose; sub bar { 'parent_bar' } } { package Issue55::RedefineChild; ## no critic (Modules::RequireFilenameMatchesPackage) use Moose; extends 'Issue55::RedefineParent'; } # Empty class for define() coverage { package Issue55::DefineTarget; ## no critic (Modules::RequireFilenameMatchesPackage) use Moose; } # redefine() on a locally-defined Moose method goes through the meta path { my $mock = Test::MockModule->new('Issue55::RedefineLocal'); $mock->redefine( foo => sub { 'redefined' } ); is(Issue55::RedefineLocal->foo, 'redefined', "redefine() mocks Moose method"); ok(Issue55::RedefineLocal->meta->get_method('foo'), "redefine() registered foo on the meta-class"); $mock->unmock('foo'); is(Issue55::RedefineLocal->foo, 'real_foo', "redefine()+unmock restores original"); } # redefine() on a method that doesn't exist anywhere should die { my $mock = Test::MockModule->new('Issue55::RedefineLocal'); throws_ok { $mock->redefine( missing_method => sub { 'no' } ); } qr/missing_method/, "redefine() dies when method doesn't exist"; } # redefine() on an inherited method should succeed (parent provides it) { my $mock = Test::MockModule->new('Issue55::RedefineChild'); lives_ok { $mock->redefine( bar => sub { 'mocked_bar' } ); } "redefine() on inherited method does not die"; is(Issue55::RedefineChild->bar, 'mocked_bar', "inherited method redefined"); ok(Issue55::RedefineChild->meta->get_method('bar'), "redefine() on inherited method registered on child meta"); $mock->unmock('bar'); is(Issue55::RedefineChild->bar, 'parent_bar', "redefine()+unmock falls back to parent"); ok(!Issue55::RedefineChild->meta->get_method('bar'), "child meta no longer has bar after unmock"); } # define() on a Moose class for a method that does not exist { my $mock = Test::MockModule->new('Issue55::DefineTarget'); $mock->define( newly_defined => sub { 'fresh' } ); is(Issue55::DefineTarget->newly_defined, 'fresh', "define() installs new method on Moose class"); ok(Issue55::DefineTarget->meta->get_method('newly_defined'), "define() registered the new method on the meta-class"); $mock->unmock('newly_defined'); ok(!Issue55::DefineTarget->can('newly_defined'), "define()+unmock removes the method entirely"); ok(!Issue55::DefineTarget->meta->get_method('newly_defined'), "define()+unmock removes from meta-class too"); } # define() should die if the method already exists { my $mock = Test::MockModule->new('Issue55::RedefineLocal'); throws_ok { $mock->define( foo => sub { 'no' } ); } qr/foo/, "define() dies when method already exists"; } done_testing; Test-MockModule-v0.185.0/t/moose_role_requires.t000444001751001751 303515177114646 21722 0ustar00runnerrunner000000000000use strict; use warnings; use Test::More; BEGIN { eval { require Moose; 1 } or plan skip_all => "Moose not installed"; eval { require Moose::Util; 1 } or plan skip_all => "Moose::Util not installed"; eval { require Test::Exception; 1 } or plan skip_all => "Test::Exception not installed"; } use Test::Exception; use Test::MockModule; # Role with a required method { package Issue55::FooRole; ## no critic (Modules::RequireFilenameMatchesPackage) use Moose::Role; requires 'foo'; } # Class implementing the role { package Issue55::FooClass; ## no critic (Modules::RequireFilenameMatchesPackage) use Moose; sub foo { 'real_foo' } with 'Issue55::FooRole'; } # A second role that also requires foo — applied dynamically AFTER the mock, # which forces Moose to re-check requirements against the (mocked) class meta. { package Issue55::AnotherFooRole; ## no critic (Modules::RequireFilenameMatchesPackage) use Moose::Role; requires 'foo'; sub other { 'other' } } my $mock = Test::MockModule->new('Issue55::FooClass'); $mock->mock( foo => sub { 'mocked_foo' } ); is(Issue55::FooClass->new->foo, 'mocked_foo', "mock visible on class"); my $obj = Issue55::FooClass->new; lives_ok { Moose::Util::apply_all_roles($obj, 'Issue55::AnotherFooRole'); } "applying a role that requires the mocked method does not die"; is($obj->foo, 'mocked_foo', "mock still visible after dynamic role application"); is($obj->other, 'other', "role's own method works after composition"); done_testing; Test-MockModule-v0.185.0/t/moose_unmock.t000444001751001751 557515177114646 20351 0ustar00runnerrunner000000000000use strict; use warnings; use Test::More; BEGIN { eval { require Moose; 1 } or plan skip_all => "Moose not installed"; } use Test::MockModule; # Local-orig case: parent has its own foo { package Issue55::UnmockLocalOrig; ## no critic (Modules::RequireFilenameMatchesPackage) use Moose; sub foo { 'orig' } } # Inherited case: child has no local foo; inherits from parent { package Issue55::UnmockParent; ## no critic (Modules::RequireFilenameMatchesPackage) use Moose; sub bar { 'parent_bar' } } { package Issue55::UnmockInherited; ## no critic (Modules::RequireFilenameMatchesPackage) use Moose; extends 'Issue55::UnmockParent'; } # Local-orig: mock+unmock restores method on meta and direct call { my $mock = Test::MockModule->new('Issue55::UnmockLocalOrig'); $mock->mock( foo => sub { 'mocked' } ); is(Issue55::UnmockLocalOrig->foo, 'mocked', "local-orig: mock visible"); ok(Issue55::UnmockLocalOrig->meta->get_method('foo'), "local-orig: meta has foo while mocked"); $mock->unmock('foo'); is(Issue55::UnmockLocalOrig->foo, 'orig', "local-orig: original restored"); ok(Issue55::UnmockLocalOrig->meta->get_method('foo'), "local-orig: meta still has foo after unmock"); } # Re-mock: mocking the same name twice must not lose the *true* original. # The second mock should replace the first mock body, but unmock should still # restore the pre-any-mock implementation -- not the first mock body. { package Issue55::UnmockReMock; ## no critic (Modules::RequireFilenameMatchesPackage) use Moose; sub foo { 'orig' } } { my $mock = Test::MockModule->new('Issue55::UnmockReMock'); $mock->mock( foo => sub { 'first_mock' } ); is(Issue55::UnmockReMock->foo, 'first_mock', "re-mock: first mock active"); $mock->mock( foo => sub { 'second_mock' } ); is(Issue55::UnmockReMock->foo, 'second_mock', "re-mock: second mock replaces first"); $mock->unmock('foo'); is(Issue55::UnmockReMock->foo, 'orig', "re-mock+unmock restores the true original, not the first mock"); ok(Issue55::UnmockReMock->meta->get_method('foo'), "re-mock+unmock leaves meta with original method"); } # Inherited-orig: mock adds method, unmock should remove it from child meta # so the inheritance lookup falls back to parent. { my $mock = Test::MockModule->new('Issue55::UnmockInherited'); $mock->mock( bar => sub { 'mocked_bar' } ); is(Issue55::UnmockInherited->bar, 'mocked_bar', "inherited-orig: mock visible"); ok(Issue55::UnmockInherited->meta->get_method('bar'), "inherited-orig: meta has bar while mocked"); $mock->unmock('bar'); is(Issue55::UnmockInherited->bar, 'parent_bar', "inherited-orig: parent method takes over after unmock"); ok(!Issue55::UnmockInherited->meta->get_method('bar'), "inherited-orig: child meta no longer has bar after unmock"); } done_testing; Test-MockModule-v0.185.0/t/mouse_basic.t000444001751001751 334115177114646 20131 0ustar00runnerrunner000000000000use strict; use warnings; use Test::More; BEGIN { eval { require Mouse; 1 } or plan skip_all => "Mouse not installed"; eval { require Mouse::Role; 1 } or plan skip_all => "Mouse::Role not installed"; eval { require Test::Exception; 1 } or plan skip_all => "Test::Exception not installed"; } use Test::Exception; use Test::MockModule; { package Issue55::MouseRole; ## no critic (Modules::RequireFilenameMatchesPackage) use Mouse::Role; requires 'foo'; } { package Issue55::MouseClass; ## no critic (Modules::RequireFilenameMatchesPackage) use Mouse; sub foo { 'real_foo' } with 'Issue55::MouseRole'; } { package Issue55::MouseParent; ## no critic (Modules::RequireFilenameMatchesPackage) use Mouse; sub bar { 'parent_bar' } } { package Issue55::MouseChild; ## no critic (Modules::RequireFilenameMatchesPackage) use Mouse; extends 'Issue55::MouseParent'; } # Basic mock-and-call my $mock = Test::MockModule->new('Issue55::MouseClass'); $mock->mock( foo => sub { 'mocked_foo' } ); is(Issue55::MouseClass->new->foo, 'mocked_foo', "Mouse mock visible"); ok(Issue55::MouseClass->meta->get_method('foo'), "Mouse meta has foo while mocked"); $mock->unmock('foo'); is(Issue55::MouseClass->new->foo, 'real_foo', "Mouse unmock restores original"); # Inherited unmock path my $imock = Test::MockModule->new('Issue55::MouseChild'); $imock->mock( bar => sub { 'mocked_bar' } ); is(Issue55::MouseChild->bar, 'mocked_bar', "Mouse inherited mock visible"); $imock->unmock('bar'); is(Issue55::MouseChild->bar, 'parent_bar', "Mouse unmock falls through to parent"); ok(!Issue55::MouseChild->meta->get_method('bar'), "Mouse child meta no longer has bar after unmock"); done_testing; Test-MockModule-v0.185.0/t/mouse_multi.t000444001751001751 1345415177114646 20230 0ustar00runnerrunner000000000000use strict; use warnings; use Test::More; BEGIN { eval { require Mouse; 1 } or plan skip_all => "Mouse not installed"; } use Test::MockModule; # Mouse counterpart of t/moose_multi.t. Same scenarios, validating that # the per-sub layer stack treats Mouse::Meta::Class consistently with # Class::MOP::Class. { package MouseMulti::Local; ## no critic (Modules::RequireFilenameMatchesPackage) use Mouse; sub greet { 'orig_greet' } sub other { 'orig_other' } } # LIFO unmock { my $m1 = Test::MockModule->new('MouseMulti::Local', distinct => 1); $m1->mock('greet', sub { 'A' }); is(MouseMulti::Local->greet, 'A', 'LIFO: m1 mock active'); my $m2 = Test::MockModule->new('MouseMulti::Local', distinct => 1); $m2->mock('greet', sub { 'B' }); is(MouseMulti::Local->greet, 'B', 'LIFO: m2 mock takes over'); $m2->unmock('greet'); is(MouseMulti::Local->greet, 'A', 'LIFO: m1 mock restored after m2 unmocks'); $m1->unmock('greet'); is(MouseMulti::Local->greet, 'orig_greet', 'LIFO: original restored after m1 unmocks'); ok(MouseMulti::Local->meta->get_method('greet'), 'LIFO: meta has greet again after full teardown'); } # Non-LIFO unmock (the case the singleton previously hid) { my $m1 = Test::MockModule->new('MouseMulti::Local', distinct => 1); $m1->mock('greet', sub { 'A' }); my $m2 = Test::MockModule->new('MouseMulti::Local', distinct => 1); $m2->mock('greet', sub { 'B' }); is(MouseMulti::Local->greet, 'B', 'non-LIFO: m2 active'); $m1->unmock('greet'); is(MouseMulti::Local->greet, 'B', 'non-LIFO: m2 still mocking after m1 unmocks'); $m2->unmock('greet'); is(MouseMulti::Local->greet, 'orig_greet', 'non-LIFO: original restored after m2 unmocks'); } # Non-top re-mock + mid-stack unmock { my $m1 = Test::MockModule->new('MouseMulti::Local', distinct => 1); $m1->mock('greet', sub { 'A' }); my $m2 = Test::MockModule->new('MouseMulti::Local', distinct => 1); $m2->mock('greet', sub { 'B' }); $m1->mock('greet', sub { 'C' }); is(MouseMulti::Local->greet, 'C', 'non-top re-mock takes effect via meta'); $m1->unmock('greet'); is(MouseMulti::Local->greet, 'B', 'mid-stack unmock after non-top re-mock hands meta back to top'); $m2->unmock('greet'); is(MouseMulti::Local->greet, 'orig_greet', 'non-top re-mock cleanup: original restored'); } # Destructor path on Mouse { my $m2; { my $m1 = Test::MockModule->new('MouseMulti::Local', distinct => 1); $m1->mock('greet', sub { 'A' }); $m2 = Test::MockModule->new('MouseMulti::Local', distinct => 1); $m2->mock('greet', sub { 'B' }); # m1 destructed here. } is(MouseMulti::Local->greet, 'B', 'destructor: mid-stack DESTROY leaves top in control of meta'); undef $m2; is(MouseMulti::Local->greet, 'orig_greet', 'destructor: cleanup ok'); } # Independent methods { my $m1 = Test::MockModule->new('MouseMulti::Local', distinct => 1); $m1->mock('greet', sub { 'AA' }); my $m2 = Test::MockModule->new('MouseMulti::Local', distinct => 1); $m2->mock('other', sub { 'BB' }); is(MouseMulti::Local->greet, 'AA', 'independent: greet from m1'); is(MouseMulti::Local->other, 'BB', 'independent: other from m2'); $m1->unmock('greet'); is(MouseMulti::Local->greet, 'orig_greet', 'independent: greet restored when m1 unmocks'); is(MouseMulti::Local->other, 'BB', 'independent: other untouched when m1 unmocks'); $m2->unmock('other'); is(MouseMulti::Local->other, 'orig_other', 'independent: other restored when m2 unmocks'); } # Inherited method, two mock objects { package MouseMulti::Parent; ## no critic (Modules::RequireFilenameMatchesPackage) use Mouse; sub bar { 'parent_bar' } } { package MouseMulti::Child; ## no critic (Modules::RequireFilenameMatchesPackage) use Mouse; extends 'MouseMulti::Parent'; } { my $m1 = Test::MockModule->new('MouseMulti::Child', distinct => 1); $m1->mock('bar', sub { 'child_A' }); my $m2 = Test::MockModule->new('MouseMulti::Child', distinct => 1); $m2->mock('bar', sub { 'child_B' }); is(MouseMulti::Child->bar, 'child_B', 'inherited: m2 mock visible'); $m1->unmock('bar'); is(MouseMulti::Child->bar, 'child_B', 'inherited: m2 mock still visible after m1 unmocks'); $m2->unmock('bar'); is(MouseMulti::Child->bar, 'parent_bar', 'inherited: parent method restored after both unmock'); ok(!MouseMulti::Child->meta->get_method('bar'), 'inherited: child meta entry removed after full teardown'); } # Edge case: immutable -> mutable transition between two mock objects. # Mouse counterpart of the toggle test in t/moose_multi.t. { package MouseMulti::Toggle; ## no critic (Modules::RequireFilenameMatchesPackage) use Mouse; sub greet { 'orig_greet' } __PACKAGE__->meta->make_immutable; } { my $m1 = Test::MockModule->new('MouseMulti::Toggle', distinct => 1); { local $SIG{__WARN__} = sub {}; # swallow the immutable carp $m1->mock('greet', sub { 'A' }); } is(MouseMulti::Toggle->greet, 'A', 'toggle: m1 mock active (symbol-only)'); MouseMulti::Toggle->meta->make_mutable; my $m2 = Test::MockModule->new('MouseMulti::Toggle', distinct => 1); $m2->mock('greet', sub { 'B' }); is(MouseMulti::Toggle->greet, 'B', 'toggle: m2 mock active (meta path)'); $m1->unmock('greet'); is(MouseMulti::Toggle->greet, 'B', 'toggle: m2 mock still active after mid-stack m1 unmock'); $m2->unmock('greet'); is(MouseMulti::Toggle->greet, 'orig_greet', 'toggle: original restored after full teardown'); ok(MouseMulti::Toggle->meta->get_method('greet'), 'toggle: meta has greet again after full teardown'); } done_testing; Test-MockModule-v0.185.0/t/multiple_objects.t000444001751001751 2447215177114646 21234 0ustar00runnerrunner000000000000use warnings; use strict; use Test::More; use Test::Warnings; use Test::MockModule; use lib "t/lib"; # Test package package Stacked; ## no critic (Modules::RequireFilenameMatchesPackage) our $VERSION = 1; sub foo { 'original_foo' } sub bar { 'original_bar' } package main; ## no critic (Modules::RequireFilenameMatchesPackage) # Basic: new() returns distinct objects { my $m1 = Test::MockModule->new('Stacked', distinct => 1); my $m2 = Test::MockModule->new('Stacked', distinct => 1); isnt($m1, $m2, 'new() returns distinct objects for same package'); is($m1->get_package, 'Stacked', '... both target the same package'); is($m2->get_package, 'Stacked', '... both target the same package'); } # Independent mocking: different subs on different objects { my $m1 = Test::MockModule->new('Stacked', distinct => 1); $m1->mock('foo', sub { 'mock1_foo' }); is(Stacked::foo(), 'mock1_foo', 'first object mocks foo'); is(Stacked::bar(), 'original_bar', 'bar is untouched'); { my $m2 = Test::MockModule->new('Stacked', distinct => 1); $m2->mock('bar', sub { 'mock2_bar' }); is(Stacked::foo(), 'mock1_foo', 'foo still mocked by first object'); is(Stacked::bar(), 'mock2_bar', 'bar mocked by second object'); } is(Stacked::foo(), 'mock1_foo', 'foo still mocked after second object destroyed'); is(Stacked::bar(), 'original_bar', 'bar restored after second object destroyed'); } is(Stacked::foo(), 'original_foo', 'foo restored after first object destroyed'); # Stacked mocking: same sub, LIFO destruction order { my $m1 = Test::MockModule->new('Stacked', distinct => 1); $m1->mock('foo', sub { 'layer1' }); is(Stacked::foo(), 'layer1', 'first layer'); { my $m2 = Test::MockModule->new('Stacked', distinct => 1); $m2->mock('foo', sub { 'layer2' }); is(Stacked::foo(), 'layer2', 'second layer overrides first'); } is(Stacked::foo(), 'layer1', 'first layer restored after second destroyed'); } is(Stacked::foo(), 'original_foo', 'original restored after all objects destroyed'); # Stacked mocking: same sub, non-LIFO destruction order (inner destroyed last) { my $m2; { my $m1 = Test::MockModule->new('Stacked', distinct => 1); $m1->mock('foo', sub { 'layer1' }); $m2 = Test::MockModule->new('Stacked', distinct => 1); $m2->mock('foo', sub { 'layer2' }); is(Stacked::foo(), 'layer2', 'layer2 active'); } # m1 destroyed, but m2 (on top) is still alive is(Stacked::foo(), 'layer2', 'layer2 still active after layer1 object destroyed'); undef $m2; is(Stacked::foo(), 'original_foo', 'original restored after both destroyed (non-LIFO)'); } # Three layers { my $m1 = Test::MockModule->new('Stacked', distinct => 1); $m1->mock('foo', sub { 'L1' }); my $m2 = Test::MockModule->new('Stacked', distinct => 1); $m2->mock('foo', sub { 'L2' }); my $m3 = Test::MockModule->new('Stacked', distinct => 1); $m3->mock('foo', sub { 'L3' }); is(Stacked::foo(), 'L3', 'three layers: top wins'); # Destroy middle undef $m2; is(Stacked::foo(), 'L3', 'destroying middle does not affect top'); # Destroy top undef $m3; is(Stacked::foo(), 'L1', 'after top and middle gone, first layer restored'); # Destroy bottom undef $m1; is(Stacked::foo(), 'original_foo', 'all gone, original restored'); } # Explicit unmock interacts correctly with stack { my $m1 = Test::MockModule->new('Stacked', distinct => 1); $m1->mock('foo', sub { 'A' }); my $m2 = Test::MockModule->new('Stacked', distinct => 1); $m2->mock('foo', sub { 'B' }); is(Stacked::foo(), 'B', 'B is active'); $m2->unmock('foo'); is(Stacked::foo(), 'A', 'after unmocking B, A is restored'); $m1->unmock('foo'); is(Stacked::foo(), 'original_foo', 'after unmocking A, original restored'); } # is_mocked is per-object { my $m1 = Test::MockModule->new('Stacked', distinct => 1); $m1->mock('foo', sub { 'x' }); my $m2 = Test::MockModule->new('Stacked', distinct => 1); ok($m1->is_mocked('foo'), 'm1 reports foo as mocked'); ok(!$m2->is_mocked('foo'), 'm2 does not report foo as mocked'); $m2->mock('bar', sub { 'y' }); ok(!$m1->is_mocked('bar'), 'm1 does not report bar as mocked'); ok($m2->is_mocked('bar'), 'm2 reports bar as mocked'); } # original() returns the correct original per object { my $orig_foo = \&Stacked::foo; my $m1 = Test::MockModule->new('Stacked', distinct => 1); $m1->mock('foo', sub { 'first' }); my $m2 = Test::MockModule->new('Stacked', distinct => 1); $m2->mock('foo', sub { 'second' }); is($m1->original('foo'), $orig_foo, 'm1 original is the true original'); # m2 saved m1s mock as its "original" is($m2->original('foo')->(), 'first', 'm2 original is m1 mock'); } # Re-mock by a non-top object: when the top unmocks, the non-top object's # most recent install should be active, not its initial install. { my $m1 = Test::MockModule->new('Stacked', distinct => 1); $m1->mock('foo', sub { 'm1_v1' }); my $m2 = Test::MockModule->new('Stacked', distinct => 1); $m2->mock('foo', sub { 'm2' }); is(Stacked::foo(), 'm2', 're-mock setup: m2 active'); # m1 (non-top) re-mocks foo with a new value. $m1->mock('foo', sub { 'm1_v2' }); is(Stacked::foo(), 'm1_v2', 'non-top re-mock takes effect immediately'); # m2 unmocks. Stack should restore m1's CURRENT install (m1_v2), # not m1's initial install (m1_v1). $m2->unmock('foo'); is(Stacked::foo(), 'm1_v2', 'top unmock restores non-top objects current install, not initial'); $m1->unmock('foo'); is(Stacked::foo(), 'original_foo', 'all unmocked: original restored'); } # Re-mock by top object also stays consistent { my $m1 = Test::MockModule->new('Stacked', distinct => 1); $m1->mock('foo', sub { 'a' }); my $m2 = Test::MockModule->new('Stacked', distinct => 1); $m2->mock('foo', sub { 'b1' }); $m2->mock('foo', sub { 'b2' }); is(Stacked::foo(), 'b2', 'top re-mock active'); $m2->unmock('foo'); is(Stacked::foo(), 'a', 'top unmock falls back to non-top install'); } # Mid-stack unmock after a non-top re-mock must NOT leave the unmocked # layer's clobbered coderef installed at the symbol. The non-top re-mock # overwrote *Pkg::sub with the layer's installed coderef (per the documented # "most recent mock wins" contract), so when that layer is removed the # symbol must be restored to the layer that's still on top. { my $m1 = Test::MockModule->new('Stacked', distinct => 1); $m1->mock('foo', sub { 'A' }); my $m2 = Test::MockModule->new('Stacked', distinct => 1); $m2->mock('foo', sub { 'B' }); # Non-top re-mock by m1 clobbers the symbol to C. $m1->mock('foo', sub { 'C' }); is(Stacked::foo(), 'C', 'non-top re-mock clobbers symbol (documented)'); # m1 unmocks while m2 is still on top. Symbol must reflect m2's mock # (the layer that should still be active), not m1's stale install. $m1->unmock('foo'); is(Stacked::foo(), 'B', 'mid-stack unmock after non-top re-mock restores top layer'); $m2->unmock('foo'); is(Stacked::foo(), 'original_foo', 'all unmocked: original restored'); } # Same shape as above but via the destructor path. { my $m2; { my $m1 = Test::MockModule->new('Stacked', distinct => 1); $m1->mock('foo', sub { 'A' }); $m2 = Test::MockModule->new('Stacked', distinct => 1); $m2->mock('foo', sub { 'B' }); $m1->mock('foo', sub { 'C' }); # non-top re-mock is(Stacked::foo(), 'C', 'destructor path: clobber visible'); # m1 destructed here as scope exits. } is(Stacked::foo(), 'B', 'mid-stack DESTROY after non-top re-mock restores top layer'); undef $m2; is(Stacked::foo(), 'original_foo', 'destructor path: cleanup ok'); } # Three-layer middle-layer re-mock then middle-layer unmock: top layer # must be re-installed; the bottom layer remains untouched and is restored # correctly when the top eventually unmocks. { my $m1 = Test::MockModule->new('Stacked', distinct => 1); $m1->mock('foo', sub { 'L1' }); my $m2 = Test::MockModule->new('Stacked', distinct => 1); $m2->mock('foo', sub { 'L2' }); my $m3 = Test::MockModule->new('Stacked', distinct => 1); $m3->mock('foo', sub { 'L3' }); $m2->mock('foo', sub { 'L2_new' }); # middle re-mock; clobbers symbol is(Stacked::foo(), 'L2_new', 'middle re-mock clobbers symbol'); $m2->unmock('foo'); is(Stacked::foo(), 'L3', 'mid-stack unmock with non-empty layer above restores top (L3)'); $m3->unmock('foo'); is(Stacked::foo(), 'L1', 'after L3 gone: L1 still active'); $m1->unmock('foo'); is(Stacked::foo(), 'original_foo', 'three-layer cleanup'); } # GH #64 contract under stacking: define() then a non-top re-mock by the # defining object must still restore the originally-defined sub when all # layers have been unmocked. Without the fix, the GH #64 path captures # \&{$sub_name} -- which is another object's installed coderef when we are # not at top of stack -- and unmock leaves THAT sibling coderef installed # instead of the defined sub. { package Stacked64; ## no critic (Modules::RequireFilenameMatchesPackage) our $VERSION = 1; package main; ok(!defined &Stacked64::wrapper, 'Stacked64::wrapper does not exist initially'); my $m1 = Test::MockModule->new('Stacked64', no_auto => 1, distinct => 1); $m1->define('wrapper', sub { 'defined_value' }); my $m2 = Test::MockModule->new('Stacked64', no_auto => 1, distinct => 1); $m2->mock('wrapper', sub { 'sibling_value' }); # m1 (non-top) redefines its own defined sub. Per the documented # "most recent mock wins" contract, the symbol now holds m1's new # coderef. The internal _orig bookkeeping must capture m1's PRIOR # install ('defined_value'), not the symbol's current value # ('sibling_value'). $m1->mock('wrapper', sub { 'redefined_value' }); is(Stacked64::wrapper(), 'redefined_value', 'GH #64 + stacking: m1 redef visible'); $m2->unmock('wrapper'); is(Stacked64::wrapper(), 'redefined_value', 'GH #64 + stacking: m1 redef stays visible after m2 unmocks'); $m1->unmock('wrapper'); is(Stacked64::wrapper(), 'defined_value', 'GH #64 + stacking: unmock restores the defined sub, not a siblings coderef'); } done_testing; Test-MockModule-v0.185.0/t/original_for.t000444001751001751 537115177114646 20317 0ustar00runnerrunner000000000000use warnings; use strict; use Test::More; use Test::MockModule; package Tgt::OriginalFor; ## no critic (Modules::RequireFilenameMatchesPackage) our $VERSION = 1; sub greet { 'hello' } sub other { 'other' } package main; ## no critic (Modules::RequireFilenameMatchesPackage) # 1. Returns the actual sub when not mocked { my $code = Test::MockModule->original_for('Tgt::OriginalFor', 'greet'); is(ref($code), 'CODE', 'returns a coderef when sub is not mocked'); is($code->(), 'hello', '... that calls the real implementation'); } # 2. Returns the truly-original (not the active mock) when mocked { my $mock = Test::MockModule->new('Tgt::OriginalFor'); $mock->mock('greet', sub { 'mocked' }); is(Tgt::OriginalFor::greet(), 'mocked', 'symbol table now holds the mock'); my $orig = Test::MockModule->original_for('Tgt::OriginalFor', 'greet'); is($orig->(), 'hello', 'original_for returns the pre-mock implementation, not the mock'); $mock->unmock_all; } # 3. Recommended GH #83-safe pattern: closure captures strings, not $mock. # Works under distinct => 1 mode because there is no $mock capture. { my @results; my $run = sub { my ($label) = @_; my $mock = Test::MockModule->new( 'Tgt::OriginalFor', no_auto => 1, distinct => 1 ); $mock->mock('greet', sub { return Test::MockModule ->original_for('Tgt::OriginalFor', 'greet')->() . "_$label"; }); push @results, Tgt::OriginalFor::greet(); }; $run->('first'); $run->('second'); is_deeply \@results, ['hello_first', 'hello_second'], 'original_for pattern works under distinct => 1 (no leak)'; } # 4. Stacked mocks: original_for still returns the truly-original { my $m1 = Test::MockModule->new('Tgt::OriginalFor', distinct => 1); $m1->mock('other', sub { 'L1' }); { my $m2 = Test::MockModule->new('Tgt::OriginalFor', distinct => 1); $m2->mock('other', sub { 'L2' }); is(Tgt::OriginalFor::other(), 'L2', 'top mock wins'); my $orig = Test::MockModule->original_for('Tgt::OriginalFor', 'other'); is($orig->(), 'other', 'original_for returns pre-any-mock impl, not the layer below'); } $m1->unmock_all; } # 5. Invalid args croak { eval { Test::MockModule->original_for('', 'foo') }; like($@, qr/Invalid package name/, 'empty package croaks'); eval { Test::MockModule->original_for('Tgt::OriginalFor', '') }; like($@, qr/valid function name/i, 'empty sub name croaks'); } # 6. Looking up a sub that doesn't exist returns undef without crashing { my $code = Test::MockModule->original_for('Tgt::OriginalFor', 'nonexistent'); is($code, undef, 'returns undef for nonexistent sub'); } done_testing; Test-MockModule-v0.185.0/t/pod.t000444001751001751 27215177114646 16402 0ustar00runnerrunner000000000000use warnings; use strict; use Test::More; eval { require Test::Pod; Test::Pod->import(1.00); 1 } or plan skip_all => "Test::Pod 1.00 required for testing POD"; all_pod_files_ok(); Test-MockModule-v0.185.0/t/pod_coverage.t000444001751001751 42415177114646 20254 0ustar00runnerrunner000000000000use warnings; use strict; use Test::More; eval { require Test::Pod::Coverage; Test::Pod::Coverage->import(1.00); 1 } or plan skip_all => "Test::Pod::Coverage 1.00 required for testing pod coverage"; all_pod_coverage_ok({also_private => [qr/^TRACE(?:F|_HERE)?|DUMP$/]}); Test-MockModule-v0.185.0/t/prototype.t000444001751001751 211515177114646 17703 0ustar00runnerrunner000000000000use warnings; use strict; use Test::More; use Test::Warnings; package Mockee; ## no critic (Modules::RequireFilenameMatchesPackage) sub good ($$); ## no critic (Subroutines::ProhibitSubroutinePrototypes) sub good ($$) { ## no critic (Subroutines::ProhibitSubroutinePrototypes) my ( $bar, $baz ) = @_; return ( $bar + 1, $baz + 2 ); } 1; package main; use Test::MockModule; $INC{'Mockee.pm'} = 1; my $mocker = Test::MockModule->new('Mockee'); # Verify original behavior my @orig = Mockee::good(10, 20); is_deeply(\@orig, [11, 22], 'original prototyped sub works'); # Redefine with a scalar value (no warnings expected for prototype mismatch) $mocker->redefine( 'good', 42 ); is(Mockee::good(1, 2), 42, 'prototyped sub can be redefined with scalar'); # Redefine with a coderef $mocker->redefine( 'good', sub { return $_[0] * $_[1] } ); is(Mockee::good(3, 7), 21, 'prototyped sub can be redefined with coderef'); # Unmock restores original $mocker->unmock('good'); @orig = Mockee::good(10, 20); is_deeply(\@orig, [11, 22], 'unmock restores original prototyped sub'); done_testing(); Test-MockModule-v0.185.0/t/redefine.t000444001751001751 161115177114646 17417 0ustar00runnerrunner000000000000use 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; ## no critic (Modules::RequireFilenameMatchesPackage) our $VERSION; BEGIN { $VERSION = 1 }; sub good { 1 } #---------------------------------------------------------------------- package MockeeWithDestroy; ## no critic (Modules::RequireFilenameMatchesPackage) our $VERSION; BEGIN { $VERSION = 1 }; sub DESTROY { print 'bad' if $_[0][1] }; 1; Test-MockModule-v0.185.0/t/strict_scoped_files.t000444001751001751 72015177114646 21645 0ustar00runnerrunner000000000000use 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.185.0/t/lib000755001751001751 015177114646 16063 5ustar00runnerrunner000000000000Test-MockModule-v0.185.0/t/lib/ExampleModule.pm000444001751001751 32015177114646 21272 0ustar00runnerrunner000000000000package 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.185.0/t/lib/Issue55000755001751001751 015177114646 17325 5ustar00runnerrunner000000000000Test-MockModule-v0.185.0/t/lib/Issue55/MooseAroundChild.pm000444001751001751 16015177114646 23174 0ustar00runnerrunner000000000000package Issue55::MooseAroundChild; use Moose; extends 'Issue55::MooseAroundParent'; around foo => sub { 2 }; 1; Test-MockModule-v0.185.0/t/lib/Issue55/MooseAroundChildOrig.pm000444001751001751 31215177114646 24014 0ustar00runnerrunner000000000000package Issue55::MooseAroundChildOrig; use Moose; extends 'Issue55::MooseAroundParent'; around foo => sub { my ($orig, $self, @args) = @_; return 'wrapped(' . $orig->($self, @args) . ')'; }; 1; Test-MockModule-v0.185.0/t/lib/Issue55/MooseAroundParent.pm000444001751001751 10015177114646 23374 0ustar00runnerrunner000000000000package Issue55::MooseAroundParent; use Moose; sub foo { 1 } 1; Test-MockModule-v0.185.0/t/lib/ScopedStrict000755001751001751 015177114646 20471 5ustar00runnerrunner000000000000Test-MockModule-v0.185.0/t/lib/ScopedStrict/Mockee1.pm000444001751001751 17515177114646 22433 0ustar00runnerrunner000000000000package ScopedStrict::Mockee1; use strict; use warnings; sub gonna_mock_this { return "you're not going to see this" } 1; Test-MockModule-v0.185.0/t/lib/ScopedStrict/Mockee2.pm000444001751001751 21115177114646 22423 0ustar00runnerrunner000000000000package ScopedStrict::Mockee2; use strict; use warnings; sub also_gonna_mock_this { return "you're not going to see this either" } 1; Test-MockModule-v0.185.0/t/lib/ScopedStrict/NonStrictMocker.pm000444001751001751 32015177114646 24223 0ustar00runnerrunner000000000000package 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.185.0/t/lib/ScopedStrict/StrictMocker.pm000444001751001751 31715177114646 23556 0ustar00runnerrunner000000000000package ScopedStrict::StrictMocker; use strict; use warnings; use Test::MockModule qw(strict); Test::MockModule->new('ScopedStrict::Mockee1')->redefine( gonna_mock_this => sub { "mocked sub" } ); 1;