Modified source files and compiled any and armel versions of packages
[pkg-perl] / deb-src / libtest-exception-perl / libtest-exception-perl-0.27 / lib / Test / Exception.pm
1 use strict;
2 use warnings;
3
4 package Test::Exception;
5 use Test::Builder;
6 use Sub::Uplevel qw( uplevel );
7 use base qw( Exporter );
8 use Carp;
9
10 our $VERSION = '0.27';
11 our @EXPORT = qw(dies_ok lives_ok throws_ok lives_and);
12
13 my $Tester = Test::Builder->new;
14
15 sub import {
16     my $self = shift;
17     if ( @_ ) {
18         my $package = caller;
19         $Tester->exported_to( $package );
20         $Tester->plan( @_ );
21     };
22     $self->export_to_level( 1, $self, $_ ) foreach @EXPORT;
23 }
24
25 =head1 NAME
26
27 Test::Exception - Test exception based code
28
29 =head1 SYNOPSIS
30
31   use Test::More tests => 5;
32   use Test::Exception;
33
34   # or if you don't need Test::More
35
36   use Test::Exception tests => 5;
37
38   # then...
39
40   # Check that the stringified exception matches given regex
41   throws_ok { $foo->method } qr/division by zero/, 'zero caught okay';
42
43   # Check an exception of the given class (or subclass) is thrown
44   throws_ok { $foo->method } 'Error::Simple', 'simple error thrown';
45   
46   # all Test::Exceptions subroutines are guaranteed to preserve the state 
47   # of $@ so you can do things like this after throws_ok and dies_ok
48   like $@, 'what the stringified exception should look like';
49
50   # Check that something died - we do not care why
51   dies_ok { $foo->method } 'expecting to die';
52
53   # Check that something did not die
54   lives_ok { $foo->method } 'expecting to live';
55
56   # Check that a test runs without an exception
57   lives_and { is $foo->method, 42 } 'method is 42';
58   
59   # or if you don't like prototyped functions
60   
61   throws_ok( sub { $foo->method }, qr/division by zero/,
62       'zero caught okay' );
63   throws_ok( sub { $foo->method }, 'Error::Simple', 
64       'simple error thrown' );
65   dies_ok( sub { $foo->method }, 'expecting to die' );
66   lives_ok( sub { $foo->method }, 'expecting to live' );
67   lives_and( sub { is $foo->method, 42 }, 'method is 42' );
68
69
70 =head1 DESCRIPTION
71
72 This module provides a few convenience methods for testing exception based code. It is built with 
73 L<Test::Builder> and plays happily with L<Test::More> and friends.
74
75 If you are not already familiar with L<Test::More> now would be the time to go take a look.
76
77 You can specify the test plan when you C<use Test::Exception> in the same way as C<use Test::More>.
78 See L<Test::More> for details.
79
80 NOTE: Test::Exception only checks for exceptions. It will ignore other methods of stopping 
81 program execution - including exit(). If you have an exit() in evalled code Test::Exception
82 will not catch this with any of its testing functions.
83
84 =cut
85
86 sub _quiet_caller (;$) { ## no critic Prototypes
87     my $height = $_[0];
88     $height++;
89     if( wantarray and !@_ ) {
90         return (CORE::caller($height))[0..2];
91     }
92     else {
93         return CORE::caller($height);
94     }
95 }
96
97 sub _try_as_caller {
98     my $coderef = shift;
99
100     # local works here because Sub::Uplevel has already overridden caller
101     local *CORE::GLOBAL::caller;
102     { no warnings 'redefine'; *CORE::GLOBAL::caller = \&_quiet_caller; }
103
104     eval { uplevel 3, $coderef };
105     return $@;
106 };
107
108
109 sub _is_exception {
110     my $exception = shift;
111     return ref $exception || $exception ne '';
112 };
113
114
115 sub _exception_as_string {
116     my ( $prefix, $exception ) = @_;
117     return "$prefix normal exit" unless _is_exception( $exception );
118     my $class = ref $exception;
119     $exception = "$class ($exception)" 
120             if $class && "$exception" !~ m/^\Q$class/;
121     chomp $exception;
122     return "$prefix $exception";
123 };
124
125
126 =over 4
127
128 =item B<throws_ok>
129
130 Tests to see that a specific exception is thrown. throws_ok() has two forms: 
131
132   throws_ok BLOCK REGEX, TEST_DESCRIPTION
133   throws_ok BLOCK CLASS, TEST_DESCRIPTION
134
135 In the first form the test passes if the stringified exception matches the give regular expression. For example:
136
137     throws_ok { read_file( 'unreadable' ) } qr/No file/, 'no file';
138
139 If your perl does not support C<qr//> you can also pass a regex-like string, for example:
140
141     throws_ok { read_file( 'unreadable' ) } '/No file/', 'no file';
142
143 The second form of throws_ok() test passes if the exception is of the same class as the one supplied, or a subclass of that class. For example:
144
145     throws_ok { $foo->bar } "Error::Simple", 'simple error';
146
147 Will only pass if the C<bar> method throws an Error::Simple exception, or a subclass of an Error::Simple exception.
148
149 You can get the same effect by passing an instance of the exception you want to look for. The following is equivalent to the previous example:
150
151     my $SIMPLE = Error::Simple->new;
152     throws_ok { $foo->bar } $SIMPLE, 'simple error';
153
154 Should a throws_ok() test fail it produces appropriate diagnostic messages. For example:
155
156     not ok 3 - simple error
157     #     Failed test (test.t at line 48)
158     # expecting: Error::Simple exception
159     # found: normal exit
160
161 Like all other Test::Exception functions you can avoid prototypes by passing a subroutine explicitly:
162
163     throws_ok( sub {$foo->bar}, "Error::Simple", 'simple error' );
164
165 A true value is returned if the test succeeds, false otherwise. On exit $@ is guaranteed to be the cause of death (if any).
166
167 A description of the exception being checked is used if no optional test description is passed.
168
169 =cut
170
171
172 sub throws_ok (&$;$) {
173     my ( $coderef, $expecting, $description ) = @_;
174     croak "throws_ok: must pass exception class/object or regex" 
175         unless defined $expecting;
176     $description = _exception_as_string( "threw", $expecting )
177         unless defined $description;
178     my $exception = _try_as_caller( $coderef );
179     my $regex = $Tester->maybe_regex( $expecting );
180     my $ok = $regex 
181         ? ( $exception =~ m/$regex/ ) 
182         : eval { 
183             $exception->isa( ref $expecting ? ref $expecting : $expecting ) 
184         };
185     $Tester->ok( $ok, $description );
186     unless ( $ok ) {
187         $Tester->diag( _exception_as_string( "expecting:", $expecting ) );
188         $Tester->diag( _exception_as_string( "found:", $exception ) );
189     };
190     $@ = $exception;
191     return $ok;
192 };
193
194
195 =item B<dies_ok>
196
197 Checks that a piece of code dies, rather than returning normally. For example:
198
199     sub div {
200         my ( $a, $b ) = @_;
201         return $a / $b;
202     };
203
204     dies_ok { div( 1, 0 ) } 'divide by zero detected';
205
206     # or if you don't like prototypes
207     dies_ok( sub { div( 1, 0 ) }, 'divide by zero detected' );
208
209 A true value is returned if the test succeeds, false otherwise. On exit $@ is guaranteed to be the cause of death (if any).
210
211 Remember: This test will pass if the code dies for any reason. If you care about the reason it might be more sensible to write a more specific test using throws_ok().
212
213 The test description is optional, but recommended. 
214
215 =cut
216
217 sub dies_ok (&;$) {
218     my ( $coderef, $description ) = @_;
219     my $exception = _try_as_caller( $coderef );
220     my $ok = $Tester->ok( _is_exception($exception), $description );
221     $@ = $exception;
222     return $ok;
223 }
224
225
226 =item B<lives_ok>
227
228 Checks that a piece of code doesn't die. This allows your test script to continue, rather than aborting if you get an unexpected exception. For example:
229
230     sub read_file {
231         my $file = shift;
232         local $/;
233         open my $fh, '<', $file or die "open failed ($!)\n";
234         $file = <FILE>;
235         return $file;
236     };
237
238     my $file;
239     lives_ok { $file = read_file('test.txt') } 'file read';
240
241     # or if you don't like prototypes
242     lives_ok( sub { $file = read_file('test.txt') }, 'file read' );
243
244 Should a lives_ok() test fail it produces appropriate diagnostic messages. For example:
245
246     not ok 1 - file read
247     #     Failed test (test.t at line 15)
248     # died: open failed (No such file or directory)
249
250 A true value is returned if the test succeeds, false otherwise. On exit $@ is guaranteed to be the cause of death (if any).
251
252 The test description is optional, but recommended. 
253
254 =cut
255
256 sub lives_ok (&;$) {
257     my ( $coderef, $description ) = @_;
258     my $exception = _try_as_caller( $coderef );
259     my $ok = $Tester->ok( ! _is_exception( $exception ), $description );
260         $Tester->diag( _exception_as_string( "died:", $exception ) ) unless $ok;
261     $@ = $exception;
262     return $ok;
263 }
264
265
266 =item B<lives_and>
267
268 Run a test that may throw an exception. For example, instead of doing:
269
270   my $file;
271   lives_ok { $file = read_file('answer.txt') } 'read_file worked';
272   is $file, "42", 'answer was 42';
273
274 You can use lives_and() like this:
275
276   lives_and { is read_file('answer.txt'), "42" } 'answer is 42';
277   # or if you don't like prototypes
278   lives_and(sub {is read_file('answer.txt'), "42"}, 'answer is 42');
279
280 Which is the same as doing
281
282   is read_file('answer.txt'), "42\n", 'answer is 42';
283
284 unless C<read_file('answer.txt')> dies, in which case you get the same kind of error as lives_ok()
285
286   not ok 1 - answer is 42
287   #     Failed test (test.t at line 15)
288   # died: open failed (No such file or directory)
289
290 A true value is returned if the test succeeds, false otherwise. On exit $@ is guaranteed to be the cause of death (if any).
291
292 The test description is optional, but recommended.
293
294 =cut
295
296 sub lives_and (&;$) {
297     my ( $test, $description ) = @_;
298     {
299         local $Test::Builder::Level = $Test::Builder::Level + 1;
300         my $ok = \&Test::Builder::ok;
301         no warnings;
302         local *Test::Builder::ok = sub {
303             $_[2] = $description unless defined $_[2];
304             $ok->(@_);
305         };
306         use warnings;
307         eval { $test->() } and return 1;
308     };
309     my $exception = $@;
310     if ( _is_exception( $exception ) ) {
311         $Tester->ok( 0, $description );
312         $Tester->diag( _exception_as_string( "died:", $exception ) );
313     };
314     $@ = $exception;
315     return;
316 }
317
318 =back
319
320
321 =head1 SKIPPING TEST::EXCEPTION TESTS
322
323 Sometimes we want to use Test::Exception tests in a test suite, but don't want to force the user to have Test::Exception installed. One way to do this is to skip the tests if Test::Exception is absent. You can do this with code something like this:
324
325   use strict;
326   use warnings;
327   use Test::More;
328   
329   BEGIN {
330       eval "use Test::Exception";
331       plan skip_all => "Test::Exception needed" if $@;
332   }
333   
334   plan tests => 2;
335   # ... tests that need Test::Exception ...
336
337 Note that we load Test::Exception in a C<BEGIN> block ensuring that the subroutine prototypes are in place before the rest of the test script is compiled.
338
339
340 =head1 BUGS
341
342 There are some edge cases in Perl's exception handling where Test::Exception will miss exceptions
343 thrown in DESTROY blocks. See the RT bug L<http://rt.cpan.org/Ticket/Display.html?id=24678> for
344 details, along with the t/edge-cases.t in the distribution test suite. These will be addressed in
345 a future Test::Exception release.
346
347 If you find any more bugs please let me know by e-mail, or report the problem with 
348 L<http://rt.cpan.org/>.
349
350
351 =head1 COMMUNITY
352
353 =over 4
354
355 =item perl-qa
356
357 If you are interested in testing using Perl I recommend you visit L<http://qa.perl.org/> and join the excellent perl-qa mailing list. See L<http://lists.perl.org/showlist.cgi?name=perl-qa> for details on how to subscribe.
358
359 =item perlmonks
360
361 You can find users of Test::Exception, including the module author, on  L<http://www.perlmonks.org/>. Feel free to ask questions on Test::Exception there.
362
363 =item CPAN::Forum
364
365 The CPAN Forum is a web forum for discussing Perl's CPAN modules.   The Test::Exception forum can be found at L<http://www.cpanforum.com/dist/Test-Exception>.
366
367 =item AnnoCPAN
368
369 AnnoCPAN is a web site that allows community annotations of Perl module documentation. The Test::Exception annotations can be found at L<http://annocpan.org/~ADIE/Test-Exception/>.
370
371 =back
372
373
374 =head1 TO DO
375
376 If you think this module should do something that it doesn't (or does something that it shouldn't) please let me know.
377
378 You can see my current to do list at L<http://adrianh.tadalist.com/lists/public/15421>, with an RSS feed of changes at L<http://adrianh.tadalist.com/lists/feed_public/15421>.
379
380
381 =head1 ACKNOWLEDGMENTS
382
383 Thanks to chromatic and Michael G Schwern for the excellent Test::Builder, without which this module wouldn't be possible.
384
385 Thanks to 
386 Adam Kennedy,
387 Andy Lester, 
388 Aristotle Pagaltzis, 
389 Ben Prew, 
390 Cees Hek,
391 Chris Dolan,
392 chromatic, 
393 Curt Sampson,
394 David Cantrell,
395 David Golden, 
396 David Wheeler, 
397 Janek Schleicher,
398 Jim Keenan, 
399 Jos I. Boumans, 
400 Joshua ben Jore,
401 Jost Krieger,
402 Mark Fowler, 
403 Michael G Schwern, 
404 Nadim Khemir,
405 Paul McCann,
406 Perrin Harkins, 
407 Peter Scott, 
408 Rob Muhlestein 
409 Scott R. Godin,
410 Steve Purkis,
411 Steve, 
412 Tim Bunce,
413 and various anonymous folk for comments, suggestions, bug reports and patches.
414
415
416 =head1 AUTHOR
417
418 Adrian Howard <adrianh@quietstars.com>
419
420 If you can spare the time, please drop me a line if you find this module useful.
421
422
423 =head1 SEE ALSO
424
425 =over 4
426
427 =item L<http://del.icio.us/tag/Test::Exception>
428
429 Delicious links on Test::Exception.
430
431 =item L<Test::Warn> & L<Test::NoWarnings>
432
433 Modules to help test warnings.
434
435 =item L<Test::Builder>
436
437 Support module for building test libraries.
438
439 =item L<Test::Simple> & L<Test::More>
440
441 Basic utilities for writing tests.
442
443 =item L<http://qa.perl.org/test-modules.html>
444
445 Overview of some of the many testing modules available on CPAN.
446
447 =item L<http://del.icio.us/tag/perl+testing>
448
449 Delicious links on perl testing.
450
451 =back
452
453
454 =head1 LICENCE
455
456 Copyright 2002-2007 Adrian Howard, All Rights Reserved.
457
458 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
459
460 =cut
461
462 1;