File Coverage

blib/lib/Test/Module/Runnable.pm
Criterion Covered Total %
statement 32 32 100.0
branch n/a
condition n/a
subroutine 17 17 100.0
pod 11 11 100.0
total 60 60 100.0


line stmt bran cond sub pod time code
1             package Test::Module::Runnable;
2             # Module test framework
3             # Copyright (c) 2015-2024, Duncan Ross Palmer (2E0EOL) and others,
4             # All rights reserved.
5             #
6             # Redistribution and use in source and binary forms, with or without
7             # modification, are permitted provided that the following conditions are met:
8             #
9             # * Redistributions of source code must retain the above copyright notice,
10             # this list of conditions and the following disclaimer.
11             #
12             # * Redistributions in binary form must reproduce the above copyright
13             # notice, this list of conditions and the following disclaimer in the
14             # documentation and/or other materials provided with the distribution.
15             #
16             # * Neither the name of the Daybo Logic nor the names of its contributors
17             # may be used to endorse or promote products derived from this software
18             # without specific prior written permission.
19             #
20             # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21             # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22             # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23             # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
24             # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25             # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26             # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27             # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28             # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29             # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30             # POSSIBILITY OF SUCH DAMAGE.
31              
32             =head1 NAME
33              
34             Test::Module::Runnable - A runnable framework on Moose for running tests
35              
36             =head1 SYNOPSIS
37              
38             package YourTestSuite;
39             use Moose;
40             use Test::More 0.96;
41              
42             extends 'Test::Module::Runnable';
43              
44             sub helper { } # Not called
45              
46             sub testExample { } # Automagically called due to 'test' prefix.
47              
48             package main;
49              
50             my $tester = new YourTestSuite;
51             return $tester->run;
52              
53             B<Deprecated> alternative:
54              
55             my $tester = new YourTestSuite;
56             plan tests => $tester->testCount;
57             foreach my $name ($tester->testMethods) {
58             subtest $name => $tester->$name;
59             }
60              
61             =head1 DESCRIPTION
62              
63             A test framework based on Moose introspection to automagically
64             call all methods matching a user-defined pattern. Supports per-test
65             setup and tear-down routines and easy early L<Test::Builder/BAIL_OUT> using
66             L<Test::More>.
67              
68             =cut
69              
70 13     13   7727353 use Moose;
  13         549798  
  13         120  
71              
72             BEGIN {
73 13     13   111189 our $VERSION = '0.6.2';
74             }
75              
76             extends 'Test::Module::Runnable::Base';
77              
78 13     13   126 use Exporter qw(import);
  13         39  
  13         672  
79 13     13   1262 use POSIX qw/EXIT_SUCCESS/;
  13         18024  
  13         153  
80 13     13   12951 use Test::Module::Runnable::Base;
  13         127  
  13         952  
81 13     13   140 use Test::More 0.96;
  13         289  
  13         129  
