From ffbc7e868f0edc5edd14be579f53807c595398cc Mon Sep 17 00:00:00 2001 From: Elizabeth Mattijsen Date: Sun, 28 Jan 2024 11:59:48 +0100 Subject: [PATCH] Preparations for transition to Raku Community Modules --- .github/workflows/test.yml | 31 ++ .gitignore | 4 +- .travis.yml | 13 - Changes | 4 + LICENSE | 201 ++++++++++ META6.json | 36 +- README.markdown | 226 ------------ README.md | 256 +++++++++++++ dist.ini | 9 + lib/Test/Mock.rakumod | 346 ++++++++++++++++++ release.raku | 12 - run-tests | 54 +++ t/{computing.t => computing.rakutest} | 0 t/{multi.t => multi.rakutest} | 0 t/{new.t => new.rakutest} | 0 t/{overriding.t => overriding.rakutest} | 0 ...quired-attrs.t => required-attrs.rakutest} | 0 t/{returning.t => returning.rakutest} | 0 t/{rw-methods.t => rw-methods.rakutest} | 0 t/{synopsis.t => synopsis.rakutest} | 0 t/{threads.t => threads.rakutest} | 0 t/{with.t => with.rakutest} | 0 22 files changed, 927 insertions(+), 265 deletions(-) create mode 100644 .github/workflows/test.yml delete mode 100644 .travis.yml create mode 100644 Changes create mode 100644 LICENSE delete mode 100644 README.markdown create mode 100644 README.md create mode 100644 dist.ini delete mode 100644 release.raku create mode 100644 run-tests rename t/{computing.t => computing.rakutest} (100%) rename t/{multi.t => multi.rakutest} (100%) rename t/{new.t => new.rakutest} (100%) rename t/{overriding.t => overriding.rakutest} (100%) rename t/{required-attrs.t => required-attrs.rakutest} (100%) rename t/{returning.t => returning.rakutest} (100%) rename t/{rw-methods.t => rw-methods.rakutest} (100%) rename t/{synopsis.t => synopsis.rakutest} (100%) rename t/{threads.t => threads.rakutest} (100%) rename t/{with.t => with.rakutest} (100%) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..8bc03d5 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,31 @@ +name: test + +on: + push: + branches: + - '*' + tags-ignore: + - '*' + pull_request: + +jobs: + raku: + strategy: + fail-fast: false + matrix: + os: + - ubuntu-latest + - macos-latest + - windows-latest + raku-version: + - 'latest' + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: Raku/setup-raku@v1 + with: + raku-version: ${{ matrix.raku-version }} + - name: Install Dependencies + run: zef install --/test --test-depends --deps-only . + - name: Run Tests + run: raku run-tests diff --git a/.gitignore b/.gitignore index 58911d9..c6da258 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,2 @@ -lib/.precomp/ -t/.precomp/ +.precomp/ +/Test-Mock-* diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 156058d..0000000 --- a/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ -dist: trusty -language: perl6 - -perl6: - - latest - - "2018.10" - -install: - - rakudobrew build-zef - - zef --debug --depsonly install . - -script: - - PERL6LIB=lib prove -v -r --exec=perl6 t/ diff --git a/Changes b/Changes new file mode 100644 index 0000000..9b98087 --- /dev/null +++ b/Changes @@ -0,0 +1,4 @@ +Revision history for Test-Mock + +{{$NEXT}} + - Initial version in the zef ecosystem diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..32efefc --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + The Artistic License 2.0 + + Copyright (c) 2000-2006, The Perl Foundation. + + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +Preamble + +This license establishes the terms under which a given free software +Package may be copied, modified, distributed, and/or redistributed. +The intent is that the Copyright Holder maintains some artistic +control over the development of that Package while still keeping the +Package available as open source and free software. + +You are always permitted to make arrangements wholly outside of this +license directly with the Copyright Holder of a given Package. If the +terms of this license do not permit the full use that you propose to +make of the Package, you should contact the Copyright Holder and seek +a different licensing arrangement. + +Definitions + + "Copyright Holder" means the individual(s) or organization(s) + named in the copyright notice for the entire Package. + + "Contributor" means any party that has contributed code or other + material to the Package, in accordance with the Copyright Holder's + procedures. + + "You" and "your" means any person who would like to copy, + distribute, or modify the Package. + + "Package" means the collection of files distributed by the + Copyright Holder, and derivatives of that collection and/or of + those files. A given Package may consist of either the Standard + Version, or a Modified Version. + + "Distribute" means providing a copy of the Package or making it + accessible to anyone else, or in the case of a company or + organization, to others outside of your company or organization. + + "Distributor Fee" means any fee that you charge for Distributing + this Package or providing support for this Package to another + party. It does not mean licensing fees. + + "Standard Version" refers to the Package if it has not been + modified, or has been modified only in ways explicitly requested + by the Copyright Holder. + + "Modified Version" means the Package, if it has been changed, and + such changes were not explicitly requested by the Copyright + Holder. + + "Original License" means this Artistic License as Distributed with + the Standard Version of the Package, in its current version or as + it may be modified by The Perl Foundation in the future. + + "Source" form means the source code, documentation source, and + configuration files for the Package. + + "Compiled" form means the compiled bytecode, object code, binary, + or any other form resulting from mechanical transformation or + translation of the Source form. + + +Permission for Use and Modification Without Distribution + +(1) You are permitted to use the Standard Version and create and use +Modified Versions for any purpose without restriction, provided that +you do not Distribute the Modified Version. + + +Permissions for Redistribution of the Standard Version + +(2) You may Distribute verbatim copies of the Source form of the +Standard Version of this Package in any medium without restriction, +either gratis or for a Distributor Fee, provided that you duplicate +all of the original copyright notices and associated disclaimers. At +your discretion, such verbatim copies may or may not include a +Compiled form of the Package. + +(3) You may apply any bug fixes, portability changes, and other +modifications made available from the Copyright Holder. The resulting +Package will still be considered the Standard Version, and as such +will be subject to the Original License. + + +Distribution of Modified Versions of the Package as Source + +(4) You may Distribute your Modified Version as Source (either gratis +or for a Distributor Fee, and with or without a Compiled form of the +Modified Version) provided that you clearly document how it differs +from the Standard Version, including, but not limited to, documenting +any non-standard features, executables, or modules, and provided that +you do at least ONE of the following: + + (a) make the Modified Version available to the Copyright Holder + of the Standard Version, under the Original License, so that the + Copyright Holder may include your modifications in the Standard + Version. + + (b) ensure that installation of your Modified Version does not + prevent the user installing or running the Standard Version. In + addition, the Modified Version must bear a name that is different + from the name of the Standard Version. + + (c) allow anyone who receives a copy of the Modified Version to + make the Source form of the Modified Version available to others + under + + (i) the Original License or + + (ii) a license that permits the licensee to freely copy, + modify and redistribute the Modified Version using the same + licensing terms that apply to the copy that the licensee + received, and requires that the Source form of the Modified + Version, and of any works derived from it, be made freely + available in that license fees are prohibited but Distributor + Fees are allowed. + + +Distribution of Compiled Forms of the Standard Version +or Modified Versions without the Source + +(5) You may Distribute Compiled forms of the Standard Version without +the Source, provided that you include complete instructions on how to +get the Source of the Standard Version. Such instructions must be +valid at the time of your distribution. If these instructions, at any +time while you are carrying out such distribution, become invalid, you +must provide new instructions on demand or cease further distribution. +If you provide valid instructions or cease distribution within thirty +days after you become aware that the instructions are invalid, then +you do not forfeit any of your rights under this license. + +(6) You may Distribute a Modified Version in Compiled form without +the Source, provided that you comply with Section 4 with respect to +the Source of the Modified Version. + + +Aggregating or Linking the Package + +(7) You may aggregate the Package (either the Standard Version or +Modified Version) with other packages and Distribute the resulting +aggregation provided that you do not charge a licensing fee for the +Package. Distributor Fees are permitted, and licensing fees for other +components in the aggregation are permitted. The terms of this license +apply to the use and Distribution of the Standard or Modified Versions +as included in the aggregation. + +(8) You are permitted to link Modified and Standard Versions with +other works, to embed the Package in a larger work of your own, or to +build stand-alone binary or bytecode versions of applications that +include the Package, and Distribute the result without restriction, +provided the result does not expose a direct interface to the Package. + + +Items That are Not Considered Part of a Modified Version + +(9) Works (including, but not limited to, modules and scripts) that +merely extend or make use of the Package, do not, by themselves, cause +the Package to be a Modified Version. In addition, such works are not +considered parts of the Package itself, and are not subject to the +terms of this license. + + +General Provisions + +(10) Any use, modification, and distribution of the Standard or +Modified Versions is governed by this Artistic License. By using, +modifying or distributing the Package, you accept this license. Do not +use, modify, or distribute the Package, if you do not accept this +license. + +(11) If your Modified Version has been derived from a Modified +Version made by someone other than you, you are nevertheless required +to ensure that your Modified Version complies with the requirements of +this license. + +(12) This license does not grant you the right to use any trademark, +service mark, tradename, or logo of the Copyright Holder. + +(13) This license includes the non-exclusive, worldwide, +free-of-charge patent license to make, have made, use, offer to sell, +sell, import and otherwise transfer the Package with respect to any +patent claims licensable by the Copyright Holder that are necessarily +infringed by the Package. If you institute patent litigation +(including a cross-claim or counterclaim) against any party alleging +that the Package constitutes direct or contributory patent +infringement, then this Artistic License to you shall terminate on the +date that such litigation is filed. + +(14) Disclaimer of Warranty: +THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS +IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR +NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL +LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF +ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/META6.json b/META6.json index 7e20735..a7b0e31 100644 --- a/META6.json +++ b/META6.json @@ -1,14 +1,26 @@ { - "perl" : "6.d", - "name" : "Test::Mock", - "auth" : "zef:jnthn", - "authors" : [ "Jonathan Worthington " ], - "version" : "1.6", - "description" : "Creation of stub objects using the Arrange, Act, Assert pattern.", - "license" : "Artistic-2.0", - "depends" : [ "OO::Monitors" ], - "provides" : { - "Test::Mock" : "lib/Test/Mock.rakumod" - }, - "source-url" : "git://github.com/jnthn/test-mock.git" + "auth": "zef:raku-community-modules", + "authors": [ + "Jonathan Worthington " + ], + "build-depends": [ + ], + "depends": [ + "OO::Monitors" + ], + "description": "Creation of stub objects using the Arrange, Act, Assert pattern", + "license": "Artistic-2.0", + "name": "Test::Mock", + "perl": "6.d", + "provides": { + "Test::Mock": "lib/Test/Mock.rakumod" + }, + "resources": [ + ], + "source-url": "git://github.com/raku-community-modules/Test-Mock.git", + "tags": [ + ], + "test-depends": [ + ], + "version": "1.6" } diff --git a/README.markdown b/README.markdown deleted file mode 100644 index fe29b80..0000000 --- a/README.markdown +++ /dev/null @@ -1,226 +0,0 @@ -# Synopsis [![Build Status](https://travis-ci.org/jnthn/test-mock.svg?branch=master)](https://travis-ci.org/jnthn/test-mock) - - use Test; - use Test::Mock; - - plan 2; - - class Foo { - method lol() { 'rofl' } - method wtf() { 'oh ffs' } - } - - my $x = mocked(Foo); - - $x.lol(); - $x.lol(); - - check-mock($x, - *.called('lol', times => 2), - *.never-called('wtf'), - ); - -# Details - -Test::Mock is a module that works alongside the standard Test module to -help you write tests when you want to verify what methods are called on -an object, while still having calls to undefined methods die. - -You get started just as normal with the test file, but also add a use -statement for Test::Mock. - - use Test; - use Test::Mock; - - plan 2; - -Imagine we have some class Foo: - - class Foo { - method lol() { 'rofl' } - method wtf() { 'oh ffs' } - } - -We then arrange to have a mocked instance of this class. This means that -instead of calls to lol and wtf actually resulting in the methods being -invoked, it simply logs the invocations. - - my $x = mocked(Foo); - -We can then take the actions that should result in some method calls. -Here we just make them directly, but you'd probably pass the mock to -other bits of code that will make calls on it. - - $x.lol(); - $x.lol(); - -When you're done, you assert that the things you expected to happen -actually happened. - - check-mock($x, - *.called('lol', times => 2), - *.never-called('wtf'), - ); - -And it's as easy as that. Of course, you may also be interested to check -that the arguments passed to the mocked method were as expected. For our -second example, here's a class representing one of my favorite places. - - class Pub { - method order_beer($pints) { } - method throw($what) { } - } - -We'll also declare a couple of other classes: - - class Glass { } - class Party { } - -Our test file would have started with the same boilerplate - use Test and -Test::Mock, and set a plan. We then produce a mock instance of Pub: - - my $p = mocked(Pub); - -And do our stuff: - - $p.throw(Party.new); - $p.order_beer(2); - $p.order_beer(1); - -After our excruciatingly low on beer party, we can now do some checks. Of -course, we ordered beer twice, so we can check this as before: - - check-mock($p, - *.called('order_beer', times => 2), - -But what if we wanted to check the arguments passed to the method? In that -case, you can simply pass along the parameter "with". We may pass a Capture -here, which contains the exact arguments we expected to be passed; this will -be tested against the actual passed Capture for equivalance. - - *.called('order_beer', times => 1, with => \(1)), - *.called('order_beer', times => 1, with => \(2)), - *.never-called('order_beer', with => \(10)), - -That's going to cover some cases, but what if we wanted to check if things of -the correct type were passed? In that case, write a Signature literal, and the -args Capture will be smart-matched against it, which conveniently happens to -check if the Capture could have bound to this Signature. - - *.called('throw', with => :(Party)), - *.never-called('throw', with => :(Glass)), - -Of course, now the gloves are off: if you have a Signature you can do all kinds -of matching, with constraints and sub-signatures. Here's an easy but not so -creative example (I need at least 3 pints to be creative...) - - *.called('order_beer', times => 2, with => :($ where { $^n < 10 })), - *.never-called('order_beer', with => :($ where { $^n >= 10 })), - -And if all that isn't enough, since we just smart-match against anything else -you may pass as the with argument, you may also pass a block that takes a -Capture as a parameter and implement whatever fancier checks you may wish to. - -In some cases, just logging method calls on your mock may not be enough; you -may wish them to return some fake data from the method call. For example, we -may have a yak shaving class that we dependency-inject with a yak provider -and a yak shaver. - - class Yak { - has $.shaved; - } - - class Shaver { - method shave($yak) { - ... - } - } - - class YakStore { - method get-all-yaks() { - ... - } - } - - class YakShaving { - has $.yak-store; - has $.yak-shaver; - - method proccess() { - for $!yak-store.get-all-yaks() -> $yak { - unless $yak.shaved { - $!yak-shaver.shave($yak); - } - } - } - } - -We want to check that our the shave method from the Shaver class is only -invoked for yaks that need shaving. We set up our mock of the Shaver class -just as normal: - - my $shaver = mocked(Shaver); - -However, for the Yak store we want to provide some fake yaks in various -states of shavenness. - - my $store = mocked(YakStore, returning => { - get-all-yaks => (Yak.new(:!shaved), Yak.new(:shaved), Yak.new(:!shaved)) - }); - -Now we can inject our mocks to the YakShaving class and and get it to do -it's thing. - - my $yaktivity = YakShaving.new( - yak-store => $store, - yak-shaver => $shaver - ); - $yaktivity.proccess(); - -And finally, it's time to write our tests. We expect just one call on the -store: - - check-mock($store, - *.called('get-all-yaks', times => 1) - ); - -On the shaver, we expect two calls in total to the shave method with yaks -that are unshaven, and no calls at all with shaven yaks. - - check-mock($shaver, - *.called('shave', times => 2, with => :($ where { !$^y.shaved })), - *.never-called('shave', with => :($ where { $^y.shaved })) - ); - -This is the first example where we're really made good use of mock testing; -if absolutely every object involved in the test is mocked, then you'd not be -testing any of the actual real code. Of course, being able to do this easily -somewhat depends on good de-coupled code design, where objects are given -instances of other objects to work on rather than directly instantiating -objects of other classes. - -Sometimes, it would be nice to fake an exception or do some other computation -rather than return a literal value. For that, use `computing` instead of using -`returning`. Our previous example would look like this: - - my $store = mocked(YakStore, computing => { - get-all-yaks => { Yak.new(:!shaved), Yak.new(:shaved), Yak.new(:!shaved) } - }); - -However, unlike with `returning`, it's possible to instead do: - - my $store = mocked(YakStore, computing => { - get-all-yaks => { die "Could not connect to yak-db" } - }); - -Occasionally, it is also desirable to have access to the arguments passed to -method. In this case, use `overriding`: - - my $shaver = mocked(Shaver, overriding => { - shave => -> $yak { die 'Already shaven' if $yak.shaved } - }); - -Of course, you can use `returning`, `computing` and `overriding` in a call to `mocked` to get different behaviours for different methods, as long as each method name only occurs once. - -Feature requests, bug reports and patches on this module are welcome; use -the GitHub issues tracker. diff --git a/README.md b/README.md new file mode 100644 index 0000000..60c2b24 --- /dev/null +++ b/README.md @@ -0,0 +1,256 @@ +[![Actions Status](https://github.com/lizmat/Test-Mock/actions/workflows/test.yml/badge.svg)](https://github.com/lizmat/Test-Mock/actions) + +NAME +==== + +Test::Mock - Creation of stub objects using the Arrange, Act, Assert pattern + +SYNOPSIS +======== + +```raku +use Test; +use Test::Mock; + +plan 2; + +class Foo { + method lol() { 'rofl' } + method wtf() { 'oh ffs' } +} + +my $x = mocked(Foo); + +$x.lol(); +$x.lol(); + +check-mock($x, + *.called('lol', times => 2), + *.never-called('wtf'), +); +``` + +DESCRIPTION +=========== + +Test::Mock is a module that works alongside the standard Test module to help you write tests when you want to verify what methods are called on an object, while still having calls to undefined methods die. + +You get started just as normal with the test file, but also add a use statement for Test::Mock. + +```raku +use Test; +use Test::Mock; + +plan 2; +``` + +Imagine we have some class Foo: + +```raku +class Foo { + method lol() { 'rofl' } + method wtf() { 'oh ffs' } +} +``` + +We then arrange to have a mocked instance of this class. This means that instead of calls to lol and wtf actually resulting in the methods being invoked, it simply logs the invocations. + +```raku +my $x = mocked(Foo); +``` + +We can then take the actions that should result in some method calls. Here we just make them directly, but you'd probably pass the mock to other bits of code that will make calls on it. + +```raku +$x.lol(); +$x.lol(); +``` + +When you're done, you assert that the things you expected to happen actually happened. + +```raku +check-mock($x, + *.called('lol', times => 2), + *.never-called('wtf'), +); +``` + +And it's as easy as that. Of course, you may also be interested to check that the arguments passed to the mocked method were as expected. For our second example, here's a class representing one of my favorite places. + +```raku +class Pub { + method order_beer($pints) { } + method throw($what) { } +} +``` + +We'll also declare a couple of other classes: + +```raku +class Glass { } +class Party { } +``` + +Our test file would have started with the same boilerplate - use Test and Test::Mock, and set a plan. We then produce a mock instance of Pub: + +```raku +my $p = mocked(Pub); +``` + +And do our stuff: + +```raku +$p.throw(Party.new); +$p.order_beer(2); +$p.order_beer(1); +``` + +After our excruciatingly low on beer party, we can now do some checks. Of course, we ordered beer twice, so we can check this as before: + +```raku +check-mock($p, + *.called('order_beer', times => 2), +``` + +But what if we wanted to check the arguments passed to the method? In that case, you can simply pass along the parameter "with". We may pass a `Capture` here, which contains the exact arguments we expected to be passed; this will be tested against the actual passed `Capture` for equivalance. + +```raku + *.called('order_beer', times => 1, with => \(1)), + *.called('order_beer', times => 1, with => \(2)), + *.never-called('order_beer', with => \(10)), +``` + +That's going to cover some cases, but what if we wanted to check if things of the correct type were passed? In that case, write a `Signature` literal, and the args `Capture` will be smart-matched against it, which conveniently happens to check if the `Capture` could have bound to this `Signature`. + +```raku + *.called('throw', with => :(Party)), + *.never-called('throw', with => :(Glass)), +``` + +Of course, now the gloves are off: if you have a `Signature` you can do all kinds of matching, with constraints and sub-signatures. Here's an easy but not so creative example (I need at least 3 pints to be creative...) + +```raku + *.called('order_beer', times => 2, with => :($ where { $^n < 10 })), + *.never-called('order_beer', with => :($ where { $^n >= 10 })), +``` + +And if all that isn't enough, since we just smart-match against anything else you may pass as the with argument, you may also pass a block that takes a `Capture` as a parameter and implement whatever fancier checks you may wish to. + +In some cases, just logging method calls on your mock may not be enough; you may wish them to return some fake data from the method call. For example, we may have a yak shaving class that we dependency-inject with a yak provider and a yak shaver. + +```raku +class Yak { + has $.shaved; +} + +class Shaver { + method shave($yak) { + ... + } +} + +class YakStore { + method get-all-yaks() { + ... + } +} + +class YakShaving { + has $.yak-store; + has $.yak-shaver; + + method proccess() { + for $!yak-store.get-all-yaks() -> $yak { + unless $yak.shaved { + $!yak-shaver.shave($yak); + } + } + } +} +``` + +We want to check that our the shave method from the `Shaver` class is only invoked for yaks that need shaving. We set up our mock of the `Shaver` class just as normal: + +```raku +my $shaver = mocked(Shaver); +``` + +However, for the `Yak` store we want to provide some fake yaks in various states of shavenness. + +```raku +my $store = mocked(YakStore, returning => { + get-all-yaks => (Yak.new(:!shaved), Yak.new(:shaved), Yak.new(:!shaved)) +}); +``` + +Now we can inject our mocks to the `YakShaving` class and and get it to do its thing. + +```raku +my $yaktivity = YakShaving.new( + yak-store => $store, + yak-shaver => $shaver +); +$yaktivity.proccess(); +``` + +And finally, it's time to write our tests. We expect just one call on the store: + +```raku +check-mock($store, + *.called('get-all-yaks', times => 1) +); +``` + +On the shaver, we expect two calls in total to the shave method with yaks that are unshaven, and no calls at all with shaven yaks. + +```raku +check-mock($shaver, + *.called('shave', times => 2, with => :($ where { !$^y.shaved })), + *.never-called('shave', with => :($ where { $^y.shaved })) +); +``` + +This is the first example where we're really made good use of mock testing; if absolutely every object involved in the test is mocked, then you'd not be testing any of the actual real code. Of course, being able to do this easily somewhat depends on good de-coupled code design, where objects are given instances of other objects to work on rather than directly instantiating objects of other classes. + +Sometimes, it would be nice to fake an exception or do some other computation rather than return a literal value. For that, use `computing` instead of using `returning`. Our previous example would look like this: + +```raku +my $store = mocked(YakStore, computing => { + get-all-yaks => { Yak.new(:!shaved), Yak.new(:shaved), Yak.new(:!shaved) } +}); +``` + +However, unlike with `returning`, it's possible to instead do: + +```raku +my $store = mocked(YakStore, computing => { + get-all-yaks => { die "Could not connect to yak-db" } +}); +``` + +Occasionally, it is also desirable to have access to the arguments passed to method. In this case, use `overriding`: + +```raku +my $shaver = mocked(Shaver, overriding => { + shave => -> $yak { die 'Already shaven' if $yak.shaved } +}); +``` + +Of course, you can use `returning`, `computing` and `overriding` in a call to `mocked` to get different behaviours for different methods, as long as each method name only occurs once. + +Feature requests, bug reports and patches on this module are welcome; use the GitHub issues tracker. + +AUTHOR +====== + +Jonathan Worthington + +COPYRIGHT AND LICENSE +===================== + +Copyright 2010 - 2024 Jonathan Worthington + +Copyright 2024 Raku Community + +This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. + diff --git a/dist.ini b/dist.ini new file mode 100644 index 0000000..c8413ce --- /dev/null +++ b/dist.ini @@ -0,0 +1,9 @@ +name = Test-Mock + +[ReadmeFromPod] +filename = lib/Test/Mock.rakumod + +[UploadToZef] + +[Badges] +provider = github-actions/test.yml diff --git a/lib/Test/Mock.rakumod b/lib/Test/Mock.rakumod index 6bd4fdb..4084081 100644 --- a/lib/Test/Mock.rakumod +++ b/lib/Test/Mock.rakumod @@ -99,3 +99,349 @@ module Test::Mock { .($mock.'!mock-log'()) for @checker; } } + +=begin pod + +=head1 NAME + +Test::Mock - Creation of stub objects using the Arrange, Act, Assert pattern + +=head1 SYNOPSIS + +=begin code :lang + +use Test; +use Test::Mock; + +plan 2; + +class Foo { + method lol() { 'rofl' } + method wtf() { 'oh ffs' } +} + +my $x = mocked(Foo); + +$x.lol(); +$x.lol(); + +check-mock($x, + *.called('lol', times => 2), + *.never-called('wtf'), +); + +=end code + +=head1 DESCRIPTION + +Test::Mock is a module that works alongside the standard Test module to +help you write tests when you want to verify what methods are called on +an object, while still having calls to undefined methods die. + +You get started just as normal with the test file, but also add a use +statement for Test::Mock. + +=begin code :lang + +use Test; +use Test::Mock; + +plan 2; + +=end code + +Imagine we have some class Foo: + +=begin code :lang + +class Foo { + method lol() { 'rofl' } + method wtf() { 'oh ffs' } +} + +=end code + +We then arrange to have a mocked instance of this class. This means that +instead of calls to lol and wtf actually resulting in the methods being +invoked, it simply logs the invocations. + +=begin code :lang + +my $x = mocked(Foo); + +=end code + +We can then take the actions that should result in some method calls. +Here we just make them directly, but you'd probably pass the mock to +other bits of code that will make calls on it. + +=begin code :lang + +$x.lol(); +$x.lol(); + +=end code + +When you're done, you assert that the things you expected to happen +actually happened. + +=begin code :lang + +check-mock($x, + *.called('lol', times => 2), + *.never-called('wtf'), +); + +=end code + +And it's as easy as that. Of course, you may also be interested to check +that the arguments passed to the mocked method were as expected. For our +second example, here's a class representing one of my favorite places. + +=begin code :lang + +class Pub { + method order_beer($pints) { } + method throw($what) { } +} + +=end code + +We'll also declare a couple of other classes: + +=begin code :lang + +class Glass { } +class Party { } + +=end code + +Our test file would have started with the same boilerplate - use Test and +Test::Mock, and set a plan. We then produce a mock instance of Pub: + +=begin code :lang + +my $p = mocked(Pub); + +=end code + +And do our stuff: + +=begin code :lang + +$p.throw(Party.new); +$p.order_beer(2); +$p.order_beer(1); + +=end code + +After our excruciatingly low on beer party, we can now do some checks. +Of course, we ordered beer twice, so we can check this as before: + +=begin code :lang + +check-mock($p, + *.called('order_beer', times => 2), + +=end code + +But what if we wanted to check the arguments passed to the method? +In that case, you can simply pass along the parameter "with". We may +pass a C here, which contains the exact arguments we expected +to be passed; this will be tested against the actual passed C +for equivalance. + +=begin code :lang + + *.called('order_beer', times => 1, with => \(1)), + *.called('order_beer', times => 1, with => \(2)), + *.never-called('order_beer', with => \(10)), + +=end code + +That's going to cover some cases, but what if we wanted to check if +things of the correct type were passed? In that case, write a +C literal, and the args C will be smart-matched +against it, which conveniently happens to check if the C +could have bound to this C. + +=begin code :lang + + *.called('throw', with => :(Party)), + *.never-called('throw', with => :(Glass)), + +=end code + +Of course, now the gloves are off: if you have a C you can +do all kinds of matching, with constraints and sub-signatures. Here's +an easy but not so creative example (I need at least 3 pints to be +creative...) + +=begin code :lang + + *.called('order_beer', times => 2, with => :($ where { $^n < 10 })), + *.never-called('order_beer', with => :($ where { $^n >= 10 })), + +=end code + +And if all that isn't enough, since we just smart-match against +anything else you may pass as the with argument, you may also pass a +block that takes a C as a parameter and implement whatever +fancier checks you may wish to. + +In some cases, just logging method calls on your mock may not be +enough; you may wish them to return some fake data from the method +call. For example, we may have a yak shaving class that we +dependency-inject with a yak provider and a yak shaver. + +=begin code :lang + +class Yak { + has $.shaved; +} + +class Shaver { + method shave($yak) { + ... + } +} + +class YakStore { + method get-all-yaks() { + ... + } +} + +class YakShaving { + has $.yak-store; + has $.yak-shaver; + + method proccess() { + for $!yak-store.get-all-yaks() -> $yak { + unless $yak.shaved { + $!yak-shaver.shave($yak); + } + } + } +} + +=end code + +We want to check that our the shave method from the C class +is only invoked for yaks that need shaving. We set up our mock of the +C class just as normal: + +=begin code :lang + +my $shaver = mocked(Shaver); + +=end code + +However, for the C store we want to provide some fake yaks in +various states of shavenness. + +=begin code :lang + +my $store = mocked(YakStore, returning => { + get-all-yaks => (Yak.new(:!shaved), Yak.new(:shaved), Yak.new(:!shaved)) +}); + +=end code + +Now we can inject our mocks to the C class and and get it +to do its thing. + +=begin code :lang + +my $yaktivity = YakShaving.new( + yak-store => $store, + yak-shaver => $shaver +); +$yaktivity.proccess(); + +=end code + +And finally, it's time to write our tests. We expect just one call on +the store: + +=begin code :lang + +check-mock($store, + *.called('get-all-yaks', times => 1) +); + +=end code + +On the shaver, we expect two calls in total to the shave method with +yaks that are unshaven, and no calls at all with shaven yaks. + +=begin code :lang + +check-mock($shaver, + *.called('shave', times => 2, with => :($ where { !$^y.shaved })), + *.never-called('shave', with => :($ where { $^y.shaved })) +); + +=end code + +This is the first example where we're really made good use of mock +testing; if absolutely every object involved in the test is mocked, +then you'd not be testing any of the actual real code. Of course, +being able to do this easily somewhat depends on good de-coupled +code design, where objects are given instances of other objects to +work on rather than directly instantiating objects of other classes. + +Sometimes, it would be nice to fake an exception or do some other +computation rather than return a literal value. For that, use +C instead of using C. Our previous example +would look like this: + +=begin code :lang + +my $store = mocked(YakStore, computing => { + get-all-yaks => { Yak.new(:!shaved), Yak.new(:shaved), Yak.new(:!shaved) } +}); + +=end code + +However, unlike with C, it's possible to instead do: + +=begin code :lang + +my $store = mocked(YakStore, computing => { + get-all-yaks => { die "Could not connect to yak-db" } +}); + +=end code + +Occasionally, it is also desirable to have access to the arguments passed to +method. In this case, use C: + +=begin code :lang + +my $shaver = mocked(Shaver, overriding => { + shave => -> $yak { die 'Already shaven' if $yak.shaved } +}); + +=end code + +Of course, you can use C, C and C in +a call to C to get different behaviours for different methods, +as long as each method name only occurs once. + +Feature requests, bug reports and patches on this module are welcome; use +the GitHub issues tracker. + +=head1 AUTHOR + +Jonathan Worthington + +=head1 COPYRIGHT AND LICENSE + +Copyright 2010 - 2024 Jonathan Worthington + +Copyright 2024 Raku Community + +This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. + +=end pod diff --git a/release.raku b/release.raku deleted file mode 100644 index 5ca10aa..0000000 --- a/release.raku +++ /dev/null @@ -1,12 +0,0 @@ -use JSON::Fast; - -sub MAIN() { - given from-json(slurp('META6.json')) -> (:$version!, *%) { - shell("fez upload"); - tag("release-$version"); - } -} - -sub tag($tag) { - shell "git tag -a -m '$tag' $tag && git push --tags origin" -} diff --git a/run-tests b/run-tests new file mode 100644 index 0000000..e328a97 --- /dev/null +++ b/run-tests @@ -0,0 +1,54 @@ +unit sub MAIN(:a($author)); + +say run(, :out).out.slurp.chomp; +say "Running on $*DISTRO.gist().\n"; + +say "Testing { + "dist.ini".IO.lines.head.substr(7) +}{ + " including author tests" if $author +}"; + +my @failed; +my $done = 0; + +sub test-dir($dir) { + for $dir.IO.dir(:test(*.ends-with: '.t' | '.rakutest')).map(*.Str).sort { + say "=== $_"; + my $proc := run "raku", "--ll-exception", "-I.", $_, :out,:err,:merge; + if $proc { + $proc.out.slurp; + } + else { + @failed.push($_); + if $proc.out.slurp -> $stdout { + my @lines = $stdout.lines; + with @lines.first( + *.starts-with(" from gen/moar/stage2"),:k) + -> $index { + say @lines[^$index].join("\n"); + } + else { + say $stdout; + } + } + else { + say "No output received, exit-code $proc.exitcode() ($proc.signal())"; + } + } + $done++; + } +} + +test-dir("t"); +test-dir("xt") if $author && "xt".IO.e; + +if @failed { + say "FAILED: {+@failed} of $done:"; + say " $_" for @failed; + exit +@failed; +} + +say "\nALL {"$done " if $done > 1}OK"; + +# vim: expandtab shiftwidth=4 diff --git a/t/computing.t b/t/computing.rakutest similarity index 100% rename from t/computing.t rename to t/computing.rakutest diff --git a/t/multi.t b/t/multi.rakutest similarity index 100% rename from t/multi.t rename to t/multi.rakutest diff --git a/t/new.t b/t/new.rakutest similarity index 100% rename from t/new.t rename to t/new.rakutest diff --git a/t/overriding.t b/t/overriding.rakutest similarity index 100% rename from t/overriding.t rename to t/overriding.rakutest diff --git a/t/required-attrs.t b/t/required-attrs.rakutest similarity index 100% rename from t/required-attrs.t rename to t/required-attrs.rakutest diff --git a/t/returning.t b/t/returning.rakutest similarity index 100% rename from t/returning.t rename to t/returning.rakutest diff --git a/t/rw-methods.t b/t/rw-methods.rakutest similarity index 100% rename from t/rw-methods.t rename to t/rw-methods.rakutest diff --git a/t/synopsis.t b/t/synopsis.rakutest similarity index 100% rename from t/synopsis.t rename to t/synopsis.rakutest diff --git a/t/threads.t b/t/threads.rakutest similarity index 100% rename from t/threads.t rename to t/threads.rakutest diff --git a/t/with.t b/t/with.rakutest similarity index 100% rename from t/with.t rename to t/with.rakutest