File Coverage

blib/lib/Carp/Assert.pm
Criterion Covered Total %
statement 82 83 98.8
branch 17 20 85.0
condition 3 3 100.0
subroutine 15 16 93.7
pod 4 6 66.6
total 121 128 94.5


line stmt bran cond sub pod time code
1             package Carp::Assert;
2              
3             require 5.006;
4 4     3   141452 use strict qw(subs vars);
  3         16  
  3         102  
5 4     3   84 use warnings;
  4         15  
  4         91  
6 4     3   36 use Exporter;
  4         7  
  4         120  
7              
8 4     3   22 use vars qw(@ISA $VERSION %EXPORT_TAGS);
  4         7  
  4         524  
9              
10             BEGIN {
11 4     3   21 $VERSION = '0.22';
12              
13 4         53 @ISA = qw(Exporter);
14              
15 4         496 %EXPORT_TAGS = (
16             NDEBUG => [qw(assert affirm should shouldnt DEBUG)],
17             );
18 4         16 $EXPORT_TAGS{DEBUG} = $EXPORT_TAGS{NDEBUG};
19 4         2993 Exporter::export_tags(qw(NDEBUG DEBUG));
20             }
21              
22             # constant.pm, alas, adds too much load time (yes, I benchmarked it)
23             sub REAL_DEBUG () { 1 } # CONSTANT
24             sub NDEBUG () { 0 } # CONSTANT
25              
26             # Export the proper DEBUG flag according to if :NDEBUG is set.
27             # Also export noop versions of our routines if NDEBUG
28 12     11 0 8586 sub noop { undef }
29 2     0 0 3 sub noop_affirm (&;$) { undef };
30              
31             sub import {
32             my $env_ndebug = exists $ENV{PERL_NDEBUG} ? $ENV{PERL_NDEBUG}
33 11 100   9   3745 : $ENV{'NDEBUG'};
34 10 100 100     71 if( grep(/^:NDEBUG$/, @_) or $env_ndebug ) {
35 8         19 my $caller = caller;
36 8         13 foreach my $func (grep !/^DEBUG$/, @{$EXPORT_TAGS{'NDEBUG'}}) {
  8         312  
37 29 100       59 if( $func eq 'affirm' ) {
38 8         11 *{$caller.'::'.$func} = \&noop_affirm;
  8         32  
39             } else {
40 22         28 *{$caller.'::'.$func} = \&noop;
  22         62  
41             }
42             }
43 8         16 *{$caller.'::DEBUG'} = \&NDEBUG;
  8         3866  
44             }
45             else {
46 3         325 *DEBUG = *REAL_DEBUG;
47 3         10 Carp::Assert->_export_to_level(1, @_);
48             }
49             }
50              
51              
52             # 5.004's Exporter doesn't have export_to_level.
53             sub _export_to_level
54             {
55 2     2   4 my $pkg = shift;
56 3         292 my $level = shift;
57 3         6 (undef) = shift; # XXX redundant arg
58 3         5 my $callpkg = caller($level);
59 3         1864 $pkg->export($callpkg, @_);
60             }
61              
62              
63             sub unimport {
64 3     2   1174 *DEBUG = *NDEBUG;
65 3         8 push @_, ':NDEBUG';
66 3         9 goto &import;
67             }
68              
69              
70             # Can't call confess() here or the stack trace will be wrong.
71             sub _fail_msg {
72 10     9   28 my($name) = shift;
73 10         314 my $msg = 'Assertion';
74 10 100       316 $msg .= " ($name)" if defined $name;
75 10         30 $msg .= " failed!\n";
76 10         1454 return $msg;
77             }
78              
79              
80             =head1 NAME
81              
82             Carp::Assert - executable comments
83              
84             =head1 SYNOPSIS
85              
86             # Assertions are on.
87             use Carp::Assert;
88              
89             $next_sunrise_time = sunrise();
90              
91             # Assert that the sun must rise in the next 24 hours.
92             assert(($next_sunrise_time - time) < 24*60*60) if DEBUG;
93              
94             # Assert that your customer's primary credit card is active
95             affirm {
96             my @cards = @{$customer->credit_cards};
97             $cards[0]->is_active;
98             };
99              
100              
101             # Assertions are off.
102             no Carp::Assert;
103              
104             $next_pres = divine_next_president();
105              
106             # Assert that if you predict Dan Quayle will be the next president
107             # your crystal ball might need some polishing. However, since
108             # assertions are off, IT COULD HAPPEN!
109             shouldnt($next_pres, 'Dan Quayle') if DEBUG;
110              
111              
112             =head1 DESCRIPTION
113              
114             =begin testing
115              
116             BEGIN {
117 2     1   69027 local %ENV = %ENV;
118 2         24 delete @ENV{qw(PERL_NDEBUG NDEBUG)};
119 2         820 require Carp::Assert;
120 2         8 Carp::Assert->import;
121             }
122              
123             local %ENV = %ENV;
124             delete @ENV{qw(PERL_NDEBUG NDEBUG)};
125              
126             =end testing
127              
128             "We are ready for any unforseen event that may or may not
129             occur."
130             - Dan Quayle
131              
132             Carp::Assert is intended for a purpose like the ANSI C library
133             L.
134             If you're already familiar with assert.h, then you can
135             probably skip this and go straight to the FUNCTIONS section.
136              
137             Assertions are the explicit expressions of your assumptions about the
138             reality your program is expected to deal with, and a declaration of
139             those which it is not. They are used to prevent your program from
140             blissfully processing garbage inputs (garbage in, garbage out becomes
141             garbage in, error out) and to tell you when you've produced garbage
142             output. (If I was going to be a cynic about Perl and the user nature,
143             I'd say there are no user inputs but garbage, and Perl produces
144             nothing but...)
145              
146             An assertion is used to prevent the impossible from being asked of
147             your code, or at least tell you when it does. For example:
148              
149             =for example begin
150              
151             # Take the square root of a number.
152             sub my_sqrt {
153 1         1 my($num) = shift;
  1         2  
154              
155             # the square root of a negative number is imaginary.
156 1         1 assert($num >= 0);
  1         117  
157              
158 1         2 return sqrt $num;
  1         15  
159             }
160              
161             =for example end
162              
163             =for example_testing
164             is( my_sqrt(4), 2, 'my_sqrt example with good input' );
165             ok( !eval{ my_sqrt(-1); 1 }, ' and pukes on bad' );
166              
167             The assertion will warn you if a negative number was handed to your
168             subroutine, a reality the routine has no intention of dealing with.
169              
170             An assertion should also be used as something of a reality check, to
171             make sure what your code just did really did happen:
172              
173             open(FILE, $filename) || die $!;
174             @stuff = ;
175             @stuff = do_something(@stuff);
176              
177             # I should have some stuff.
178             assert(@stuff > 0);
179              
180             The assertion makes sure you have some @stuff at the end. Maybe the
181             file was empty, maybe do_something() returned an empty list... either
182             way, the assert() will give you a clue as to where the problem lies,
183             rather than 50 lines down at when you wonder why your program isn't
184             printing anything.
185              
186             Since assertions are designed for debugging and will remove themelves
187             from production code, your assertions should be carefully crafted so
188             as to not have any side-effects, change any variables, or otherwise
189             have any effect on your program. Here is an example of a bad
190             assertation:
191              
192             assert($error = 1 if $king ne 'Henry'); # Bad!
193              
194             It sets an error flag which may then be used somewhere else in your
195             program. When you shut off your assertions with the $DEBUG flag,
196             $error will no longer be set.
197              
198             Here's another example of B use:
199              
200             assert($next_pres ne 'Dan Quayle' or goto Canada); # Bad!
201              
202             This assertion has the side effect of moving to Canada should it fail.
203             This is a very bad assertion since error handling should not be
204             placed in an assertion, nor should it have side-effects.
205              
206             In short, an assertion is an executable comment. For instance, instead
207             of writing this
208              
209             # $life ends with a '!'
210             $life = begin_life();
211              
212             you'd replace the comment with an assertion which B the comment.
213              
214             $life = begin_life();
215             assert( $life =~ /!$/ );
216              
217             =for testing
218             my $life = 'Whimper!';
219             ok( eval { assert( $life =~ /!$/ ); 1 }, 'life ends with a bang' );
220              
221              
222             =head1 FUNCTIONS
223              
224             =over 4
225              
226             =item B
227              
228             assert(EXPR) if DEBUG;
229             assert(EXPR, $name) if DEBUG;
230              
231             assert's functionality is effected by compile time value of the DEBUG
232             constant, controlled by saying C or C
233             Carp::Assert>. In the former case, assert will function as below.
234             Otherwise, the assert function will compile itself out of the program.
235             See L for details.
236              
237             =for testing
238             {
239             package Some::Other;
240 0         0 no Carp::Assert;
  1         284  
  1         3  
241             ::ok( eval { assert(0) if DEBUG; 1 } );
242             }
243              
244             Give assert an expression, assert will Carp::confess() if that
245             expression is false, otherwise it does nothing. (DO NOT use the
246             return value of assert for anything, I mean it... really!).
247              
248             =for testing
249             ok( eval { assert(1); 1 } );
250             ok( !eval { assert(0); 1 } );
251              
252             The error from assert will look something like this:
253              
254             Assertion failed!
255             Carp::Assert::assert(0) called at prog line 23
256             main::foo called at prog line 50
257              
258             =for testing
259             eval { assert(0) };
260             like( $@, '/^Assertion failed!/', 'error format' );
261             like( $@, '/Carp::Assert::assert\(0\) called at/', ' with stack trace' );
262              
263             Indicating that in the file "prog" an assert failed inside the
264             function main::foo() on line 23 and that foo() was in turn called from
265             line 50 in the same file.
266              
267             If given a $name, assert() will incorporate this into your error message,
268             giving users something of a better idea what's going on.
269              
270             assert( Dogs->isa('People'), 'Dogs are people, too!' ) if DEBUG;
271             # Result - "Assertion (Dogs are people, too!) failed!"
272              
273             =for testing
274             eval { assert( Dogs->isa('People'), 'Dogs are people, too!' ); };
275             like( $@, '/^Assertion \(Dogs are people, too!\) failed!/', 'names' );
276              
277             =cut
278              
279             sub assert ($;$) {
280 13 100   12 1 1423 unless($_[0]) {
281 9         42 require Carp;
282 8         23 Carp::confess( _fail_msg($_[1]) );
283             }
284 5         15 return undef;
285             }
286              
287              
288             =item B
289              
290             affirm BLOCK if DEBUG;
291             affirm BLOCK $name if DEBUG;
292              
293             Very similar to assert(), but instead of taking just a simple
294             expression it takes an entire block of code and evaluates it to make
295             sure its true. This can allow more complicated assertions than
296             assert() can without letting the debugging code leak out into
297             production and without having to smash together several
298             statements into one.
299              
300             =for example begin
301              
302             affirm {
303             my $customer = Customer->new($customerid);
304             my @cards = $customer->credit_cards;
305             grep { $_->is_active } @cards;
306             } "Our customer has an active credit card";
307              
308             =for example end
309              
310             =for testing
311             my $foo = 1; my $bar = 2;
312             eval { affirm { $foo == $bar } };
313             like( $@, '/\$foo == \$bar/' );
314              
315              
316             affirm() also has the nice side effect that if you forgot the C
317             suffix its arguments will not be evaluated at all. This can be nice
318             if you stick affirm()s with expensive checks into hot loops and other
319             time-sensitive parts of your program.
320              
321             If the $name is left off and your Perl version is 5.6 or higher the
322             affirm() diagnostics will include the code begin affirmed.
323              
324             =cut
325              
326             sub affirm (&;$) {
327 2 50   2 1 7 unless( eval { &{$_[0]}; } ) {
  2         293  
  2         5  
328 2         4 my $name = $_[1];
329              
330 2 50       6 if( !defined $name ) {
331 2         2 eval {
332 2         8 require B::Deparse;
333 2         928 $name = B::Deparse->new->coderef2text($_[0]);
334             };
335 2 50       14 $name =
336             'code display non-functional on this version of Perl, sorry'
337             if $@;
338             }
339              
340 2         14 require Carp;
341 2         18 Carp::confess( _fail_msg($name) );
342             }
343 1         52 return undef;
344             }
345              
346             =item B
347              
348             =item B
349              
350             should ($this, $shouldbe) if DEBUG;
351             shouldnt($this, $shouldntbe) if DEBUG;
352              
353             Similar to assert(), it is specially for simple "this should be that"
354             or "this should be anything but that" style of assertions.
355              
356             Due to Perl's lack of a good macro system, assert() can only report
357             where something failed, but it can't report I failed or I.
358             should() and shouldnt() can produce more informative error messages:
359              
360             Assertion ('this' should be 'that'!) failed!
361             Carp::Assert::should('this', 'that') called at moof line 29
362             main::foo() called at moof line 58
363              
364             So this:
365              
366             should($this, $that) if DEBUG;
367              
368             is similar to this:
369              
370             assert($this eq $that) if DEBUG;
371              
372             except for the better error message.
373              
374             Currently, should() and shouldnt() can only do simple eq and ne tests
375             (respectively). Future versions may allow regexes.
376              
377             =cut
378              
379             sub should ($$) {
380 3 100   2 1 1401 unless($_[0] eq $_[1]) {
381 2         19 require Carp;
382 2         14 &Carp::confess( _fail_msg("'$_[0]' should be '$_[1]'!") );
383             }
384 2         4 return undef;
385             }
386              
387             sub shouldnt ($$) {
388 3 100   2 1 1206 unless($_[0] ne $_[1]) {
389 2         11 require Carp;
390 2         328 &Carp::confess( _fail_msg("'$_[0]' shouldn't be that!") );
391             }
392 2         4 return undef;
393             }
394              
395             =back
396              
397             =head1 Debugging vs Production
398              
399             Because assertions are extra code and because it is sometimes necessary to
400             place them in 'hot' portions of your code where speed is paramount,
401             Carp::Assert provides the option to remove its assert() calls from your
402             program.
403              
404             So, we provide a way to force Perl to inline the switched off assert()
405             routine, thereby removing almost all performance impact on your production
406             code.
407              
408             no Carp::Assert; # assertions are off.
409             assert(1==1) if DEBUG;
410              
411             DEBUG is a constant set to 0. Adding the 'if DEBUG' condition on your
412             assert() call gives perl the cue to go ahead and remove assert() call from
413             your program entirely, since the if conditional will always be false.
414              
415             # With C the assert() has no impact.
416             for (1..100) {
417             assert( do_some_really_time_consuming_check ) if DEBUG;
418             }
419              
420             If C gets too annoying, you can always use affirm().
421              
422             # Once again, affirm() has (almost) no impact with C
423             for (1..100) {
424             affirm { do_some_really_time_consuming_check };
425             }
426              
427             Another way to switch off all asserts, system wide, is to define the
428             NDEBUG or the PERL_NDEBUG environment variable.
429              
430             You can safely leave out the "if DEBUG" part, but then your assert()
431             function will always execute (and its arguments evaluated and time
432             spent). To get around this, use affirm(). You still have the
433             overhead of calling a function but at least its arguments will not be
434             evaluated.
435              
436              
437             =head1 Differences from ANSI C
438              
439             assert() is intended to act like the function from ANSI C fame.
440             Unfortunately, due to Perl's lack of macros or strong inlining, it's not
441             nearly as unobtrusive.
442              
443             Well, the obvious one is the "if DEBUG" part. This is cleanest way I could
444             think of to cause each assert() call and its arguments to be removed from
445             the program at compile-time, like the ANSI C macro does.
446              
447             Also, this version of assert does not report the statement which
448             failed, just the line number and call frame via Carp::confess. You
449             can't do C because $a and $b will probably be
450             lexical, and thus unavailable to assert(). But with Perl, unlike C,
451             you always have the source to look through, so the need isn't as
452             great.
453              
454              
455             =head1 EFFICIENCY
456              
457             With C (or NDEBUG) and using the C suffixes
458             on all your assertions, Carp::Assert has almost no impact on your
459             production code. I say almost because it does still add some load-time
460             to your code (I've tried to reduce this as much as possible).
461              
462             If you forget the C on an C, C or
463             C, its arguments are still evaluated and thus will impact
464             your code. You'll also have the extra overhead of calling a
465             subroutine (even if that subroutine does nothing).
466              
467             Forgetting the C on an C is not so bad. While you
468             still have the overhead of calling a subroutine (one that does
469             nothing) it will B evaluate its code block and that can save
470             a lot.
471              
472             Try to remember the B.
473              
474              
475             =head1 ENVIRONMENT
476              
477             =over 4
478              
479             =item NDEBUG
480              
481             Defining NDEBUG switches off all assertions. It has the same effect
482             as changing "use Carp::Assert" to "no Carp::Assert" but it effects all
483             code.
484              
485             =item PERL_NDEBUG
486              
487             Same as NDEBUG and will override it. Its provided to give you
488             something which won't conflict with any C programs you might be
489             working on at the same time.
490              
491             =back
492              
493              
494             =head1 BUGS, CAVETS and other MUSINGS
495              
496             =head2 Conflicts with C
497              
498             The C module exports an C routine which will conflict with C if both are used in the same namespace. If you are using both together, prevent C from exporting like so:
499              
500             use POSIX ();
501             use Carp::Assert;
502              
503             Since C exports way too much, you should be using it like that anyway.
504              
505             =head2 C and C<$^S>
506              
507             affirm() mucks with the expression's caller and it is run in an eval
508             so anything that checks $^S will be wrong.
509              
510             =head2 missing C
511              
512             It would be nice if we could warn about missing C.
513              
514              
515             =head1 SEE ALSO
516              
517             L - the wikipedia
518             page about C.
519              
520             L provides a set of convenience functions
521             that are wrappers around C.
522              
523             L provides support for subroutine pre- and post-conditions.
524             The documentation says it's slow.
525              
526             L provides compile-time assertions, which are usually
527             optimised away at compile time. Currently part of the L
528             distribution, but may get its own distribution sometime in 2014.
529              
530             L also provides an C function, for Perl >= 5.8.1.
531              
532             L provides an assertion mechanism for Perl >= 5.9.0.
533              
534             =head1 REPOSITORY
535              
536             L
537              
538             =head1 COPYRIGHT
539              
540             Copyright 2001-2007 by Michael G Schwern Eschwern@pobox.comE.
541              
542             This program is free software; you can redistribute it and/or
543             modify it under the same terms as Perl itself.
544              
545             See F
546              
547              
548             =head1 AUTHOR
549              
550             Michael G Schwern
551              
552             =cut
553              
554             return q|You don't just EAT the largest turnip in the world!|;