Pockito.pm

filter: Statementstmt 100% 150 / 150 Branchbran 94.1% 32 / 34 Conditioncond 90.0% 9 / 10 MC/DCmcdc 83.3% 5 / 6 Subroutinesub 100% 18 / 18 Podpod 100% 8 / 8 totaltotal 98.2% 222 / 226 CC 33 SCAR 17.5
CC
33
Cov
98%
_mock_call
13.0
report_expected_calls
7.0
mock
6.0
CRAP 5.8
↑ Summary Pockito/DefaultMatcher.pm »
1 package Test::Pockito;
2  
3 21 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 21 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 21 ▶use Test::Pockito::DefaultMatcher;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 21 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 21 ▶use Class::MOP;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 21 ▶use Class::MOP::Class;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 21 our $VERSION = "0.02";
13  
14 =head1 NAME
15  
16 Pockito - Inspired by Mockito, a library to build mock objects for test driven development
17  
18 =head1 SYNOPSIS
19  
20 Pockito allows for very matter of fact mock definitions and uses.
21  
22 =over 1
23  
24 =item 1. when A happens, produce B
25  
26 =item 2. if it's impossible for A to happen, complain
27  
28 =item 3. make every A produce B, or have it return different values
29  
30 =item 4. after using my mock objects, let me know if my expectations were met
31  
32 =back
33  
34 With the advent of Class::MOP, new methods for package creation exists. The almighty Moose is made possible by it. Pockito is intended to fit most ways of class creation.
35  
36 =head1 DESCRIPTION
37  
38 A mock object is a thing that imitates something else that may be hard to setup or can be brittle. Examples of such are databases, network connections, and things deemed non trivial that may involve state.
39  
40 The following is an overly complicated class that marries two people together, that takes two user ids and inserts that user1 is married to user2, and vice versa. We should probably check to make sure they exist to make sure they aren't married already.
41  
42 Our database object we wish to mock out may provide methods like, is_married( $user ), and marry($user1, $user2);
43  
44  
45 package Love;
46  
47 sub new {
48 return bless {}, Love;
49 }
50  
51 sub marry {
52 my $self = shift;
53 my $user1 = shift;
54 my $user2 = shift;
55  
56 my $db_object = $self->{'db_object'};
57  
58 if ( $db_object->is_married($user1) == 0
59 && $db_object->is_married($user2) == 0 )
60 {
61 $db_object->marry( $user1, $user2 );
62 $db_object->marry( $user2, $user1 );
63 return 1;
64 }
65 return 0;
66 }
67  
68 package MyDbClass;
69  
70 sub is_married {
71 # do some complicated stuff
72 }
73  
74 sub marry {
75 # do some other complicated stuff
76 }
77  
78 #Our test can be
79  
80 use Test::Pockito;
81 use Test::Simple;
82  
83 my $pocket = Test::Pockito->new("MyNamespace");
84 my $db_mock = $pocket->mock("MyDbClass");
85  
86 $pocket->when( $db_mock->is_married("bob") )->then(0);
87 $pocket->when( $db_mock->is_married("alice") )->then(0);
88 $pocket->when( $db_mock->marry( "alice", "bob" ) )->then();
89 $pocket->when( $db_mock->marry( "bob", "alice" ) )->then();
90  
91 my $target = Love->new();
92 $target->{'db_object'} = $db_mock;
93  
94 ok( $target->marry( "bob", "alice" ) == 1, "single to married == success!" );
95  
96 ok( scalar keys %{ $pocket->expected_calls } == 0,
97 "No extra cruft calls, huzzah!" );
98  
99 A few things are going on here.
100  
101 The $pocket object holds logs of interactions between objects you mock through it. This offers the convenience of validating through one object, but if you wish to have two completely different mocks, one can create different Pockito objects. The namespace passed along is a prefix to all packages created for the mock to avoid collisions. In this case, a MyNamespace::Love package is created.
102  
103 The ->mock call is just like ->new except the package name is passed. It will inspect the package for all subs, and in the case of Moose, attributes to mimic.
104  
105 $pocket->when( .... )->then( ... ) records many things. It records in the ->is_married sub is called, with a parameter "bob". When this combination occurs the first time, return 0. One can queue up multiple calls with the same signature to have multiple results.
106  
107 $pocket->{'warn'} tells Pockito to complain about calls that it doesn't expect.
108  
109 Finally, a hash of calls that have yet to be executed are returned via expected_calls. Since we called everything we expected, we can celebrate. If is_married returned a random number, we could inspect the result of expected_calls and make a judgement call if the expectations were met.
110  
111 There are some conveniences written in for default calls, partial mocks, outputting a formated report of what method calls have yet to be called, custom equality comparisons for parameters and bridges for package creation.
112  
113  
114 =cut
115  
116 60 ▶sub _push_expected_call {
Subroutine _push_expected_call: called CC=1 SCAR=0.0
117 60 my $self = shift;
118 60 my $mock_call = shift;
119  
120 60 my $package = $$mock_call{'package'};
121 60 my $method = $$mock_call{'method'};
122 60 my $params = $$mock_call{'params'};
123 60 my $result = $$mock_call{'result'};
124 60 my $execute = $$mock_call{'execute'};
125  
126 push(
127 60 @{ $self->{'_calls'}{$package}{$method} },
128 { 'params' => $params, 'result' => $result, 'execute' => $execute }
129 );
130 }
131  
132 129 ▶sub _mock_call {
Subroutine _mock_call: called CC=13 SCAR=25.6
133 129 my $self = shift;
134 129 my $package = shift;
135 129 my $method = shift;
136 129 my @params = @_;
137  
138 129 ▶ return if ( $method eq "DESTROY" );
Branch: 1 branch
BranchTrueFalseTotal
if $method eq "DESTROY" 2 127 129
139  
140 127 %{ $self->{'_last_mock_call'} } = (
141 'package' => $package,
142 'method' => $method,
143 'params' => \@params
144 );
145  
146 127 ▶ if ( exists $self->{'_calls'}{$package}{$method} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $self->{"_calls"}{$package}{$method}) 68 59 127
147 68 my @expectation = @{ $self->{'_calls'}{$package}{$method} };
148  
149 68 my $method_last_index = $#expectation;
150 68 foreach my $x ( 0 .. $#expectation ) {
151 my ($found) =
152 $self->{'call_matcher'}( $package, $method, \@params,
153 67 $expectation[$x]->{'params'} );
154 67 ▶ if ($found) {
Branch: 1 branch
BranchTrueFalseTotal
if ($found) 54 13 67
155 54 splice @{ $self->{'_calls'}{$package}{$method} }, $x, 1;
156  
157 54 my @result = @{ $expectation[$x]->{'result'} };
158 54 $self->{'_last_mock_call'}{'result'} = \@result;
159 54 $self->{'_last_mock_call'}{'complete'} = 1;
160 $self->{'_last_mock_call'}{'execute'} =
161 54 $expectation[$x]->{'execute'};
162  
163 54 ▶ if ( $self->{'go'} and $expectation[$x]->{'execute'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'go'} and $expectation[$x]{'execute'}) { } 6 48 54
Condition100%3/3
$self->{"go"} and $expectation[$x]{"execute"}
!ll&&!rl&&r
2466
MC/DC100%2/2
$self->{"go"} and $expectation[$x]{"execute"}
$self->{"go"} $expectation[$x]{"execute"}
Truth table100%3/3
A and B
A= $self->{"go"}B= $expectation[$x]{"execute"}
ABresult
0X0
100
111
164 6 return $result[0]();
165 }
166 else {
167 48 ▶ return wantarray ? @result : shift @result;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 14 34 48
168 }
169 }
170 }
171 }
172 73 ▶ if ( exists $self->{'_defaultcalls'}{$package}{$method} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $self->{"_defaultcalls"}{$package}{$method}) 16 57 73
173 16 my @expectation = @{ $self->{'_defaultcalls'}{$package}{$method} };
174  
175 16 my $method_last_index = $#expectation;
176 16 foreach my $x ( 0 .. $#expectation ) {
177 my ($found) =
178 $self->{'call_matcher'}( $package, $method, \@params,
179 22 $expectation[$x]->{'params'} );
180  
181 22 my (@result) = @{ $expectation[$x]->{'result'} };
182 22 ▶ return wantarray ? @result : shift @result if $found;
Branch: 2 branches
BranchTrueFalseTotal
if $found 14 8 22
wantarray ? : 2 12 14
183 }
184  
185 }
186  
187 59 ▶ if ( $self->{warn} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"warn"}) 2 57 59
188 2 my $original_package = $package;
189 2 $original_package =~ s/^$self->{namespace}:://;
190  
191 2 carp("Mock call not found to ${original_package}->${method}");
192 }
193  
194 59 return;
195 }
196  
197 =head1 ATTRIBUTES
198  
199 =over 4
200  
201 =item warn
202  
203 Setting the hash key of warn to 1 will cause a mock call that wasn't scheduled, but called, to be carped.
204  
205 =item go
206  
207 Pockito can keep track of state pretty well, except when ->execute is called for the same parameters more than once. Perl evaluates lazily, so
208  
209 $pocket->when( $mock->a(1) )->execute( sub{ ... } );
210 $pocket->when( $mock->a(1) )->execute( sub{ ... } );
211  
212 will cause the anonymous sub to be called twice. If this occurs a warning will be produced. Toggle go to 0 before scheduling calls, and back to 1 when the test starts to use mocks to quiet it.
213  
214 =back
215  
216 =head1 METHODS
217  
218 =over 4
219  
220 =item new(package [, matcher])
221  
222 Instanciate Pockito. package is a prefix name for the namespace for your mocks. It would be rude to assume every nacemspace will be valid. You do that work. matcher is a reference to a sub to check for equality of a mocked call. See Test::Pockito::DefaultMatcher::default_call_match for more information on how to implement this subroutine.
223  
224 =cut
225  
226 44 ▶sub new {
Subroutine new: called CC=2 SCAR=6.9
Pod documented
227 44 my $package = shift;
228 44 my $namespace = shift;
229 44 ▶ my $matcher = shift || \&Test::Pockito::DefaultMatcher::default_call_match;
Condition100%2/2
shift() || \&Test::Pockito::DefaultMatcher::default_call_match
l!l
242
MC/DC100%1/1
shift() || \&Test::Pockito::DefaultMatcher::default_call_match
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
230 44 return bless {
231 '_calls' => {},
232 'namespace' => $namespace,
233 'call_matcher' => $matcher,
234 'go' => 1
235 }, $package;
236 }
237  
238 =pod
239  
240 =item mock(module, [excluded1, excluded2, ..., excluded-n])
241  
242 module is the name of the package to inspect and construct a mock from. The result is an objet that looks just like the object you would normally use. In the case of IO::Socket::connect, a connect method would be constructed. In the case of Moose, attributes and methods are mocked out, right down to meta.
243  
244 The second parameter is a list of methods not to mock. This is useful for partial mocks for those heavily coupled methods. Example uses are for data that is harder to setup, but easier to call a helping method.
245
246 =cut
247  
248 42 ▶sub mock {
Subroutine mock: called CC=6 SCAR=17.9
Pod documented
249 42 my $self = shift;
250 42 my $module = shift;
251 42 my @excluded = @_;
252  
253 42 my $package = $self->{'namespace'} . "::" . $module;
254 42 my $module_meta = Class::MOP::Class->initialize($module);
255 42 my %dispatch = ();
256  
257 42 foreach my $method ( $module_meta->get_method_list ) {
258 54 ▶ if ( !grep { $method eq $_ } @excluded ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {$method eq $_;} @excluded) 52 2 54
259 28 ▶ $dispatch{$method} = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine AUTOLOAD: called CC=1 SCAR=0.0
260 28 shift;
261 28 $self->_mock_call( $package, $method, @_ );
262 }
263 52 }
264 }
265  
266 42 ▶ $module_meta->make_mutable if $module_meta->can("make_mutable");
Branch: 1 branch
BranchTrueFalseTotal
if $module_meta->can("make_mutable") 42 0 42
267  
268 42 ▶ if ( $module_meta->can("get_all_attributes") ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($module_meta->can("get_all_attributes")) 42 0 42
269 42 foreach ( $module_meta->get_all_attributes ) {
270 1 my $attr = $_->clone( required => 0 );
271 1 $module_meta->add_attribute($attr);
272 }
273 }
274  
275 Class::MOP::Class->create(
276 42 $package,
277 'methods' => \%dispatch,
278 'superclasses' => [$module]
279 )->new_object();
280 }
281  
282 =pod
283  
284 =item when( ... )
285  
286 The idiom is ->when( $mock_object->a_call( ... )->then( ... ). Some house keeping is done within when. It is possible to write:
287  
288 $pocket->when();
289 $mock->a_call( ... );
290 $pocket->then( ... );
291  
292 It is awkward. Don't do that.
293  
294 =cut
295  
296 62 ▶sub when {
Subroutine when: called CC=4 SCAR=13.9
Pod documented
297 62 my $self = shift;
298 62 ▶ if ( $self->{'_last_mock_call'}{'complete'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_last_mock_call"}{"complete"}) 6 56 62
299 6 $self->_push_expected_call( $self->{'_last_mock_call'} );
300 }
301 62 ▶ if ( $self->{'go'} and $self->{'_last_mock_call'}{'execute'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"go"} and $self->{"_last_mock_call"}{"execute"}) 2 60 62
Condition100%3/3
$self->{"go"} and $self->{"_last_mock_call"}{"execute"}
!ll&&!rl&&r
5552
MC/DC100%2/2
$self->{"go"} and $self->{"_last_mock_call"}{"execute"}
$self->{"go"} $self->{"_last_mock_call"}{"execute"}
Truth table100%3/3
A and B
A= $self->{"go"}B= $self->{"_last_mock_call"}{"execute"}
ABresult
0X0
100
111
302 2 carp(
303 "when called after an executable mock result occured. set ->{'go'} = 1 after all mocks are setup"
304 );
305 }
306 62 return $self;
307 }
308  
309 =pod
310  
311 =item then( ... )
312  
313 then takes 0 or many parameters, the result of the subroutine call should the mock get called for a method and the right parameters. Then is the right side of the bookshelf holding up the mock. No when without a then and vice versa.
314  
315 then will record one instance of the combination of method and parameters returning the values requested. To illustrate:
316  
317 $pocket->when( $db_mock->is_married("bob") )->then(2);
318 $pocket->when( $db_mock->is_married("alice") )->then(3);
319 $pocket->when( $db_mock->is_married("bob") )->then(1);
320  
321 print $db_mock->is_married("alice");
322 print $db_mock->is_married("bob");
323 print $db_mock->is_married("bob");
324  
325 will print 321. I've told my mock to return 2 and then 1 for my two consecutive calls with parameter bob. Alice, she's alone in her call expectations, until she gets married.
326  
327 Note well, within the default matcher, Test::Pockito::DefaultMatcher, there are ways to match anything that's defined instead of specific values, or any array reference and so on. See that documentation for details.
328  
329 =cut
330  
331 44 ▶sub then {
Subroutine then: called CC=1 SCAR=0.0
Pod documented
332 44 my $self = shift;
333 44 my @result = @_;
334  
335 44 $self->{'_last_mock_call'}{'result'} = \@result;
336 44 $self->_push_expected_call( $self->{'_last_mock_call'} );
337  
338 44 delete $self->{'_last_mock_call'};
339 }
340  
341 =pod
342  
343 =item execute( ... )
344  
345 Execute takes 1 parameter, a reference to a sub to execute on call. Similar to then, but useful when state comes into play. Examples of use would be returning a random number or throwing an exception.
346  
347 =cut
348  
349 10 ▶sub execute {
Subroutine execute: called CC=1 SCAR=0.0
Pod documented
350 10 my $self = shift;
351 10 my $sub = shift;
352  
353 10 $self->{'_last_mock_call'}{'result'} = [$sub];
354 10 $self->{'_last_mock_call'}{'execute'} = 1;
355 10 $self->_push_expected_call( $self->{'_last_mock_call'} );
356  
357 10 delete $self->{'_last_mock_call'};
358 }
359  
360 =pod
361  
362 =item default( ... )
363  
364 default acts exacty like then except it if a mock using ->then doesn't match, check for a default. Defaults are not reported if they are not used.
365  
366 =cut
367  
368 8 ▶sub default {
Subroutine default: called CC=1 SCAR=0.0
Pod documented
369 8 my $self = shift;
370 8 my $mock_call = $self->{'_last_mock_call'};
371 8 my @result = @_;
372  
373 8 my $package = $$mock_call{'package'};
374 8 my $method = $$mock_call{'method'};
375 8 my $params = $$mock_call{'params'};
376  
377 unshift(
378 8 @{ $self->{'_defaultcalls'}{$package}{$method} },
379 { 'params' => $params, 'result' => \@result }
380 );
381 }
382  
383 =item report_expected_calls( [\*HANDLE] )
384  
385 Prints out in a pretty format, all packages, calls and parameters that were unused. to STDOUT or the glob passed in.
386  
387 =cut
388  
389 6 ▶sub report_expected_calls {
Subroutine report_expected_calls: called CC=7 SCAR=19.5
Pod documented
390 6 my $self = shift;
391 6 ▶ my $handle = shift || \*STDOUT;
Condition50%1/2
shift() || \*STDOUT
l!l
60
MC/DC0%0/1
shift() || \*STDOUT
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
392  
393 6 my $last_package = "";
394 6 foreach my $package ( keys %{ $self->{'_calls'} } ) {
395 10 foreach my $call ( keys %{ $self->{'_calls'}{$package} } ) {
396 10 my @calls = $self->{'_calls'}{$package}{$call};
397 10 foreach my $x ( 0 .. $#calls ) {
398 10 foreach my $y ( 0 .. $#{ $calls[$x] } ) {
399 8 ▶ if ( $last_package ne $package ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($last_package ne $package) 4 4 8
400 4 print $handle "${package}::\n";
401 4 $last_package = $package;
402 }
403 8 print $handle "\t$call(";
404 8 my @values = @{ $calls[$x][$y]->{'params'} };
405 8 @values = map { $_ =~ s/"/\" /g; $_ } @values;
406 8 print $handle join ",", @values;
407 8 print $handle ");\n";
408 }
409 }
410 }
411 }
412 }
413  
414 =item expected_calls
415  
416 Returns a complicated data structure if you really wish to know the outstanding history
417  
418 {
419 $package =>
420 $method =>
421 [
422 {
423 'params' => [ $p1, $p2, ... $pn ],
424 'result' => [ $r1, $r2, ... $rn ]
425 }
426 ]
427 }
428  
429 For:
430  
431 Foo::bar( 1, 2, 3 ) = ( 4, 5, 6 )
432  
433 my ( $one, $two, $three ) = { 'Foo' }{ 'bar' }[0]->{'params'};
434 my ( $four, $five, $six ) = { 'Foo' }{ 'bar' }[0]->{'result'};
435  
436  
437 =cut
438  
439 5 ▶sub expected_calls {
Subroutine expected_calls: called CC=6 SCAR=17.9
Pod documented
440 5 my $self = shift;
441  
442 5 foreach my $package ( keys %{ $self->{'_calls'} } ) {
443 5 foreach my $method ( keys %{ $self->{'_calls'}{$package} } ) {
444 delete $self->{'_calls'}{$package}{$method}
445 6 ▶ if ( $#{ $self->{'_calls'}{$package}{$method} } == -1 );
Branch: 1 branch
BranchTrueFalseTotal
if $#{$$self{"_calls"}{$package}{$method};} == -1 4 2 6
446 }
447 }
448  
449 5 foreach my $package ( keys %{ $self->{'_calls'} } ) {
450 delete $self->{'_calls'}{$package}
451 5 ▶ if ( !scalar keys %{ $self->{'_calls'}{$package} } );
Branch: 1 branch
BranchTrueFalseTotal
unless scalar keys %{$$self{"_calls"}{$package};} 3 2 5
452 }
453 5 return $self->{'_calls'};
454 }
455  
456  
457 =back
458  
459  
460 =head1 SUPPORT
461  
462 exussum@gmail.com
463  
464 =head1 AUTHOR
465  
466 Spencer Portee
467 CPAN ID: EXUSSUM
468 exussum@gmail.com
469  
470 =head1 SOURCE
471  
472 http://bitbucket.org/exussum/pockito/
473  
474 =head1 COPYRIGHT
475  
476 This program is free software licensed under the...
477  
478 The BSD License
479  
480 The full text of the license can be found in the
481 LICENSE file included with this module.
482  
483  
484 =head1 SEE ALSO
485  
486 perl(1).
487  
488 =cut
489  
490 21 1;
↑ Summary Pockito/DefaultMatcher.pm »