82              
83             our @EXPORT_OK = qw(unique uniqueDomain uniqueStr uniqueStrCI uniqueLetters);
84              
85             =head1 ATTRIBUTES
86              
87             =over
88              
89             =item C<sut>
90              
91             System under test - a generic slot for an object you are testing, which
92             could be re-initialized under the C<setUp> routine, but this entry may be
93             ignored.
94              
95             =item C<mocker>
96              
97             This slot can be used during L</setUpBeforeClass> to set up a C<Test::MockModule>
98             for the L</sut> class being tested. If set, C<< mocker->unmock_all() >> will be
99             called automagically, just after each test method is executed.
100             This will allow different methods to to be mocked, which are not directly relevant
101             to the test method being executed.
102              
103             By default, this slot is C<undef>
104              
105             =item C<pattern>
106              
107             The pattern which defines which user-methods are considered tests.
108             Defaults to C<^test>.
109             Methods matching this pattern will be returned from L</methodNames>
110              
111             =item C<logger>
112              
113             A generic slot for a loggger, to be initialized with your logging framework,
114             or a mock logging system.
115              
116             This slot is not touched by this package, but might be passed on to
117             your L</sut>, or you may wish to clear it between tests by sub-classing
118             this package.
119              
120             =back
121              
122             =head1 METHODS
123              
124             =over
125              
126             =item C<methodNames>
127              
128             Returns a list of all names of test methods which should be called by C</subtest>,
129             ie. all method names beginning with 'test', or the user-defined L</pattern>.
130              
131             If you use L</run>, this is handled automagically.
132              
133             =item C<debug>
134              
135             Call C<Test::Builder::diag> with a user-defined message,
136             if and only if the C<TEST_VERBOSE> environment variable is set.
137              
138             =item C<mock($class, $method, $return)>
139              
140             This mocks the given method on the specified class, with the specified
141             return value, described below. Additionally, stores internally a log of all
142             method calls, and their arguments. Note that the first argument is not
143             saved, i.e. the object on which the method was called, as this is rarely useful
144             in a unit test comparison.
145              
146             The return value, C<$return>, may be specified in one of two ways:
147              
148             =over
149              
150             =item A C<CODE> reference
151              
152             In which case the code reference is simply called
153             each time, with all arguments as passed to the mocked function, and the
154             return value passed as-is to the caller. Note that care is taken that
155             if the mocked method is called in array context, the code reference is
156             called in array context, and likewise for scalar context.
157              
158             =item An C<ARRAY> reference
159              
160             In which case, a value is shifted from the front
161             of the array. If the value removed is itself a C<CODE> ref the code
162             reference is called, and its return value returned, as described above,
163             otherwise the value is returned as-is.
164              
165             Note that you cannot return a list by adding it to an array, so if you need to
166             use the array form, and also return a list, you will need to add a C<CODE> reference into the array:
167              
168             $self->mock($class, $method, [
169             1, # first call returns scalar '1'
170             [2,3,4], # second call returns array reference
171             sub { return (5,6,7) }, # third call returns a list
172             ]);
173              
174             =back
175              
176             If no value is specified, or if the specified array is exhaused, then either
177             C<undef> or an empty array is returned, depending on context.
178              
179             Calls including arguments and return values are passed to the L</debug>
180             method.
181              
182             =item unmock([class], [$method])
183              
184             Clears all mock objects.
185              
186             If no arguments are specified L<Test::Module::Runnable::Base/clearMocks> is called.
187              
188             Is a class is specified, only that class is cleared.
189              
190             If a method is specified too, only that method of that mocked class is cleared
191             (not methods by the same name under other classes).
192              
193             It is not legal to unmock a method in many or unspecified classes,
194             doing so will invoke C<die()>.
195              
196             The reference to the the tester is returned.
197              
198             =item C<mockCalls($class, $method)>
199              
200             Return a reference to an array of the calls made to the specified mocked function. Each entry in the arrayref
201             is an arrayref of the arguments to that call, B<excluding> the object reference itself (i.e. C<$self>).
202              
203             =item C<mockCallsWithObject($class, $method)>
204              
205             Return a reference to an array of the calls made to the specified mocked function. Each entry in the arrayref
206             is an arrayref of the arguments to that call, B<including> the object reference itself (i.e. C<$self>).
207              
208             This method is strongly encouraged in preference to L</mockCalls($class,
209             $method)> if your test constructs multiple instances of the same class,
210             so that you know that the right method calls were actually made on the
211             right object.
212              
213             Normal usage:
214              
215             cmp_deeply($self->mockCallsWithObject($class, $method), [
216             [ shallow($instance1), $arg1, $arg2 ],
217             [ shallow($instance2), $otherArg1, $otherArg2 ],
218             ...
219             ], 'correct method calls');
220              
221             =item C<unique>
222              
223             Returns a unique, integer ID, which is predictable.
224              
225             An optional C<$domain> can be specified, which is a discrete sequence,
226             isolated from any other domain. If not specified, a default domain is used.
227             The actual name for this domain is opaque.
228              
229             A special domain; C<rand> can be used for random numbers which will not repeat.
230              
231             =item C<methodCount>
232              
233             Returns the number of tests to pass to C<plan>
234             If you use L</run>, this is handled automagically.
235              
236             =item C<clearMocks>
237              
238             Forcibly clear all mock objects, if required e.g. in C<tearDown>.
239              
240             =back
241              
242             =head1 PROTECTED METHODS
243              
244             =over
245              
246             =item C<_mockdump>
247              
248             Helper method for dumping arguments and return values from C<mock> function.
249              
250             =back
251              
252             =head1 USER DEFINED METHODS
253              
254             =over
255              
256             =item C<setUpBeforeClass>
257              
258             If you need to initialize your test suite before any tests run,
259             this hook is your opportunity. If the setup fails, you should
260             return C<EXIT_FAILURE>. you must return C<EXIT_SUCCESS> in order
261             for tests to proceed.
262              
263             Don't write code here! Override the method in your test class.
264              
265             The default action is to do nothing.
266              
267             =cut
268              
269             sub setUpBeforeClass {
270 6     6 1 24 return EXIT_SUCCESS;
271             }
272              
273             =item C<tearDownAfterClass>
274              
275             If you need to finalize any cleanup for your test suite, after all
276             tests have completed running, this hook is your opportunity. If the
277             cleanup fails, you should return C<EXIT_FAILURE>. If cleanup succeeds,
278             you should return C<EXIT_SUCCESS>. You can also perform final sanity checking
279             here, because retuning C<EXIT_FAILURE> causes the suite to call
280             L<Test::Builder/BAIL_OUT>.
281              
282             Don't write code here! Override the method in your test class.
283              
284             The default action is to do nothing.
285              
286             =cut
287              
288             sub tearDownAfterClass {
289 12     12 1 35 return EXIT_SUCCESS;
290             }
291              
292             =item C<setUp>
293              
294             If you need to perform per-test setup, ie. before individual test methods
295             run, you should override this hook. You must return C<EXIT_SUCCESS> from
296             the hook, otherwise the entire test suite will be aborted via L<Test::Builder/BAIL_OUT>.
297              
298             Don't write code here! Override the method in your test class.
299              
300             The default action is to do nothing.
301              
302             =cut
303              
304             sub setUp {
305 28     28 1 174 return EXIT_SUCCESS;
306             }
307              
308             =item C<tearDown>
309              
310             If you need to perform per-test cleanup, ie. after individual test methods
311             run, you should override this hook. You must return C<EXIT_SUCCESS> from
312             the hook, otherwise the entire test suite will be aborted via L<Test::Builder/BAIL_OUT>.
313              
314             Don't write code here! Override the method in your test class.
315              
316             The default action is to do nothing.
317              
318             =cut
319              
320             sub tearDown {
321 13     13 1 39 return EXIT_SUCCESS;
322             }
323              
324             sub unique {
325 508     508 1 4701 my (@args) = @_;
326 508         2360 return Test::Module::Runnable::Base::unique(@args);
327             }
328              
329             =item C<uniqueStr([$length])>
330              
331             Return a unique alphanumeric string which shall not be shorter than the specified C<$length>,
332             which is 1 by default. The string is guaranteed to evaluate true in a boolean context.
333              
334             The numerical value of each character is obtained from L</unique>.
335              
336             Note that the strings returned from this function are B<only> guaranteed to
337             be in monotonically increasing lexicographical order if they are all of
338             the same length. Therefore if this is a concern, specify a length which
339             will be long enough to include all the strings you wish to generate,
340             for example C<uniqueStr(4)> would produce C<62**4> (over 14 million)
341             strings in increasing order.
342              
343             Can be called statically and exported in the same way as L</unique>.
344              
345             =cut
346              
347             sub uniqueStr {
348 67     67 1 846 my (@args) = @_;
349 67         107 return Test::Module::Runnable::Base::uniqueStr(@args);
350             }
351              
352             =item C<uniqueStrCI($length)>
353              
354             Works exactly the same as L</uniqueStr([$length])> except that the results are case
355             sensitively identical. Note that the strings are not guaranteed to be
356             all lowercase or all uppercase, you may get "A" or "a", but you will
357             never get both. No assumption should be made about the case.
358              
359             =cut
360              
361             sub uniqueStrCI {
362 1     1 1 5 my (@args) = @_;
363 1         5 return Test::Module::Runnable::Base::uniqueStrCI(@args);
364             }
365              
366             =item C<uniqueDomain([$options])>
367              
368             Returns a unique, fake domain-name. No assumptions should be made about the domain
369             name or TLD returned, except that this domain cannot be registered via a domain registrar, is lower-case and is
370             unique per test suite run.
371              
372             The optional C<$options>, if specified, must be a C<HASH> ref, and it may contain the following keys:
373              
374             =over
375              
376             =item C<length>
377              
378             The length of the first part of the hostname. This ensures correct lexicographic ordering.
379              
380             =item C<lettersOnly>
381              
382             Ensure that hostname parts only contain letters, not numbers. This is also useful to
383             ensure correct lexicographic ordering.
384              
385             =back
386              
387             =cut
388              
389             sub uniqueDomain {
390 208     208 1 107586 my (@args) = @_;
391 208         735 return Test::Module::Runnable::Base::uniqueDomain(@args);
392             }
393              
394             =item C<uniqueLetters($length)>
395              
396             Return a unique string containing letters only, which shall not be shorter
397             than the specified C<$length>, which is 1 by default. The string is guaranteed
398             to evaluate true in a boolean context.
399              
400             Note that the strings returned from this function are B<only> guaranteed to
401             be in monotonically increasing lexicographical order if they are all of
402             the same length. Therefore if this is a concern, specify a length which
403             will be long enough to include all the strings you wish to generate,
404             for example C<uniqueStr(4)> would produce C<62**4> (over 14 million)
405             strings in increasing order.
406              
407             =cut
408              
409             sub uniqueLetters {
410 1     1 1 4 my (@args) = @_;
411 1         6 return Test::Module::Runnable::Base::uniqueLetters(@args);
412             }
413              
414             =item C<modeName>
415              
416             If set, this routine will be called from the internal
417             L<Test::Module::Runnable::Base/__generateMethodName>
418             method, which is used to generate the method name displyed to the user. This
419             name should represent the mode of testing currently in use, for example.
420             you may be re-running all the tests to test a different database driver.
421              
422             If C<undef> or an empty string is returned, the result is ignored, as if you
423             had not defined this method.
424              
425             SEE ALSO L</modeSwitch>
426              
427             This is a dummy method which just returns C<undef>.
428             User test classes can override this.
429              
430             =cut
431              
432             sub modeName {
433 59     59 1 133 return;
434             }
435              
436             =item C<modeSwitch>
437              
438             If set, this routine will be called between test runs.
439             This is typically used by setting an C<n> value of at least C<2>.
440             Every time the test suite finishes, this routine is called, and
441             you can replace a L</sut> or set a flag so that all tests can then
442             run with an underlying assumption shared between the tests inverted,
443             for example, with a different database driver.
444              
445             The return value from your registered C<modeSwitch CODE> reference
446             should be zero to indicate success. Your routine will be passed the
447             current C<n> iteration, starting with zero.
448              
449             This is the default action for switching the mode of the test between
450             iterations is to report success but do nothing.
451             Testers which are subclasses may override this method.
452              
453             =cut
454              
455             sub modeSwitch {
456 26     26 1 177 return EXIT_SUCCESS;
457             }
458              
459             =item C<run>
460              
461             Executes all of the tests, in a random order
462             An optional override may be passed with the tests parameter.
463              
464             * tests
465             An ARRAY ref which contains the inclusive list of all tests
466             to run. If not passed, all tests are run. If an empty list
467             is passed, no tests are run. If a test does not exist, C<confess>
468             is called.
469              
470             * n
471             Number of times to iterate through the tests.
472             Defaults to 1. Setting to a higher level is useful if you want to
473             prove that the random ordering of tests does not break, but you do
474             not want to type 'make test' many times.
475              
476             Returns:
477             The return value is always C<EXIT_SUCCESS>, which you can pass straight
478             to C<exit>
479              
480             =back
481              
482             =head1 AUTHOR
483              
484             Duncan Ross Palmer, 2E0EOL L<mailto:palmer@overchat.org>
485              
486             =head1 LICENCE
487              
488             Daybo Logic Shared Library
489             Copyright (c) 2015-2024, Duncan Ross Palmer (2E0EOL), Daybo Logic
490             All rights reserved.
491              
492             Redistribution and use in source and binary forms, with or without
493             modification, are permitted provided that the following conditions are met:
494              
495             * Redistributions of source code must retain the above copyright notice,
496             this list of conditions and the following disclaimer.
497              
498             * Redistributions in binary form must reproduce the above copyright
499             notice, this list of conditions and the following disclaimer in the
500             documentation and/or other materials provided with the distribution.
501              
502             * Neither the name of the Daybo Logic nor the names of its contributors
503             may be used to endorse or promote products derived from this software
504             without specific prior written permission.
505              
506             THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
507             AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
508             IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
509             ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
510             LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
511             CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
512             SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
513             INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
514             CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
515             ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
516             POSSIBILITY OF SUCH DAMAGE.
517              
518             =head1 AVAILABILITY
519              
520             L<https://metacpan.org/release/Test-Module-Runnable>
521             L<https://git.sr.ht/~m6kvm/libtest-module-runnable-perl>
522             L<http://www.daybologic.co.uk/software.php?content=libtest-module-runnable-perl>
523              
524             =head1 CAVEATS
525              
526             None known.
527              
528             =cut
529              
530             1;