Sub.pm

filter: Statementstmt 100% 64 / 64 Branchbran 100% 14 / 14 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 85.7% 12 / 14 Podpod 100% 5 / 5 totaltotal 97.9% 95 / 97 CC 11 SCAR 9.2
CC
11
Cov
100%
mock
5.0
mocked_subs
3.0
mocked_state
3.0
CRAP 2.5
« Sub/Child.pm ↑ Summary
1 package Mock::Sub;
2 20 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 20 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 20 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 20 ▶use Carp qw(confess);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 20 ▶use Mock::Sub::Child;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 20 ▶use Scalar::Util qw(weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 20 our $VERSION = '1.09';
11  
12 20 my %opts;
13  
14 20 ▶sub import {
Subroutine import: called CC=1 SCAR=0.0
15 20 my ($class, %args) = @_;
16 20 %opts = %args;
17 }
18 56 ▶sub new {
Subroutine new: called CC=2 SCAR=6.9
Pod documented
19 56 my $self = bless {}, shift;
20 56 %{ $self } = @_;
21  
22 56 for (keys %opts){
23 1 $self->{$_} = $opts{$_};
24 }
25 56 return $self;
26 }
27 70 ▶sub mock {
Subroutine mock: called CC=5 SCAR=16.1
Pod documented
28 70 my ($self, $sub, %p) = @_;
29  
30 70 ▶ if (ref($self) ne 'Mock::Sub'){
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self ne "Mock::Sub") 3 67 70
31 3 confess
32 "calling mock() on the Mock::Sub class is no longer permitted. " .
33 "create a new mock object with Mock::Sub->new;, then call mock " .
34 "with my \$sub_object = \$mock->mock('sub_name'); ";
35 }
36  
37 67 ▶ if (! defined wantarray){
Branch: 1 branch
BranchTrueFalseTotal
unless (defined wantarray) 1 66 67
38 1 confess "\n\ncalling mock() in void context isn't allowed. ";
39 }
40  
41 66 my $child = Mock::Sub::Child->new(no_warnings => $self->{no_warnings});
42  
43 my $side_effect = defined $p{side_effect}
44 ? $p{side_effect}
45 66 ▶ : $self->{side_effect};
Branch: 1 branch
BranchTrueFalseTotal
defined $p{'side_effect'} ? : 5 61 66
46  
47 my $return_value = defined $p{return_value}
48 ? $p{return_value}
49 66 ▶ : $self->{return_value};
Branch: 1 branch
BranchTrueFalseTotal
defined $p{'return_value'} ? : 15 51 66
50  
51 66 $child->side_effect($side_effect);
52 64 $child->return_value($return_value);
53  
54 64 $self->{objects}{$sub}{obj} = $child;
55 64 $child->_mock($sub);
56  
57 # remove the REFCNT to the child, or else DESTROY won't be called
58 64 weaken $self->{objects}{$sub}{obj};
59  
60 64 return $child;
61 }
62 3 ▶sub mocked_subs {
Subroutine mocked_subs: called CC=3 SCAR=11.0
Pod documented
63 3 my $self = shift;
64  
65 3 my @names;
66  
67 3 for (keys %{ $self->{objects} }) {
68 9 ▶ if ($self->mocked_state($_)){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->mocked_state($_)) 8 1 9
69 8 push @names, $_;
70 }
71 }
72 3 return @names;
73 }
74 2 ▶sub mocked_objects {
Subroutine mocked_objects: called CC=2 SCAR=6.9
Pod documented
75 2 my $self = shift;
76  
77 2 my @mocked;
78 2 for (keys %{ $self->{objects} }){
79 6 push @mocked, $self->{objects}{$_}{obj};
80 }
81 2 return @mocked;
82 }
83 13 ▶sub mocked_state {
Subroutine mocked_state: called CC=3 SCAR=11.0
Pod documented
84 13 my ($self, $sub) = @_;
85  
86 13 ▶ if (! $sub){
Branch: 1 branch
BranchTrueFalseTotal
unless ($sub) 1 12 13
87 1 confess "calling mocked_state() on a Mock::Sub object requires a sub " .
88 "name to be passed in as its only parameter. ";
89 }
90  
91 12 eval {
92 12 my $test = $self->{objects}{$sub}{obj}->mocked_state();
93 };
94 12 ▶ if ($@){
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 11 12
95 1 confess "can't call mocked_state() on the class if the sub hasn't yet " .
96 "been mocked. ";
97 }
98 11 return $self->{objects}{$sub}{obj}->mocked_state;
99 }
100 0 ▶sub DESTROY {
Subroutine DESTROY: not called CC=1 SCAR=0.0
101 }
102 0 ▶sub __end {}; # vim fold placeholder
Subroutine __end: not called CC=1 SCAR=0.0
103  
104 20 1;
105 =head1 NAME
106  
107 Mock::Sub - Mock package, object and standard subroutines, with unit testing in mind.
108  
109 =for html
110 <a href="http://travis-ci.org/stevieb9/mock-sub"><img src="https://secure.travis-ci.org/stevieb9/mock-sub.png"/>
111 <a href='https://coveralls.io/github/stevieb9/mock-sub?branch=master'><img src='https://coveralls.io/repos/stevieb9/mock-sub/badge.svg?branch=master&service=github' alt='Coverage Status' /></a>
112  
113 =head1 SYNOPSIS
114  
115 # see EXAMPLES for a full use case and caveats
116  
117 use Mock::Sub;
118  
119 # disable warnings about mocking non-existent subs
120  
121 use Mock::Sub no_warnings => 1
122  
123 # create the parent mock object
124  
125 my $mock = Mock::Sub->new;
126  
127 # mock some subs...
128  
129 my $foo = $mock->mock('Package::foo');
130 my $bar = $mock->mock('Package::bar');
131  
132 # wait until a mocked sub is called
133  
134 Package::foo();
135  
136 # then...
137  
138 $foo->name; # name of sub that's mocked
139 $foo->called; # was the sub called?
140 $foo->called_count; # how many times was it called?
141 $foo->called_with; # array of params sent to sub
142  
143 # have the mocked sub return something when it's called (list or scalar).
144  
145 $foo->return_value(1, 2, {a => 1});
146 my @return = Package::foo;
147  
148 # have the mocked sub perform an action
149  
150 $foo->side_effect( sub { die "eval catch" if @_; } );
151  
152 eval { Package::foo(1); };
153 like ($@, qr/eval catch/, "side_effect worked with params");
154  
155 # extract the parameters the sub was called with (if return_value or
156 # side_effect is not used, we will return the parameters that were sent into
157 # the mocked sub (list or scalar context)
158  
159 my @args = $foo->called_with;
160  
161 # reset the mock object for re-use within the same scope
162  
163 $foo->reset;
164  
165 # restore original functionality to the sub
166  
167 $foo->unmock;
168  
169 # re-mock a previously unmock()ed sub
170  
171 $foo->remock;
172  
173 # check if a sub is mocked
174  
175 my $state = $foo->mocked_state;
176  
177 # mock out a CORE:: function. Be warned that this *must* be done within
178 # compile stage (BEGIN), and the function can NOT be unmocked prior
179 # to the completion of program execution
180  
181 my ($mock, $caller);
182  
183 BEGIN {
184 $mock = Mock::Sub->new;
185 $caller = $mock->mock('caller');
186 };
187  
188 $caller->return_value(55);
189 caller(); # mocked caller() called
190  
191 =head1 DESCRIPTION
192  
193 Easy to use and very lightweight module for mocking out sub calls.
194 Very useful for testing areas of your own modules where getting coverage may
195 be difficult due to nothing to test against, and/or to reduce test run time by
196 eliminating the need to call subs that you really don't want or need to test.
197  
198 =head1 EXAMPLE
199  
200 Here's a full example to get further coverage where it's difficult if not
201 impossible to test certain areas of your code (eg: you have if/else statements,
202 but they don't do anything but call other subs. You don't want to test the
203 subs that are called, nor do you want to add statements to your code).
204  
205 Note that if the end subroutine you're testing is NOT Object Oriented (and
206 you're importing them into your module that you're testing), you have to mock
207 them as part of your own namespace (ie. instead of Other::first, you'd mock
208 MyModule::first).
209  
210 # module you're testing:
211  
212 package MyPackage;
213
214 use Other;
215 use Exporter qw(import);
216 @EXPORT_OK = qw(test);
217
218 my $other = Other->new;
219  
220 sub test {
221 my $arg = shift;
222
223 if ($arg == 1){
224 # how do you test this?... there's no return etc.
225 $other->first();
226 }
227 if ($arg == 2){
228 $other->second();
229 }
230 }
231  
232 # your test file
233  
234 use MyPackage qw(test);
235 use Mock::Sub;
236 use Test::More tests => 2;
237  
238 my $mock = Mock::Sub->new;
239  
240 my $first = $mock->mock('Other::first');
241 my $second = $mock->mock('Other::second');
242  
243 # coverage for first if() in MyPackage::test
244 test(1);
245 is ($first->called, 1, "1st if() statement covered");
246  
247 # coverage for second if()
248 test(2);
249 is ($second->called, 1, "2nd if() statement covered");
250  
251 =head1 MOCK OBJECT METHODS
252  
253 =head2 C<new(%opts)>
254  
255 Instantiates and returns a new C<Mock::Sub> object, ready to be used to start
256 creating mocked sub objects.
257  
258 Optional options:
259  
260 =over 4
261  
262 =item C<return_value =E<gt> $scalar>
263  
264 Set this to have all mocked subs created with this mock object return anything
265 you wish (accepts a single scalar only. See C<return_value()> method to return
266 a list and for further information). You can also set it in individual mocks
267 only (see C<return_value()> method).
268  
269 =item C<side_effect =E<gt> $cref>
270  
271 Set this in C<new()> to have the side effect passed into all child mocks
272 created with this object. See C<side_effect()> method.
273  
274 =back
275  
276 =head2 C<mock('sub', %opts)>
277  
278 Instantiates and returns a new mock object on each call. 'sub' is the name of
279 the subroutine to mock (requires full package name if the sub isn't in
280 C<main::>).
281  
282 The mocked sub will return the parameters sent into the mocked sub if a return
283 value isn't set, or a side effect doesn't return anything, if available. If
284 in scalar context but a list was sent in, we'll return the first parameter in
285 the list. In list context, we simply receive the parameters as they were sent
286 in.
287  
288 Optional parameters:
289  
290 See C<new()> for a description of the parameters. Both the C<return_value> and
291 C<side_effect> parameters can be set in this method to individualize each mock
292 object, and will override the global configuration if set in C<new()>.
293  
294 There's also C<return_value()> and C<side_effect()> methods if you want to
295 set, change or remove these values after instantiation of a child sub object.
296  
297 =head2 mocked_subs
298  
299 Returns a list of all the names of the subs that are currently mocked under
300 the parent mock object.
301  
302 =head2 mocked_objects
303  
304 Returns a list of all sub objects underneath the parent mock object, regardless
305 if its sub is currently mocked or not.
306  
307 =head2 mocked_state('Sub::Name')
308  
309 Returns 1 if the sub currently under the parent mock object is mocked or not,
310 and 0 if not. Croaks if there hasn't been a child sub object created with this
311 sub name.
312  
313 =head1 SUB OBJECT METHODS
314  
315 These methods are for the children mocked sub objects returned from the
316 parent mock object. See L<MOCK OBJECT METHODS> for methods related
317 to the parent mock object.
318  
319 =head2 C<unmock>
320  
321 Restores the original functionality back to the sub, and runs C<reset()> on
322 the object.
323  
324 =head2 C<remock>
325  
326 Re-mocks the sub within the object after calling C<unmock> on it (accepts the
327 side_effect and return_value parameters).
328  
329 =head2 C<called>
330  
331 Returns true (1) if the sub being mocked has been called, and false (0) if not.
332  
333 =head2 C<called_count>
334  
335 Returns the number of times the mocked sub has been called.
336  
337 =head2 C<called_with>
338  
339 Returns an array of the parameters sent to the subroutine. C<confess()s> if
340 we're called before the mocked sub has been called.
341  
342 =head2 C<mocked_state>
343  
344 Returns true (1) if the sub the object refers to is currently mocked, and
345 false (0) if not.
346  
347 =head2 C<name>
348  
349 Returns the name of the sub being mocked.
350  
351 =head2 C<side_effect($cref)>
352  
353 Add (or change/delete) a side effect after instantiation.
354  
355 Send in a code reference containing an action you'd like the
356 mocked sub to perform.
357  
358 The side effect function will receive all parameters sent into the mocked sub.
359  
360 You can use both C<side_effect()> and C<return_value()> params at the same
361 time. C<side_effect> will be run first, and then C<return_value>. Note that if
362 C<side_effect>'s last expression evaluates to any value whatsoever
363 (even false), it will return that and C<return_value> will be skipped.
364  
365 To work around this and have the side_effect run but still get the
366 return_value thereafter, write your cref to evaluate undef as the last thing
367 it does: C<sub { ...; undef; }>.
368  
369 =head2 C<return_value>
370  
371 Add (or change/delete) the mocked sub's return value after instantiation.
372 Can be a scalar or list. Send in C<undef> to remove previously set values.
373  
374 =head2 C<reset>
375  
376 Resets the functional parameters (C<return_value>, C<side_effect>), along
377 with C<called()> and C<called_count()> back to undef/false. Does not restore
378 the sub back to its original state.
379  
380 =head1 NOTES
381  
382 This module has a backwards parent-child relationship. To use, you create a
383 mock object using L</MOCK OBJECT METHODS> C<new> and C<mock> methods,
384 thereafter, you use the returned mocked sub object L</SUB OBJECT METHODS> to
385 perform the work.
386  
387 The parent mock object retains certain information and statistics of the child
388 mocked objects (and the subs themselves).
389  
390 To mock CORE::GLOBAL functions, you *must* initiate within a C<BEGIN> block
391 (see C<SYNOPSIS> for details). It is important that if you mock a CORE sub,
392 it can't and won't be returned to its original state until after the entire
393 program process tree exists. Period.
394  
395 I didn't make this a C<Test::> module (although it started that way) because
396 I can see more uses than placing it into that category.
397  
398 =head1 AUTHOR
399  
400 Steve Bertrand, C<< <steveb at cpan.org> >>
401  
402 =head1 BUGS
403  
404 Please report any bugs or requests at
405 L<https://github.com/stevieb9/mock-sub/issues>
406  
407 =head1 REPOSITORY
408  
409 L<https://github.com/stevieb9/mock-sub>
410  
411 =head1 BUILD RESULTS
412  
413 CPAN Testers: L<http://matrix.cpantesters.org/?dist=Mock-Sub>
414  
415 =head1 SUPPORT
416  
417 You can find documentation for this module with the perldoc command.
418  
419 perldoc Mock::Sub
420  
421 =head1 ACKNOWLEDGEMENTS
422  
423 Python's MagicMock module.
424  
425 =head1 LICENSE AND COPYRIGHT
426  
427 Copyright 2016 Steve Bertrand.
428  
429 This program is free software; you can redistribute it and/or modify it
430 under the terms of either: the GNU General Public License as published
431 by the Free Software Foundation; or the Artistic License.
432  
433 See L<http://dev.perl.org/licenses/> for more information.
434  
435  
436 =cut
437  
438 20 1; # End of Mock::Sub
439  
« Sub/Child.pm ↑ Summary