blib/lib/MooseX/Contract.pm

filter: Statementstmt 92.0% 104 / 113 Branchbran 75.0% 36 / 48 Conditioncond 70.5% 12 / 17 MC/DCmcdc 40.0% 4 / 10 Subroutinesub 95.4% 21 / 22 Podpod 100% 8 / 8 totaltotal 84.8% 185 / 218 CC 34 SCAR 16.4
CC
34
Cov
85%
__ANON__
11.1
contract
7.2
__ANON__
6.3
CRAP 5.2
↑ Summary
1 package MooseX::Contract;
2  
3 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 5 ▶use Moose ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 5 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 5 ▶use Moose::Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 5 ▶use Moose::Util::TypeConstraints;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 5 ▶use Moose::Util qw(add_method_modifier find_meta);
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 5 Moose::Exporter->setup_import_methods(
13 with_caller => [ qw(invariant contract) ],
14 as_is => [qw(check assert accepts returns void with_context)],
15 also => 'Moose',
16 );
17  
18 =head1 NAME
19  
20 MooseX::Contract - Helps you avoid Moose-stakes!
21  
22 =head1 VERSION
23  
24 Version 0.01
25  
26 =cut
27  
28 5 our $VERSION = '0.01';
29  
30 =head1 WARNING
31  
32 This module should be considered EXPERIMENTAL and should not be used in
33 critical applications unless you're willing to deal with all the typical
34 bugs that young, under-tested software has to offer!
35  
36 =head1 SYNOPSIS
37  
38 This module provides "Design by Contract" functionality using Moose
39 method hooks.
40  
41 For example, in your Moose-built class:
42  
43 package MyEvenInt;
44  
45 use MooseX::Contract; # imports Moose for you!
46 use Moose::Util::TypeConstraints;
47  
48 my $even_int = subtype 'Int', where { $_ % 2 == 0 };
49  
50 invariant assert { shift->{value} % 2 == 0 } '$self->{value} must be an even integer';
51  
52 has value => (
53 is => 'rw',
54 isa => $even_int,
55 required => 1,
56 default => 0
57 );
58  
59 contract 'add'
60 => accepts [ $even_int ]
61 => returns void,
62 with_context( # very contrived...
63 pre => sub {
64 my $self = shift;
65 my $add = shift;
66 return [ $self->{value}, $add ];
67 },
68 post => assert {
69 my $pre = shift;
70 $pre->[0] + $pre->[1] == shift->{value};
71 }
72 );
73 sub add {
74 my $self = shift;
75 my $incr = shift;
76 $self->{value} += $incr;
77 return;
78 }
79  
80 contract 'get_multiple'
81 => accepts ['Int'],
82 => returns [$even_int];
83 sub get_multiple {
84 return shift->{value} * shift;
85 }
86  
87 no MooseX::Contract;
88  
89 =head1 DESCRIPTION
90  
91 The Design by Contract (DbC) method of programming could be seen as
92 simply baking some simple unit test or assertions right into your regular
93 code path. The set of assertions or tests for a given class is considered
94 that class' contract - a guarantee of how any instance of that class will
95 behave and appear. This implementation of DbC provides three types of
96 assertions (referred to here as "contract clauses") when defining your
97 class' contract:
98  
99 =over 4
100  
101 =item C<pre> clause
102  
103 This clause is attached to a specific method and is executed before
104 control is passed to the original method. Typically, these could be
105 used to validate incoming parameters but one might also validate state
106 of the object itself in this type of clause.
107  
108 =item C<post> clause
109  
110 This clause is also attached to a specific method and is executed after
111 the original method has been called. This type of DbC clause has the
112 opportunity to validate return values (or lack thereof) as well as the
113 state of the object following the method.
114  
115 =item C<invariant> clause
116  
117 This is a special type of DbC clause that makes assertions about the
118 ongoing state of the object. These clauses are invoked after each
119 public method (subs that don't begin with an underscore) is called.
120 Unlike C<post> clauses, however, these clauses are only allowed to
121 inspect the object's state (not the return values of the method).
122  
123 =back
124  
125 The contract clauses are created using a declarative syntax as inspired
126 by the Moose syntax.
127  
128 One item worht noting: there's no guaranteed safe way to resume execution
129 after a contract clause validation failure. For instance, if a method does
130 something naughty and causes a C<post> or C<invariant> clause to fail,
131 the object in question may be irreperably broken. Catching these errors
132 and ignoring them (or in some cases, trying to handle them) is not
133 advisable and makes the use of this module pointless. These contract
134 errors should be allowed to die an ugly death. If you're concerned
135 about the end user experience, you should disable all MooseX::Contract
136 functionality in your production code and plan to have enough coverage
137 in your development and test environments that you're comfortable with
138 the checks not being in effect.
139  
140  
141 =head1 EXPORT
142  
143 The following subs are exported by default and will be removed from
144 the caller's namespace using C<no MooseX::Contract>.
145  
146 =head2 contract
147  
148 This is the core method of the module. It sets up a contract clause for a
149 specific method (or methods) and uses Moose's C<around> hook to execute
150 the C<pre> and C<post> clauses that are specified. Some of the "sugar"
151 listed below help with building up the contract that you want to express.
152  
153 The first argument to C<contract> is always the method name. Following
154 the method name, you must pass pairs of arguments (type => CodeRef). The
155 C<type> indicates the clause of the contract (pre or post) that the CodeRef
156 should be applicable to. Another special C<invar> type of clause is
157 very similar to the C<post> type except that it doesn't receive the return
158 values to verify (demonstrated below).
159  
160 Typically you will only want to use C<pre> and C<post> with the C<contract>
161 method.
162  
163 For instance (using none of the sugar supplied below):
164  
165 contract 'some_method',
166 pre => sub {
167 my($self,@params) = @_;
168 # do some validation here, dieing if validation fails
169 }
170 post => sub {
171 my($self, @return_values) = @_;
172 # do some validation here, dieing if validation fails
173 };
174  
175 You can provide as many C<pre> and C<post> hook but each of them must
176 be preceded in the list by the lable (C<pre> or C<post>). They will be
177 executed in the order they are listed and the first one that fails will
178 result in the operation dieing.
179  
180 As noted below in the PERFORMANCE section, you can short circuit all
181 functionality provided by this module by setting the NO_MOOSEX_CONTRACT
182 environment variable. That essentially makes the C<contract> sub a no-op.
183  
184 =head2 invariant
185  
186 This is a special kind of contract clause that adds a C<post> clause to all
187 public method calls. Typically you would use this to assert a specific
188 characteristic about the object itself.
189  
190 =head2 check
191  
192 This is pure sugar and simply returns the CodeRef that is passed in.
193  
194 =head2 assert
195  
196 This helper method creates a wrapper clause that will C<croak> if the
197 underlying anonymous sub does not return a true value.
198  
199 contract 'some_method'
200 pre => assert {
201
202 };
203  
204 =head2 accepts
205  
206 This helper method takes an ArrayRef of Moose type constraints and creates
207 a C<pre> clause that verifies the type of the value or values passed
208 in to the method by the caller. Any extra arguments passed to the method
209 that don't have explicit restrictions given to C<accepts> will be passed
210 without validation (this may change in the future)
211  
212 # method_a accepts at least two Int arguments
213 contract method_a => accepts ['Int', 'Int'];
214  
215 # method_b accepts no arguments
216 contract method_b => accepts void;
217  
218 # works with any type that Moose will recognize
219 my $cheezey = subtype 'Str', where { m/cheese/ };
220 contract method_c => accepts ['MyClass', 'ArrayRef[Str]', $cheezey];
221  
222 =head2 returns
223  
224 This helper method creates a C<post> clause that looks at the value
225 or values returned by the method it's affecting. PLEASE NOTE: these
226 checks only have a chance to evaluate the values that are actually
227 returned to the caller. If the caller is using scalar context, then this
228 validation will get the value that is returned when in scalar context.
229 More importantly (surprisingly?) if the caller is executing the statement
230 in void context, these checks won't receive any return values to evaluate
231 but may still validate the state of $self (the first argument received by
232 the post hook).
233  
234 =head2 void
235  
236 A simple helper method that asserts zero items were passed (useful in
237 specifying C<accepts> and C<returns> clauses).
238  
239 =head2 with_context
240  
241 This helper method wraps a C<pre> and C<post> clause with closures that allow
242 a values to be compared between the two clauses. The C<SYNOPSIS> above shows
243 an example of how to use this functionality.
244  
245 =cut
246  
247 5 our @CARP_NOT = qw(Class::MOP::Method::Wrapped);
248  
249 sub assert(&;$);
250 8 ▶sub void() { return assert { shift; @_ == 0 } "too many values (expected 0)" }
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine void: called CC=1 SCAR=0.0
Pod documented
251  
252 3 ▶sub invariant {
Subroutine invariant: called CC=3 SCAR=11.0
Pod documented
253 3 my $caller = shift;
254 3 my %packages = map { $_ => 1 } ($caller, grep { ! ref($_) } @_);
255 3 my @checks = map { (invar => $_) } grep { ref($_) eq 'CODE' } @_;
256 contract(
257 $caller,
258 [
259 11 map { $_->name }
260 3 ▶ grep { $_->name ne 'meta' && $_->name !~ m/^_/ && exists( $packages{ $_->original_package_name } ) }
Condition83%5/6
$_->name ne 'meta' && !($_->name =~ /^_/) && exists $packages{$_->original_package_name}
!ll&&!rl&&r
33911
$_->name ne "meta" and not $_->name =~ /^_/
!ll&&!rl&&r
3050
MC/DC66%2/3
$_->name ne 'meta' && !($_->name =~ /^_/) && exists $packages{$_->original_package_name}
$_->name ne "meta" not $_->name =~ /^_/ exists $packages{$_->original_package_name}
Truth table75%3/4
A and not(B) && C
A= $_->name ne "meta"B= not $_->name =~ /^_/C= exists $packages{$_->original_package_name}
ABCresult
0XX0
10X0
1100
1111
261 find_meta($caller)->get_all_methods
262 ],
263 @checks
264 );
265 }
266  
267 13 ▶sub contract {
Subroutine contract: called CC=7 SCAR=19.7
Pod documented
268 13 ▶ return if($ENV{NO_MOOSEX_CONTRACT}); # bail if contracts are turned off
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"NO_MOOSEX_CONTRACT"} 0 13 13
269 13 my $caller = shift;
270 13 my $method = shift; # could be a regex or ARRAY or scalar
271 13 my %args = (pre => [], post => [], invar => []);
272 13 ▶ if(@_ % 2){
Branch: 1 branch
BranchTrueFalseTotal
if (@_ % 2) 0 13 13
273 0 croak "contract must have even pairs of arguments: @_";
274 }
275 13 ▶ while(@_){
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 24 13 37
276 24 my($type, $code) = splice(@_,0,2);
277 24 ▶ if(!exists($args{$type})){
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $args{$type}) 0 24 24
278 0 croak "unknown contract type $type";
279 }
280 24 ▶ if(ref($code) ne 'CODE'){
Branch: 1 branch
BranchTrueFalseTotal
if (ref $code ne "CODE") 0 24 24
281 0 croak "invalid argument $code (should be a CodeRef";
282 }
283 24 push(@{ $args{ $type } }, $code);
284 }
285 add_method_modifier(
286 $caller, 'around',
287 [
288 ref($method) eq 'ARRAY' ? @$method : $method,
289 30 ▶ sub {
Subroutine __ANON__: called CC=11 SCAR=24.0
290 30 my $next = shift;
291 30 my ($self, @params) = @_;
292 30 foreach my $m ( @{ $args{pre} } ) {
293 17 eval { $m->($self, @params) };
294 17 ▶ croak "pre contract error for $method: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 4 13 17
295 }
296 26 my @retval;
297 # contortions to maintain calling context
298 26 ▶ if(defined wantarray){
Branch: 1 branch
BranchTrueFalseTotal
if (defined wantarray) { } 9 17 26
299 9 ▶ if(wantarray){
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 0 9 9
300 0 @retval = $next->(@_);
301 } else {
302 9 $retval[0] = $next->(@_);
303 }
304 } else {
305 # no return values available in this case...
306 17 $next->(@_);
307 }
308  
309 25 foreach my $m ( @{ $args{post} } ) {
310 11 eval { $m->($self, @retval) };
311 11 ▶ croak "post contract error for $method: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 2 9 11
312 }
313  
314 23 foreach my $m( @{ $args{invar} } ){
315 14 eval { $m->($self) };
316 14 ▶ croak "invariant contract error for $method: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 13 14
317 }
318 22 ▶ return defined(wantarray) ? wantarray ? @retval : $retval[0] : ();
Branch: 2 branches
BranchTrueFalseTotal
defined wantarray ? : 7 15 22
wantarray ? : 0 7 7
319 },
320 13 ▶ ]
Branch: 1 branch
BranchTrueFalseTotal
ref $method eq 'ARRAY' ? : 3 10 13
321 );
322 }
323  
324 8 ▶sub accepts($) {
Subroutine accepts: called CC=4 SCAR=14.5
Pod documented
325 8 ▶ return if(!@_);
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 0 8 8
326 8 my $accepts = shift;
327 8 ▶ if(ref($accepts) eq 'ARRAY'){
Branch: 2 branches
BranchTrueFalseTotal
if (ref $accepts eq 'ARRAY') { } 7 1 8
elsif (ref $accepts eq 'CODE') { } 1 0 1
328 7 return pre => _make_type_validator( "accepts", $accepts);
329 } elsif(ref($accepts) eq 'CODE'){
330 1 return pre => $accepts;
331 } else {
332 0 croak "invalid parameter to accepts: $accepts";
333 }
334 }
335  
336 11 ▶sub _make_type_validator {
Subroutine _make_type_validator: called CC=1 SCAR=0.0
337 11 my $mode = shift;
338 11 my @expected = map { Moose::Util::TypeConstraints::find_or_parse_type_constraint($_) } @{ $_[0] };
339 10 ▶ return sub {
Subroutine __ANON__: called CC=6 SCAR=18.5
340 10 my $self = shift;
341 10 ▶ if ( $mode eq 'accepts' && @_ < @expected ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode eq "accepts" and @_ < @expected) 0 10 10
Condition66%2/3
$mode eq "accepts" and @_ < @expected
!ll&&!rl&&r
280
MC/DC0%0/2
$mode eq "accepts" and @_ < @expected
$mode eq "accepts" @_ < @expected
Truth table66%2/3
A and B
A= $mode eq "accepts"B= @_ < @expected
ABresult
0X0
100
111
342 0 croak "$mode contract expects at least " . @expected . " values, only " . @_ . " parameters passed";
343 }
344 10 ▶ for ( my $i = 0 ; $i < @_ && $i < @expected ; $i++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @_ and $i < @expected) 10 7 17
Condition66%2/3
$i < @_ and $i < @expected
!ll&&!rl&&r
7010
MC/DC50%1/2
$i < @_ and $i < @expected
$i < @_ $i < @expected
Truth table66%2/3
A and B
A= $i < @_B= $i < @expected
ABresult
0X0
100
111
345 10 my $error = $expected[$i]->validate( $_[$i] );
346 10 ▶ croak $error if $error;
Branch: 1 branch
BranchTrueFalseTotal
if $error 3 7 10
347 }
348 7 return 1;
349 11 };
350 }
351  
352 8 ▶sub returns($) {
Subroutine returns: called CC=4 SCAR=14.5
Pod documented
353 8 ▶ return if(!@_);
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 0 8 8
354 8 my $returns = shift;
355 8 ▶ if(ref($returns) eq 'ARRAY'){
Branch: 2 branches
BranchTrueFalseTotal
if (ref $returns eq 'ARRAY') { } 4 4 8
elsif (ref $returns eq 'CODE') { } 4 0 4
356 4 return post => _make_type_validator( "returns", $returns);
357 } elsif(ref($returns) eq 'CODE') {
358 4 return post => $returns;
359 } else {
360 0 croak "invalid parameter to accepts: $returns";
361 }
362 }
363  
364 0 ▶sub check(&) { return @_ };
Subroutine check: not called CC=1 SCAR=6.9
Pod documented
365  
366 2 ▶sub with_context {
Subroutine with_context: called CC=3 SCAR=12.0
Pod documented
367 2 my %args = @_;
368 2 ▶ if(!exists($args{pre}) || !exists($args{post})){
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $args{"pre"} and exists $args{"post"}) 0 2 2
Condition33%1/3
exists $args{"pre"} and exists $args{"post"}
!ll&&!rl&&r
002
MC/DC0%0/2
exists $args{"pre"} and exists $args{"post"}
exists $args{"pre"} exists $args{"post"}
Truth table33%1/3
A and B
A= exists $args{"pre"}B= exists $args{"post"}
ABresult
0X0
100
111
369 0 croak "both 'pre' and 'post' clauses must be specified when using context";
370 }
371 2 my $context;
372 return (
373 3 ▶ pre => sub { $context = $args{pre}->(@_) },
Subroutine __ANON__: called CC=1 SCAR=0.0
374 3 ▶ post => sub { $args{post}->( $context, @_ ) }
Subroutine __ANON__: called CC=1 SCAR=0.0
375 2 );
376 }
377  
378 11 ▶sub assert(&;$) {
Subroutine assert: called CC=2 SCAR=6.9
Pod documented
379 11 my($code, $message) = @_;
380 11 ▶ $message ||= "assertion failed";
Condition100%2/2
$message ||= "assertion failed"
l!l
101
MC/DC100%1/1
$message ||= "assertion failed"
$message
Truth table100%2/2
A
A= $message
Aresult
11
00
381 29 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
382 29 ▶ $code->(@_) or croak $message;
Branch: 1 branch
BranchTrueFalseTotal
&$code(@_) or croak($message) 25 4 29
383 }
384 11 }
385  
386 =head1 PERFORMANCE
387  
388 As the saying goes, you never get something for nothing. That is
389 definitely the case with this module (or indeed any usage of Moose's
390 method hooks). At the time of this writing, L<Class::MOP> claims that an
391 C<around> method hook is ~5x slower than a standard method invocation.
392 This facter doesn't include any of the actual checks that are run as
393 part of validating the contract so (short of doing actual profiling)
394 I would guess using MooseX::Contract could slow your method calls down
395 by up to 10x.
396  
397 That is a pretty considerable drawback to using the features of this
398 module. However, to mitigate this, MooseX::Contract allows you to
399 turn off all method wrapping if it detects the C<NO_MOOSEX_CONTRACT>
400 environment variable. If you are about performance but wish to use some
401 of the features of this module, you might want to enable these features
402 only in your development or testing environment and let things run fast
403 and free in production.
404  
405 =head1 A WORD OF CAUTION
406  
407 This module is by no means a comprehensive approach to DbC. I have
408 very limited experience with this style of programming and wrote this
409 module more as a learning project than anything.
410  
411 =head1 SEE ALSO
412  
413 =over 4
414  
415 =item L<Sub::Contract>
416  
417 =item L<Class::Contract>
418  
419 =back
420  
421 =head1 AUTHOR
422  
423 Brian Phillips, C<< <bphillips at cpan.org> >>
424  
425 =head1 BUGS
426  
427 Please report any bugs or feature requests to C<bug-moosex-contract at rt.cpan.org>, or through
428 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=MooseX-Contract>. I will be notified, and then you'll
429 automatically be notified of progress on your bug as I make changes.
430  
431  
432  
433  
434 =head1 SUPPORT
435  
436 You can find documentation for this module with the perldoc command.
437  
438 perldoc MooseX::Contract
439  
440  
441 You can also look for information at:
442  
443 =over 4
444  
445 =item * RT: CPAN's request tracker
446  
447 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=MooseX-Contract>
448  
449 =item * AnnoCPAN: Annotated CPAN documentation
450  
451 L<http://annocpan.org/dist/MooseX-Contract>
452  
453 =item * CPAN Ratings
454  
455 L<http://cpanratings.perl.org/d/MooseX-Contract>
456  
457 =item * Search CPAN
458  
459 L<http://search.cpan.org/dist/MooseX-Contract/>
460  
461 =back
462  
463  
464 =head1 ACKNOWLEDGEMENTS
465  
466  
467 =head1 COPYRIGHT & LICENSE
468  
469 Copyright 2009 Brian Phillips
470  
471 This program is free software; you can redistribute it and/or modify it
472 under the same terms as Perl itself.
473  
474  
475 =cut
476  
477 5 1; # End of MooseX::Contract
↑ Summary