Test-MockModule-v0.171.0000755000000000000 013552627430 14130 5ustar00rootroot000000000000Test-MockModule-v0.171.0/Build.PL000444000000000000 174113552627430 15564 0ustar00rootroot000000000000use strict; use warnings; use Module::Build; my $builder = Module::Build->new( module_name => 'Test::MockModule', create_license => 1, license => 'perl', dist_author => [q{Current Maintainer: Geoff Franks }, q{Original Author: Simon Flack }], meta_merge => { resources => { homepage => 'https://github.com/geofffranks/test-mockmodule', bugtracker => 'https://github.com/geofffranks/test-mockmodule/issues', repository => 'git://github.com/geofffranks/test-mockmodule.git', }, }, configure_requires => { 'Module::Build' => '0.38', }, requires => { 'perl' => 5.006, 'Carp' => 0, 'Scalar::Util' => 0, 'SUPER' => 0, }, build_requires => { 'Test::More' => 0.88, 'Test::Warnings' => 0 }, add_to_cleanup => [ 'Test-MockModule-*', 'cover_db', '*.rpm', '*.deb', ] ); $builder->create_build_script(); Test-MockModule-v0.171.0/Changes000444000000000000 677713552627430 15601 0ustar00rootroot000000000000Revision history for Test::MockModule 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.171.0/LICENSE000444000000000000 4431213552627430 15316 0ustar00rootroot000000000000This software is copyright (c) 2019 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) 2019 by Current Maintainer: Geoff Franks & Original Author: Simon Flack . This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2019 by Current Maintainer: Geoff Franks & Original Author: Simon Flack . This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End Test-MockModule-v0.171.0/MANIFEST000444000000000000 55313552627430 15401 0ustar00rootroot000000000000Build.PL Changes ci/Dockerfile ci/pipeline.yml ci/repipe ci/scripts/shipit ci/scripts/testflight ci/settings.yml lib/Test/MockModule.pm LICENSE MANIFEST This list of files MANIFEST.SKIP README.md t/chaining.t t/define.t t/inheritance.t t/lib/ExampleModule.pm t/mock_strict.t t/mockmodule.t t/pod.t t/pod_coverage.t t/prototype.t t/redefine.t META.yml META.json Test-MockModule-v0.171.0/MANIFEST.SKIP000444000000000000 233613552627430 16167 0ustar00rootroot000000000000 #!start included /usr/share/perl/5.14/ExtUtils/MANIFEST.SKIP # Avoid version control files. \bRCS\b \bCVS\b \bSCCS\b ,v$ \B\.svn\b \B\.git\b \B\.gitignore\b \b_darcs\b \B\.cvsignore$ # Avoid VMS specific MakeMaker generated files \bDescrip.MMS$ \bDESCRIP.MMS$ \bdescrip.mms$ # Avoid Makemaker generated and utility files. \bMANIFEST\.bak \bMakefile$ \bblib/ \bMakeMaker-\d \bpm_to_blib\.ts$ \bpm_to_blib$ \bblibdirs\.ts$ # 6.18 through 6.25 generated this # Avoid Module::Build generated and utility files. \bBuild$ \b_build/ \bBuild.bat$ \bBuild.COM$ \bBUILD.COM$ \bbuild.com$ # Avoid temp and backup files. ~$ \.old$ \#$ \b\.# \.bak$ \.tmp$ \.# \.rej$ # Avoid OS-specific files/dirs # Mac OSX metadata \B\.DS_Store # Mac OSX SMB mount metadata files \B\._ # Avoid Devel::Cover and Devel::CoverX::Covered files. \bcover_db\b \bcovered\b # Avoid MYMETA files ^MYMETA\. #!end included /usr/share/perl/5.14/ExtUtils/MANIFEST.SKIP # Avoid configuration metadata file ^MYMETA\. # Avoid Module::Build generated and utility files. \bBuild$ \bBuild.bat$ \b_build \bBuild.COM$ \bBUILD.COM$ \bbuild.com$ #^MANIFEST\.SKIP # Avoid archives of this distribution ^Test-MockModule-* ^t/tmp # Avoid Travis-CI configuration file \.travis.yml Test-MockModule-v0.171.0/META.json000444000000000000 300213552627430 15701 0ustar00rootroot000000000000{ "abstract" : "Override subroutines in a module for unit testing", "author" : [ "Current Maintainer: Geoff Franks ", "Original Author: Simon Flack " ], "dynamic_config" : 1, "generated_by" : "Module::Build version 0.4224", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Test-MockModule", "prereqs" : { "build" : { "requires" : { "Test::More" : "0.88", "Test::Warnings" : "0" } }, "configure" : { "requires" : { "Module::Build" : "0.38" } }, "runtime" : { "requires" : { "Carp" : "0", "SUPER" : "0", "Scalar::Util" : "0", "perl" : "5.006" } } }, "provides" : { "Test::MockModule" : { "file" : "lib/Test/MockModule.pm", "version" : "v0.171.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.171.0", "x_serialization_backend" : "JSON::PP version 2.27400_02" } Test-MockModule-v0.171.0/META.yml000444000000000000 174713552627430 15547 0ustar00rootroot000000000000--- abstract: 'Override subroutines in a module for unit testing' author: - 'Current Maintainer: Geoff Franks ' - 'Original Author: Simon Flack ' build_requires: Test::More: '0.88' Test::Warnings: '0' configure_requires: Module::Build: '0.38' dynamic_config: 1 generated_by: 'Module::Build version 0.4224, CPAN::Meta::Converter version 2.150010' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Test-MockModule provides: Test::MockModule: file: lib/Test/MockModule.pm version: v0.171.0 requires: Carp: '0' SUPER: '0' 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.171.0 x_serialization_backend: 'CPAN::Meta::YAML version 0.018' Test-MockModule-v0.171.0/README.md000444000000000000 77513552627430 15535 0ustar00rootroot000000000000# Test::MockModule - mock subroutines in a module See the LICENSE section in `lib/Test/MockModule.pm` for usage and distribution rights. ## Installation Run these commands in the source directory: perl Build.PL ./Build ./Build test ./Build install Then delete the source directory tree since it's no longer needed. Alternatively, you can simply install the module via `cpanm`: cpanm Test::MockModule ## Documentation Run `perldoc Test::MockModule` to read the full documentation. Test-MockModule-v0.171.0/ci000755000000000000 013552627430 14523 5ustar00rootroot000000000000Test-MockModule-v0.171.0/ci/Dockerfile000444000000000000 40713552627430 16633 0ustar00rootroot000000000000FROM ubuntu:bionic ENV DEBIAN_FRONTEND=noninteractive RUN apt-get update RUN apt-get install -y git libmodule-build-perl libsuper-perl libtest-warnings-perl libsuper-perl libtest-warnings-perl libtest-pod-coverage-perl libdevel-cover-perl libcpan-uploader-perl Test-MockModule-v0.171.0/ci/pipeline.yml000444000000000000 2474313552627430 17242 0ustar00rootroot000000000000--- # # ci/pipeline.yml # meta: name: (( param "Please name your pipeline" )) release: (( grab meta.name )) target: (( param "Please identify the name of the target Concourse CI" )) url: (( param "Please specify the full url of the target Concourse CI" )) pipeline: (( grab meta.name )) cpan: user: (( param "What is the username to use for uploading to CPAN?" )) password: (( param "What is the password to use for uplaoding to CPAN?" )) image: name: starkandwayne/concourse tag: latest aws: bucket: (( concat meta.pipeline "-pipeline" )) region_name: us-east-1 access_key: (( param "Please set your AWS Access Key ID for your pipeline S3 Bucket" )) secret_key: (( param "Please set your AWS Secret Key ID for your pipeline S3 Bucket" )) github: uri: (( concat "git@github.com:" meta.github.owner "/" meta.github.repo )) owner: (( param "Please specify the name of the user / organization that owns the Github repository" )) repo: (( param "Please specify the name of the Github repository" )) branch: master private_key: (( param "Please generate an SSH Deployment Key for this repo and specify it here" )) access_token: (( param "Please generate a Personal Access Token to be used for creating github releases (do you have a ci-bot?)" )) slack: webhook: (( param "Please specify your Slack Incoming Webhook Integration URL" )) success_moji: ":airplane_departure:" fail_moji: ":airplane_arriving:" upset_moji: ":sad_panda:" channel: (( param "Please specify the channel (#name) or user (@user) to send messages to" )) username: concourse icon: http://cl.ly/image/3e1h0H3H2s0P/concourse-logo.png fail_url: '(( concat "<" meta.url "/teams/$BUILD_TEAM_NAME/pipelines/$BUILD_PIPELINE_NAME/jobs/$BUILD_JOB_NAME/builds/$BUILD_NAME| Concourse Failure! " meta.slack.upset_moji ">" ))' groups: - name: (( grab meta.pipeline )) jobs: - testflight - testflight-pr - pre - rc - shipit - major jobs: - name: testflight public: true serial: true plan: - do: - aggregate: - { get: git, trigger: true } - task: testflight config: platform: linux image_resource: type: docker-image source: repository: (( grab meta.image.name )) tag: (( grab meta.image.tag )) inputs: - { name: git } run: path: ./git/ci/scripts/testflight args: [] params: REPO_ROOT: git on_failure: put: notify params: channel: (( grab meta.slack.channel )) username: (( grab meta.slack.username )) icon_url: (( grab meta.slack.icon )) text: '(( concat meta.slack.fail_url " " meta.pipeline ": testflight job failed" ))' - name: testflight-pr public: true serial: true plan: - do: - { get: git-pull-requests, trigger: true, version: every } - put: git-pull-requests params: path: git-pull-requests status: pending - task: testflight config: platform: linux image_resource: type: docker-image source: repository: (( grab meta.image.name )) tag: (( grab meta.image.tag )) inputs: - { name: git-pull-requests } run: path: ./git-pull-requests/ci/scripts/testflight args: [] params: REPO_ROOT: git-pull-requests on_success: put: git-pull-requests params: path: git-pull-requests status: success on_failure: put: git-pull-requests params: path: git-pull-requests status: failure - task: pr-success-message config: platform: linux image_resource: type: docker-image source: repository: (( grab meta.image.name )) tag: (( grab meta.image.tag )) inputs: - { name: git-pull-requests } outputs: - { name: message } run: path: sh args: - -ce - | cd git-pull-requests pr_url=$(git config --get pullrequest.url) cd - echo "<${pr_url}|Pull request passed testflight> Merge when ready: ${pr_url}" > message/body on_success: put: notify params: channel: (( grab meta.slack.channel )) username: (( grab meta.slack.username )) icon_url: (( grab meta.slack.icon )) text_file: message/body - name: pre public: true serial: true plan: - do: - get: git passed: - testflight trigger: true - get: version trigger: true - task: release-notes config: platform: linux image_resource: type: docker-image source: repository: (( grab meta.image.name )) tag: (( grab meta.image.tag )) run: path: sh args: - -ce - | cd git if [ -f ci/release_notes.md ]; then echo "###### RELEASE NOTES ###############" echo cat ci/release_notes.md echo echo "########################################" echo else echo "NO RELEASE NOTES HAVE BEEN WRITTEN" echo "You *might* want to do that before" echo "hitting (+) on that shipit job..." echo fi inputs: - name: git on_failure: put: notify params: channel: (( grab meta.slack.channel )) username: (( grab meta.slack.username )) icon_url: (( grab meta.slack.icon )) text: release candidate job 'pre' failed (which is unusual). ok: false - name: rc public: true plan: - do: - aggregate: - { get: git, trigger: true, passed: [pre] } - { get: version, trigger: false, params: {pre: rc} } - put: version params: {file: version/number} on_failure: put: notify params: channel: (( grab meta.slack.channel )) username: (( grab meta.slack.username )) icon_url: (( grab meta.slack.icon )) text: '(( concat meta.slack.fail_url " " meta.pipeline ": rc job failed" ))' - name: major public: true plan: - do: - { get: version, trigger: false, params: {bump: major} } - { put: version, params: {file: version/number} } on_failure: put: notify params: channel: (( grab meta.slack.channel )) username: (( grab meta.slack.username )) icon_url: (( grab meta.slack.icon )) text: '(( concat meta.slack.fail_url " " meta.pipeline ": major job failed" ))' - name: shipit public: true serial: true plan: - do: - name: inputs aggregate: - { get: version, passed: [rc], params: {bump: final} } - { get: git, passed: [rc] } - name: release task: release config: platform: linux image_resource: type: docker-image source: repository: (( grab meta.image.name )) tag: (( grab meta.image.tag )) inputs: - name: version - name: git outputs: - name: gh - name: pushme - name: notifications run: path: ./git/ci/scripts/shipit args: [] params: REPO_ROOT: git VERSION_FROM: version/number RELEASE_ROOT: gh REPO_OUT: pushme NOTIFICATION_OUT: notifications BRANCH: (( grab meta.github.branch )) GITHUB_OWNER: (( grab meta.github.owner )) CPAN_USER: (( grab meta.cpan.user )) CPAN_PASSWORD: (( grab meta.cpan.password )) AWS_ACCESS_KEY: (( grab meta.aws.access_key )) AWS_SECRET_KEY: (( grab meta.aws.secret_key )) - name: upload-git put: git params: rebase: true repository: pushme/git - name: github-release put: github params: name: gh/name tag: gh/tag body: gh/notes.md globs: [gh/artifacts/*] - name: version-bump put: version params: bump: minor on_failure: put: notify params: channel: (( grab meta.slack.channel )) username: (( grab meta.slack.username )) icon_url: (( grab meta.slack.icon )) text: '(( concat meta.slack.fail_url " " meta.pipeline ": shipit job failed" ))' resource_types: - name: slack-notification type: docker-image source: repository: cfcommunity/slack-notification-resource - name: pull-request type: docker-image source: repository: jtarchie/pr resources: - name: git type: git source: uri: (( grab meta.github.uri )) branch: (( grab meta.github.branch )) private_key: (( grab meta.github.private_key )) - name: git-pull-requests type: pull-request source: access_token: (( grab meta.github.access_token )) private_key: (( grab meta.github.private_key )) repo: (( concat meta.github.owner "/" meta.github.repo )) base: (( grab meta.github.branch )) - name: version type: semver source : driver: s3 bucket: (( grab meta.aws.bucket )) region_name: (( grab meta.aws.region_name )) key: version access_key_id: (( grab meta.aws.access_key )) secret_access_key: (( grab meta.aws.secret_key )) initial_version: (( grab meta.initial_version || "0.170.0" )) - name: notify type: slack-notification source: url: (( grab meta.slack.webhook )) - name: github type: github-release source: user: (( grab meta.github.owner )) repository: (( grab meta.github.repo )) access_token: (( grab meta.github.access_token )) Test-MockModule-v0.171.0/ci/repipe000555000000000000 642513552627430 16101 0ustar00rootroot000000000000#!/bin/bash # # ci/repipe # # Script for merging together pipeline configuration files # (via Spruce!) and configuring Concourse. # # author: James Hunt # Dennis Bell # created: 2016-03-04 need_command() { local cmd=${1:?need_command() - no command name given} if [[ ! -x "$(command -v $cmd)" ]]; then echo >&2 "${cmd} is not installed." if [[ "${cmd}" == "spruce" ]]; then echo >&2 "Please download it from https://github.com/geofffranks/spruce/releases" fi exit 2 fi } NO_FLY= SAVE_MANIFEST= VALIDATE_PIPELINE= NON_INTERACTIVE= cleanup() { rm -f save-manifest.yml if [[ -n ${SAVE_MANIFEST} && -e .deploy.yml ]]; then mv .deploy.yml save-manifest.yml fi rm -f .deploy.yml } usage() { echo Command line arguments: echo "no-fly Do not execute any fly commands" echo "save-manifest Save manifest to file save-manifest" echo "validate Validatei pipeline instead of set pipeline" echo "validate-strict Validate pipeline with strict mode" echo "non-interactivet Run set-pipeline in non-interactive mode" } for arg do case "${arg}" in no-fly|no_fly) NO_FLY="yes" ;; save-manifest|save_manifest) SAVE_MANIFEST="yes" ;; validate) VALIDATE_PIPELINE="normal" ;; validate-strict|validate_strict) VALIDATE_PIPELINE="strict" ;; non-interactive|non_interactive) NON_INTERACTIVE="--non-interactive" ;; help|-h|--help) usage; exit 0 ;; *) echo Invalid argument usage exit 1 esac done cd $(dirname $BASH_SOURCE[0]) echo "Working in $(pwd)" need_command spruce # Allow for target-specific settings settings_file="$(ls -1 settings.yml ${CONCOURSE_TARGET:+"settings-${CONCOURSE_TARGET}.yml"} 2>/dev/null | tail -n1)" if [[ -z "$settings_file" ]] then echo >&2 "Missing local settings in ci/settings.yml${CONCOURSE_TARGET:+" or ci/settings-${CONCOURSE_TARGET}.yml"}!" exit 1 fi echo >&2 "Using settings found in ${settings_file}" set -e trap "cleanup" QUIT TERM EXIT INT spruce merge pipeline.yml ${settings_file} > .deploy.yml PIPELINE=$(spruce json .deploy.yml | jq -r '.meta.pipeline // ""') if [[ -z ${PIPELINE} ]]; then echo >&2 "Missing pipeline name in ci/settings.yml!" exit 1 fi TARGET_FROM_SETTINGS=$(spruce json .deploy.yml | jq -r '.meta.target // ""') if [[ -z ${CONCOURSE_TARGET} ]]; then TARGET=${TARGET_FROM_SETTINGS} elif [[ "$CONCOURSE_TARGET" != "$TARGET_FROM_SETTINGS" ]] then echo >&2 "Target in {$settings_file} differs from target in \$CONCOURSE_TARGET" echo >&2 " \$CONCOURSE_TARGET: $CONCOURSE_TARGET" echo >&2 " Target in file: $TARGET_FROM_SETTINGS" exit 1 else TARGET=${CONCOURSE_TARGET} fi if [[ -z ${TARGET} ]]; then echo >&2 "Missing Concourse Target in ci/settings.yml!" exit 1 fi fly_cmd="${FLY_CMD:-fly}" [[ -n ${NO_FLY} ]] && { echo no fly execution requested ; exit 0; } case "${VALIDATE_PIPELINE}" in normal) fly_opts="validate-pipeline" ;; strict) fly_opts="validate-pipeline --strict" ;; *) fly_opts="set-pipeline ${NON_INTERACTIVE} --pipeline ${PIPELINE}" ;; esac set +x $fly_cmd --target ${TARGET} ${fly_opts} --config .deploy.yml [[ -n ${VALIDATE_PIPELINE} ]] && exit 0 $fly_cmd --target ${TARGET} unpause-pipeline --pipeline ${PIPELINE} Test-MockModule-v0.171.0/ci/settings.yml000444000000000000 233313552627430 17244 0ustar00rootroot000000000000--- meta: name: perl5-test-mockmodule target: ci.spruce.cf url: https://ci.spruce.cf image: name: gfranks/cpan-uploader aws: access_key: (( vault "secret/aws/cfcommunity:access" )) secret_key: (( vault "secret/aws/cfcommunity:secret" )) cpan: user: (( vault "secret/pipelines/test-mockmodule/cpan:user" )) password: (( vault "secret/pipelines/test-mockmodule/cpan:password" )) github: owner: geofffranks repo: test-mockmodule branch: master private_key: (( vault "secret/pipelines/test-mockmodule/github:private" )) access_token: (( vault "secret/pipelines/test-mockmodule/github:token" )) slack: webhook: (( vault "secret/pipelines/test-mockmodule/slack:webhook" )) channel: '@gfranks' username: ci-bot blob_success: '(( concat "$BUILD_PIPELINE_NAME: New version of $BUILD_JOB_NAME was detected, and updated in master. <" meta.url "/teams/$BUILD_TEAM_NAME/pipelines/$BUILD_PIPELINE_NAME| Cut a new release?>" ))' blob_failure: '(( concat "$BUILD_PIPELINE_NAME: :airplane_arriving: <" meta.url "/teams/$BUILD_TEAM_NAME/pipelines/$BUILD_PIPELINE_NAME/jobs/$BUILD_JOB_NAME/builds/$BUILD_NAME| Failed to update the blob for $BUILD_JOB_NAME>" ))' Test-MockModule-v0.171.0/ci/scripts000755000000000000 013552627430 16212 5ustar00rootroot000000000000Test-MockModule-v0.171.0/ci/scripts/shipit000555000000000000 422213552627430 17575 0ustar00rootroot000000000000#!/bin/bash set -eu header() { echo echo "###############################################" echo echo $* echo } : ${REPO_ROOT:?required} : ${RELEASE_ROOT:?required} : ${REPO_OUT:?required} : ${BRANCH:?required} : ${GITHUB_OWNER:?required} : ${VERSION_FROM:?required} if [[ ! -f ${VERSION_FROM} ]]; then echo >&2 "Version file (${VERSION_FROM}) not found. Did you misconfigure Concourse?" exit 2 fi VERSION=$(cat ${VERSION_FROM}) if [[ -z ${VERSION} ]]; then echo >&2 "Version file (${VERSION_FROM}) was empty. Did you misconfigure Concourse?" exit 2 fi DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" ############################################################### header "Generating release notes..." pushd ${REPO_ROOT} changes=$(git log --pretty="- %h %s - %an" $(git describe --tags | cut -d - -f1)..HEAD) old_changes=$(tail -n +3 Changes) cat < Changes Revision history for Test::MockModule v${VERSION} $changes $old_changes EOF popd header "Updating module version..." pushd ${REPO_ROOT} sed -i "s/\$VERSION = '.*';/\$VERSION = '$VERSION';/" lib/Test/MockModule.pm header "Creating distribution tarball..." perl Build.PL ./Build manifest ./Build dist header "Uploading distribution to cpan..." cat < ~/.pause user ${CPAN_USER} password ${CPAN_PASSWORD} EOF cpan-upload *.tar.gz popd mkdir -p ${RELEASE_ROOT}/artifacts echo "${VERSION}" > ${RELEASE_ROOT}/tag echo "v${VERSION}" > ${RELEASE_ROOT}/name mv ${REPO_ROOT}/*-v${VERSION}.tar.gz ${RELEASE_ROOT}/artifacts [ -f ${REPO_ROOT}/ci/release_notes.md ] && mv ${REPO_ROOT}/ci/release_notes.md ${RELEASE_ROOT}/notes.md cat <>${RELEASE_ROOT}/notes.md # Changes $changes EOF header "Updating git repo with release..." if [[ -z $(git config --global user.email) ]]; then git config --global user.email "ci@starkandwayne.com" fi if [[ -z $(git config --global user.name) ]]; then git config --global user.name "CI Bot" fi (cd ${REPO_ROOT} git merge --no-edit ${BRANCH} git add -A git status git commit -m "release v${VERSION}") # so that future steps in the pipeline can push our changes cp -a ${REPO_ROOT} ${REPO_OUT} Test-MockModule-v0.171.0/ci/scripts/testflight000555000000000000 47313552627430 20436 0ustar00rootroot000000000000#!/bin/bash header() { echo echo "###############################################" echo echo $* echo } #!/bin/bash set -e pushd ${REPO_ROOT} perl Build.PL header "Running tests..." ./Build test header "Testing POD coverage..." ./Build testpodcoverage header "Examining test coverage..." ./Build testcover Test-MockModule-v0.171.0/lib000755000000000000 013552627430 14676 5ustar00rootroot000000000000Test-MockModule-v0.171.0/lib/Test000755000000000000 013552627430 15615 5ustar00rootroot000000000000Test-MockModule-v0.171.0/lib/Test/MockModule.pm000444000000000000 3263313552627430 20376 0ustar00rootroot000000000000package Test::MockModule; use warnings; use strict qw/subs vars/; use vars qw/$VERSION/; use Scalar::Util qw/reftype weaken/; use Carp; use SUPER; $VERSION = '0.171.0'; our $STRICT_MODE; sub import { my ( $class, @args ) = @_; $STRICT_MODE = 1 if ( grep { $_ =~ m/strict/i } @args ); return; } my %mocked; sub new { my $class = shift; my ($package, %args) = @_; if ($package && (my $existing = $mocked{$package})) { return $existing; } croak "Cannot mock $package" if $package && $package eq $class; unless (_valid_package($package)) { $package = 'undef' unless defined $package; croak "Invalid package name $package"; } unless ($package eq "CORE::GLOBAL" || $args{no_auto} || ${"$package\::VERSION"}) { (my $load_package = "$package.pm") =~ s{::}{/}g; TRACE("$package is empty, loading $load_package"); require $load_package; } TRACE("Creating MockModule object for $package"); my $self = bless { _package => $package, _mocked => {}, }, $class; $mocked{$package} = $self; weaken $mocked{$package}; return $self; } sub DESTROY { my $self = shift; $self->unmock_all; } sub get_package { my $self = shift; return $self->{_package}; } sub redefine { my ($self, @mocks) = (shift, @_); while ( my ($name, $value) = splice @mocks, 0, 2 ) { my $sub_name = $self->_full_name($name); my $coderef = *{$sub_name}{'CODE'}; next if 'CODE' eq ref $coderef; if ( $sub_name =~ qr{^(.+)::([^:]+)$} ) { my ( $pkg, $sub ) = ( $1, $2 ); next if $pkg->can( $sub ); } if ('CODE' ne ref $coderef) { croak "$sub_name does not exist!"; } } return $self->_mock(@_); } sub define { my ($self, @mocks) = (shift, @_); while ( my ($name, $value) = splice @mocks, 0, 2 ) { my $sub_name = $self->_full_name($name); my $coderef = *{$sub_name}{'CODE'}; if ('CODE' eq ref $coderef) { croak "$sub_name exists!"; } } return $self->_mock(@_); } sub mock { my ($self, @mocks) = (shift, @_); croak "mock is not allowed in strict mode. Please use define or redefine" if $STRICT_MODE; return $self->_mock(@mocks); } sub _mock { my $self = shift; while (my ($name, $value) = splice @_, 0, 2) { my $code = sub { }; if (ref $value && reftype $value eq 'CODE') { $code = $value; } elsif (defined $value) { $code = sub {$value}; } TRACE("$name: $code"); croak "Invalid subroutine name: $name" unless _valid_subname($name); my $sub_name = _full_name($self, $name); if (!$self->{_mocked}{$name}) { TRACE("Storing existing $sub_name"); $self->{_mocked}{$name} = 1; if (defined &{$sub_name}) { $self->{_orig}{$name} = \&$sub_name; } else { $self->{_orig}{$name} = undef; } } TRACE("Installing mocked $sub_name"); _replace_sub($sub_name, $code); } return $self; } sub noop { my $self = shift; croak "noop is not allowed in strict mode. Please use define or redefine" if $STRICT_MODE; $self->_mock($_,1) for @_; return; } sub original { my $self = shift; my ($name) = @_; return carp _full_name($self, $name) . " is not mocked" unless $self->{_mocked}{$name}; return defined $self->{_orig}{$name} ? $self->{_orig}{$name} : $self->{_package}->super($name); } sub unmock { my $self = shift; for my $name (@_) { croak "Invalid subroutine name: $name" unless _valid_subname($name); my $sub_name = _full_name($self, $name); unless ($self->{_mocked}{$name}) { carp $sub_name . " was not mocked"; next; } TRACE("Restoring original $sub_name"); _replace_sub($sub_name, $self->{_orig}{$name}); delete $self->{_mocked}{$name}; delete $self->{_orig}{$name}; } return $self; } sub unmock_all { my $self = shift; foreach (keys %{$self->{_mocked}}) { $self->unmock($_); } return; } sub is_mocked { my $self = shift; my ($name) = shift; return $self->{_mocked}{$name}; } sub _full_name { my ($self, $sub_name) = @_; sprintf "%s::%s", $self->{_package}, $sub_name; } sub _valid_package { defined($_[0]) && $_[0] =~ /^[a-z_]\w*(?:::\w+)*$/i; } sub _valid_subname { $_[0] =~ /^[a-z_]\w*$/i; } sub _replace_sub { my ($sub_name, $coderef) = @_; no warnings 'redefine'; no warnings 'prototype'; if (defined $coderef) { *{$sub_name} = $coderef; } else { TRACE("removing subroutine: $sub_name"); my ($package, $sub) = $sub_name =~ /(.*::)(.*)/; my %symbols = %{$package}; # save a copy of all non-code slots my %slot; foreach (qw(ARRAY FORMAT HASH IO SCALAR)) { next unless defined(my $elem = *{$symbols{$sub}}{$_}); $slot{$_} = $elem; } # clear the symbol table entry for the subroutine undef *$sub_name; # restore everything except the code slot return unless keys %slot; foreach (keys %slot) { *$sub_name = $slot{$_}; } } } # Log::Trace stubs sub TRACE {} sub DUMP {} 1; =pod =head1 NAME Test::MockModule - Override subroutines in a module for unit testing =head1 SYNOPSIS use Module::Name; use Test::MockModule; { my $module = Test::MockModule->new('Module::Name'); $module->mock('subroutine', sub { ... }); Module::Name::subroutine(@args); # mocked # Same effect, but this will die() if other_subroutine() # doesn't already exist, which is often desirable. $module->redefine('other_subroutine', sub { ... }); # This will die() if another_subroutine() is defined. $module->define('another_subroutine', sub { ... }); } { # you can also chain new/mock/redefine/define Test::MockModule->new('Module::Name') ->mock( one_subroutine => sub { ... }) ->redefine( other_subroutine => sub { ... } ) ->define( a_new_sub => 1234 ); } Module::Name::subroutine(@args); # original subroutine # Working with objects use Foo; use Test::MockModule; { my $mock = Test::MockModule->new('Foo'); $mock->mock(foo => sub { print "Foo!\n"; }); my $foo = Foo->new(); $foo->foo(); # prints "Foo!\n" } # If you want to prevent noop and mock from working, you can # load Test::MockModule in strict mode use Test::MockModule qw/strict/; my $module = Test::MockModule->new('Module::Name'); # Redefined the other_subroutine or dies if it's not there. $module->redefine('other_subroutine', sub { ... }); # Dies since you specified you wanted strict mode. $module->mock('subroutine', sub { ... }); =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 METHODS =over 4 =item new($package[, %options]) Returns an object that will mock subroutines in the specified C<$package>. If there is no C<$VERSION> defined in C<$package>, the module will be automatically loaded. You can override this behaviour by setting the C option: my $mock = Test::MockModule->new('Module::Name', no_auto => 1); =item get_package() Returns the target package name for the mocked subroutines =item is_mocked($subroutine) Returns a boolean value indicating whether or not the subroutine is currently mocked =item mock($subroutine =E \Ecoderef) Temporarily replaces one or more subroutines in the mocked module. A subroutine can be mocked with a code reference or a scalar. A scalar will be recast as a subroutine that returns the scalar. Returns the current C object, so you can chain L with L. my $mock = Test::MockModule->new->(...)->mock(...); The following statements are equivalent: $module->mock(purge => 'purged'); $module->mock(purge => sub { return 'purged'}); When dealing with references, things behave slightly differently. The following statements are B equivalent: # Returns the same arrayref each time, with the localtime() at time of mocking $module->mock(updated => [localtime()]); # Returns a new arrayref each time, with up-to-date localtime() value $module->mock(updated => sub { return [localtime()]}); The following statements are in fact equivalent: my $array_ref = [localtime()] $module->mock(updated => $array_ref) $module->mock(updated => sub { return $array_ref }); However, C is a special case. If you mock a subroutine with C it will install an empty subroutine $module->mock(purge => undef); $module->mock(purge => sub { }); rather than a subroutine that returns C: $module->mock(purge => sub { undef }); You can call C for the same subroutine many times, but when you call C, the original subroutine is restored (not the last mocked instance). B If you are trying to mock a subroutine exported from another module, this may not behave as you initially would expect, since Test::MockModule is only mocking at the target module, not anything importing that module. If you mock the local package, or use a fully qualified function name, you will get the behavior you desire: use Test::MockModule; use Test::More; use POSIX qw/strftime/; my $posix = Test::MockModule->new("POSIX"); $posix->mock("strftime", "Yesterday"); is strftime("%D", localtime(time)), "Yesterday", "`strftime` was mocked successfully"; # Fails is POSIX::strftime("%D", localtime(time)), "Yesterday", "`strftime` was mocked successfully"; # Succeeds my $main = Test::MockModule->new("main", no_auto => 1); $main->mock("strftime", "today"); is strftime("%D", localtime(time)), "today", "`strftime` was mocked successfully"; # Succeeds If you are trying to mock a subroutine that was exported into a module that you're trying to test, rather than mocking the subroutine in its originating module, you can instead mock it in the module you are testing: package MyModule; use POSIX qw/strftime/; sub minus_twentyfour { return strftime("%a, %b %d, %Y", localtime(time - 86400)); } package main; use Test::More; use Test::MockModule; my $posix = Test::MockModule->new("POSIX"); $posix->mock("strftime", "Yesterday"); is MyModule::minus_twentyfour(), "Yesterday", "`minus-twentyfour` got mocked"; # fails my $mymodule = Test::MockModule->new("MyModule", no_auto => 1); $mymodule->mock("strftime", "Yesterday"); is MyModule::minus_twentyfour(), "Yesterday", "`minus-twentyfour` got mocked"; # succeeds =item redefine($subroutine) The same behavior as C, but this will preemptively check to be sure that all passed subroutines actually exist. This is useful to ensure that if a mocked module's interface changes the test doesn't just keep on testing a code path that no longer behaves consistently with the mocked behavior. Note that redefine is also now checking if one of the parent provides the sub and will not die if it's available in the chain. Returns the current C object, so you can chain L with L. my $mock = Test::MockModule->new->(...)->redefine(...); =item define($subroutine) The reverse of redefine, this will fail if the passed subroutine exists. While this use case is rare, there are times where the perl code you are testing is inspecting a package and adding a missing subroutine is actually what you want to do. By using define, you're asserting that the subroutine you want to be mocked should not exist in advance. Note: define does not check for inheritance like redefine. Returns the current C object, so you can chain L with L. my $mock = Test::MockModule->new->(...)->define(...); =item original($subroutine) Returns the original (unmocked) subroutine Here is a sample how to wrap a function with custom arguments using the original subroutine. This is useful when you cannot (do not) want to alter the original code to abstract one hardcoded argument pass to a function. package MyModule; sub sample { return get_path_for("/a/b/c/d"); } sub get_path_for { ... # anything goes there... } package main; use Test::MockModule; my $mock = Test::MockModule->new("MyModule"); # replace all calls to get_path_for using a different argument $mock->redefine("get_path_for", sub { return $mock->original("get_path_for")->("/my/custom/path"); }); # or $mock->redefine("get_path_for", sub { my $path = shift; if ( $path && $path eq "/a/b/c/d" ) { # only alter calls with path set to "/a/b/c/d" return $mock->original("get_path_for")->("/my/custom/path"); } else { # preserve the original arguments return $mock->original("get_path_for")->(@_); } }); =item unmock($subroutine [, ...]) Restores the original C<$subroutine>. You can specify a list of subroutines to C in one go. =item unmock_all() Restores all the subroutines in the package that were mocked. This is automatically called when all C objects for the given package go out of scope. =item noop($subroutine [, ...]) Given a list of subroutine names, mocks each of them with a no-op subroutine. Handy for mocking methods you want to ignore! # Neuter a list of methods in one go $module->noop('purge', 'updated'); =back =over 4 =item TRACE A stub for Log::Trace =item DUMP A stub for Log::Trace =back =head1 SEE ALSO L L =head1 AUTHORS Current Maintainer: Geoff Franks Original Author: Simon Flack Esimonflk _AT_ cpan.orgE =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.171.0/t000755000000000000 013552627430 14373 5ustar00rootroot000000000000Test-MockModule-v0.171.0/t/chaining.t000444000000000000 125713552627430 16502 0ustar00rootroot000000000000use warnings; use strict; use Test::More; use Test::Warnings; use Test::MockModule; my $mocker = Test::MockModule->new('Mockee')->mock( good => 51 ) ->redefine( to_redefine => sub { 42 } )->define( something => 1234 ); isa_ok $mocker, 'Test::MockModule'; is( Mockee::good(), 51, 'mock() works when chaining with new' ); is( Mockee::to_redefine(), 42, 'redefine() works when chaining with new' ); is( Mockee::something(), 1234, 'something() works when chaining with new' ); done_testing(); #---------------------------------------------------------------------- package Mockee; our $VERSION; BEGIN { $VERSION = 1 } sub good { 1 } sub to_redefine { 1 } 1; Test-MockModule-v0.171.0/t/define.t000444000000000000 164413552627430 16154 0ustar00rootroot000000000000use warnings; use strict; use Test::More; use Test::Warnings; use Test::MockModule; my $mocker = Test::MockModule->new('Mockee'); $mocker->define( 'doesnt_exist', 2 ); is( Mockee::doesnt_exist(), 2, 'define() allows us to mock nonexistant subroutines.' ); eval { $mocker->define( 'existing_subroutine', 6 ) }; like( $@, qr/Mockee::existing_subroutine exists\!/, 'exception when define()ing an existing subroutine' ); undef $mocker; is( Mockee->can('doesnt_exist'), undef, "the defined sub went away after mocker is undeffed" ); $mocker = Test::MockModule->new('Mockee'); $mocker->define( 'doesnt_exist', 3 ); is( Mockee::doesnt_exist(), 3, 'The subroutine can be defined again after the mock object goes out of scope and is re-instantiated.' ); done_testing(); #---------------------------------------------------------------------- package Mockee; our $VERSION; BEGIN { $VERSION = 1 } sub existing_subroutine { 1 } 1; Test-MockModule-v0.171.0/t/inheritance.t000444000000000000 526113552627430 17212 0ustar00rootroot000000000000use warnings; use strict; use Test::MockModule; use Test::More; use Test::Warnings; @Bar::ISA = 'Foo'; @Baz::ISA = 'Bar'; sub Foo::motto { 'Foo!' }; is(Foo->motto(), "Foo!", "pre-mock: Foo original motto is correct"); is(Bar->motto(), "Foo!", "pre-mock: Bar inherit's Foo's motto"); is(Baz->motto(), "Foo!", "pre-mock: Baz inherit's Bar's inheritance of Foo's motto"); { my $mock_bar = Test::MockModule->new('Bar', no_auto => 1); $mock_bar->mock('motto', sub { 'Bar!' }); is(Foo->motto(), "Foo!", "Foo motto is unchanged post-Bar mock"); is(Bar->motto(), "Bar!", "Bar motto has been mocked"); is(Baz->motto(), "Bar!", "Baz inherits from Bar's mocked motto"); is($mock_bar->original("motto")->(), "Foo!", "Bar's original function can still be reached correctly"); ok($mock_bar->is_mocked("motto"), "Baz's motto is really mocked"); my $mock_baz = Test::MockModule->new('Baz', no_auto => 1); $mock_baz->mock('motto', sub { 'Baz!' }); is(Foo->motto(), "Foo!", "Foo motto is unchanged post-Baz mock"); is(Bar->motto(), "Bar!", "Bar motto is unchanged post-Baz mock"); is(Baz->motto(), "Baz!", "Baz motto has been mocked"); is($mock_baz->original("motto")->(), "Bar!", "Baz's original function is Bar's mocked function"); ok($mock_baz->is_mocked("motto"), "Baz's motto is really mocked"); $mock_bar->unmock("motto"); is(Bar->motto, "Foo!", "Bar's motto is unmocked"); is($mock_baz->original("motto")->(), "Foo!", "Baz's original function is now magically inherited up to Foo"); } is(Foo->motto(), "Foo!", "post-unmock: Foo original motto is correct"); is(Bar->motto(), "Foo!", "post-unmock: Bar inherit's Foo's motto"); is(Baz->motto(), "Foo!", "post-unmock: Baz inherit's Bar's inheritance of Foo's motto"); { BEGIN { $INC{'Mother.pm'} = '__MOCKED__'; $INC{'InvalidChild.pm'} = '__MOCKED__'; $INC{'ValidChild.pm'} = '__MOCKED__'; } package Mother; sub do_something { 1 } package InvalidChild; sub abcd { 1 } package ValidChild; use parent q{Mother}; sub abcd { 1 } } package main; { my $mock_child = Test::MockModule->new( 'InvalidChild' ); local $@; ok ! eval { $mock_child->redefine( 'do_something', sub { 42 } ); 1 }, "cannot redefine do_something"; like $@, qr{InvalidChild::do_something does not exist!}, "throw a die"; } { my $mock_child = Test::MockModule->new( 'ValidChild' ); local $@; ok eval { $mock_child->redefine( 'do_something', sub { 42 } ); 1 }, "cann redefine do_something when parent define this function"; is $@, '', 'no warnings'; my $object = bless {}, 'ValidChild'; is $object->do_something(), 42, "mocked value from do_something"; $mock_child->unmock( 'do_something' ); is $object->do_something(), 1, "do_something is now unmocked"; } done_testing; Test-MockModule-v0.171.0/t/mock_strict.t000444000000000000 212213552627430 17233 0ustar00rootroot000000000000use warnings; use strict; use Test::More; use Test::Warnings; use Test::MockModule qw/strict/; my $mocker = Test::MockModule->new('Mockee'); is( $Test::MockModule::STRICT_MODE, 1, "use Test::MockModule qw/strict/; sets \$STRICT_MODE to 1" ); eval { $mocker->mock( 'foo', 2 ) }; like( "$@", qr/^mock is not allowed in strict mode. Please use define or redefine at/, "mock croaks in strict mode." ); eval { $mocker->noop('foo') }; like( "$@", qr/^noop is not allowed in strict mode. Please use define or redefine at/, "noop croaks in strict mode." ); $mocker->define( 'foo', "abc" ); is( Mockee->foo, "abc", "define is allowed in strict mode." ); $mocker->redefine( 'existing_subroutine', "def" ); is( Mockee->existing_subroutine, "def", "redefine is allowed in strict mode." ); $Test::MockModule::STRICT_MODE = 0; $mocker->mock( 'foo', 123 ); is( Mockee->foo, 123, "mock is allowed when strict mode is turned off." ); done_testing(); #---------------------------------------------------------------------- package Mockee; our $VERSION; BEGIN { $VERSION = 1 } sub existing_subroutine { 1 } 1; Test-MockModule-v0.171.0/t/mockmodule.t000444000000000000 1271413552627430 17101 0ustar00rootroot000000000000use warnings; use strict; use Test::More; use Test::Warnings; use lib "t/lib"; BEGIN { use_ok('Test::MockModule') or BAIL_OUT "Could not load Test::MockModule. Giving up"; } package Test_Package; our $VERSION=1; sub listify { my ($lower, $upper) = @_; return ($lower .. $upper); } package main; # new() ok(Test::MockModule->can('new'), 'new()'); eval {Test::MockModule->new('Test::MockModule')}; like($@, qr/Cannot mock Test::MockModule/, '... cannot mock itself'); eval {Test::MockModule->new('12Monkeys')}; like($@, qr/Invalid package name/, ' ... croaks if package looks invalid'); eval {Test::MockModule->new()}; like($@, qr/Invalid package name/, ' ... croaks if package is undefined'); { { Test::MockModule->new('ExampleModule', no_auto => 1); ok(!$INC{'ExampleModule.pm'}, '... no_auto prevents module being loaded'); } my $mcgi = Test::MockModule->new('ExampleModule'); ok($INC{'ExampleModule.pm'}, '... module loaded if !$VERSION'); ok($mcgi->isa('Test::MockModule'), '... returns a Test::MockModule object'); my $mcgi2 = Test::MockModule->new('ExampleModule'); is($mcgi, $mcgi2, "... returns existing object if there's already one for the package"); # get_package() ok($mcgi->can('get_package'), 'get_package'); is($mcgi->get_package, 'ExampleModule', '... returns the package name'); # mock() ok($mcgi->can('mock'), 'mock()'); eval {$mcgi->mock(q[p-ram])}; like($@, qr/Invalid subroutine name: /, '... dies if a subroutine name is invalid'); my $orig_param = \&ExampleModule::param; $mcgi->mock('param', sub {return qw(abc def)}); my @params = ExampleModule::param(); is_deeply(\@params, ['abc', 'def'], '... replaces the subroutine with a mocked sub'); $mcgi->mock('param' => undef); @params = ExampleModule::param(); is_deeply(\@params, [], '... which is an empty sub if !defined'); $mcgi->mock(param => 'The quick brown fox jumped over the lazy dog'); my $a2z = ExampleModule::param(); is($a2z, 'The quick brown fox jumped over the lazy dog', '... or a subroutine returning the supplied value'); my $ref = [1,2,3]; $mcgi->mock(param => $ref); @params = ExampleModule::param(); is($params[0], $ref, '... given a reference, install a sub that returns said reference'); my $blessed_code = bless sub { return 'Hello World' }, 'FOO'; $mcgi->mock(param => $blessed_code); @params = ExampleModule::param(); is($params[0], 'Hello World', '... a blessed coderef is properly detected'); $mcgi->mock(Just => 'another', Perl => 'Hacker'); @params = (ExampleModule::Just(), ExampleModule::Perl()); is_deeply(\@params, ['another', 'Hacker'], '... can mock multiple subroutines at a time'); # original() ok($mcgi->can('original'), 'original()'); is($mcgi->original('param'), $orig_param, '... returns the original subroutine'); my ($warn); local $SIG{__WARN__} = sub {$warn = shift}; $mcgi->original('Vars'); like($warn, qr/ is not mocked/, "... warns if a subroutine isn't mocked"); # unmock() ok($mcgi->can('unmock'), 'unmock()'); eval {$mcgi->unmock('V@rs')}; like($@, qr/Invalid subroutine name/, '... dies if the subroutine is invalid'); $warn = ''; $mcgi->unmock('Vars'); like($warn, qr/ was not mocked/, "... warns if a subroutine isn't mocked"); $mcgi->unmock('param'); is(\&{"ExampleModule::param"}, $orig_param, '... restores the original subroutine'); # unmock_all() ok($mcgi->can('unmock_all'), 'unmock_all'); $mcgi->mock('Vars' => sub {1}, param => sub {2}); ok(ExampleModule::Vars() == 1 && ExampleModule::param() == 2, 'mock: can mock multiple subroutines'); my @orig = ($mcgi->original('Vars'), $mcgi->original('param')); $mcgi->unmock_all(); ok(\&ExampleModule::Vars eq $orig[0] && \&ExampleModule::param eq $orig[1], '... removes all mocked subroutines'); # is_mocked() ok($mcgi->can('is_mocked'), 'is_mocked'); ok(!$mcgi->is_mocked('param'), '... returns false for non-mocked sub'); $mcgi->mock('param', sub { return 'This sub is mocked' }); is(ExampleModule::param(), 'This sub is mocked', '... mocked params'); ok($mcgi->is_mocked('param'), '... returns true for non-mocked sub'); # noop() is(ExampleModule::cookie(), 'choc-chip', 'cookie does default behaviour'); $mcgi->noop('cookie'); ok($mcgi->is_mocked('cookie'), 'cookie is mocked using noop'); $mcgi->unmock('cookie'); $mcgi->unmock('Vars'); $mcgi->noop('cookie', 'Vars'); is(ExampleModule::cookie(), 1, 'now cookie does nothing'); is(ExampleModule::Vars(), 1, 'now Vars does nothing'); } isnt(ExampleModule::param(), 'This sub is mocked', '... params is unmocked when object goes out of scope'); # test inherited methods package Test_Parent; sub method { 1 } package Test_Child; @Test_Child::ISA = 'Test_Parent'; package main; my $test_mock = Test::MockModule->new('Test_Child', no_auto => 1); ok(Test_Child->can('method'), 'test class inherits from parent'); $test_mock->mock('method' => sub {2}); is(Test_Child->method, 2, 'mocked subclass method'); $test_mock->unmock('method'); ok(Test_Child->can('method'), 'unmocked subclass method still exists'); is(Test_Child->method, 1, 'mocked subclass method'); # test restoring non-existant functions $test_mock->mock(ISA => sub {'basic test'}); can_ok(Test_Child => 'ISA'); is(Test_Child::ISA(), 'basic test', "testing a mocked sub that didn't exist before"); $test_mock->unmock('ISA'); ok(!Test_Child->can('ISA') && $Test_Child::ISA[0] eq 'Test_Parent', "restoring an undefined sub doesn't clear out the rest of the symbols"); # ensure mocking CORE::GLOBAL works ok(Test::MockModule->new("CORE::GLOBAL")); done_testing; Test-MockModule-v0.171.0/t/pod.t000444000000000000 23513552627430 15457 0ustar00rootroot000000000000use warnings; use strict; use Test::More; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok(); Test-MockModule-v0.171.0/t/pod_coverage.t000444000000000000 35513552627430 17335 0ustar00rootroot000000000000use warnings; use strict; use Test::More; eval "use Test::Pod::Coverage 1.00"; plan skip_all => "Test::Pod::Coverage 1.00 required for testing pod coverage" if $@; all_pod_coverage_ok({also_private => [qr/^TRACE(?:F|_HERE)?|DUMP$/]}); Test-MockModule-v0.171.0/t/prototype.t000444000000000000 63613552627430 16747 0ustar00rootroot000000000000use warnings; use strict; use Test::More; use Test::Warnings; package Mockee; sub good ($$); sub good ($$) { my ( $bar, $baz ) = @_; return ( $bar + 1, $baz + 2 ); } 1; package main; use Test::MockModule; $INC{'Mockee.pm'} = 1; my $mocker = Test::MockModule->new('Mockee'); $mocker->redefine( 'good', 2 ); done_testing(); #---------------------------------------------------------------------- Test-MockModule-v0.171.0/t/redefine.t000444000000000000 143513552627430 16501 0ustar00rootroot000000000000use warnings; use strict; use Test::More; use Test::Warnings; use Test::MockModule; my $mocker = Test::MockModule->new('Mockee'); $mocker->redefine('good', 2); is( Mockee::good(), 2, 'redefine() redefines the function' ); eval { $mocker->redefine('bad', 6) }; like( $@, qr/Mockee::bad/, 'exception when redefine()ing a nonexistent function' ); my $mocker2 = Test::MockModule->new('MockeeWithDestroy'); eval { $mocker2->redefine('what', 2) }; done_testing(); #---------------------------------------------------------------------- package Mockee; our $VERSION; BEGIN { $VERSION = 1 }; sub good { 1 } #---------------------------------------------------------------------- package MockeeWithDestroy; our $VERSION; BEGIN { $VERSION = 1 }; sub DESTROY { print 'bad' if $_[0][1] }; 1; Test-MockModule-v0.171.0/t/lib000755000000000000 013552627430 15141 5ustar00rootroot000000000000Test-MockModule-v0.171.0/t/lib/ExampleModule.pm000444000000000000 32013552627430 20350 0ustar00rootroot000000000000package ExampleModule; use strict; use warnings; # This is an example module used by Test::MockModule for testing. sub Vars { return; } sub param { return; } sub cookie { return 'choc-chip'; } 1;