File Coverage

File:local/lib/perl5/Test/Exception.pm
Coverage:23.4%

linestmtbrancondsubtimecode
1
6
6
6
11
5
88
use strict;
2
6
6
6
7
5
75
use warnings;
3
4package Test::Exception;
5
6
6
6
9
4
56
use Test::Builder;
6
6
6
6
738
6
13
use Sub::Uplevel qw( uplevel );
7
6
6
6
16
5
1021
use base qw( Exporter );
8
9our $VERSION = '0.32';
10our @EXPORT = qw(dies_ok lives_ok throws_ok lives_and);
11
12my $Tester = Test::Builder->new;
13
14sub import {
15
6
5
    my $self = shift;
16
6
12
    if ( @_ ) {
17
0
0
        my $package = caller;
18
0
0
        $Tester->exported_to( $package );
19
0
0
        $Tester->plan( @_ );
20    };
21
6
641
    $self->export_to_level( 1, $self, $_ ) foreach @EXPORT;
22}
23
24 - 83
=head1 NAME

Test::Exception - Test exception based code

=head1 SYNOPSIS

  use Test::More tests => 5;
  use Test::Exception;

  # or if you don't need Test::More

  use Test::Exception tests => 5;

  # then...

  # Check that the stringified exception matches given regex
  throws_ok { $foo->method } qr/division by zero/, 'zero caught okay';

  # Check an exception of the given class (or subclass) is thrown
  throws_ok { $foo->method } 'Error::Simple', 'simple error thrown';
  
  # all Test::Exceptions subroutines are guaranteed to preserve the state 
  # of $@ so you can do things like this after throws_ok and dies_ok
  like $@, 'what the stringified exception should look like';

  # Check that something died - we do not care why
  dies_ok { $foo->method } 'expecting to die';

  # Check that something did not die
  lives_ok { $foo->method } 'expecting to live';

  # Check that a test runs without an exception
  lives_and { is $foo->method, 42 } 'method is 42';
  
  # or if you don't like prototyped functions
  
  throws_ok( sub { $foo->method }, qr/division by zero/,
      'zero caught okay' );
  throws_ok( sub { $foo->method }, 'Error::Simple', 
      'simple error thrown' );
  dies_ok( sub { $foo->method }, 'expecting to die' );
  lives_ok( sub { $foo->method }, 'expecting to live' );
  lives_and( sub { is $foo->method, 42 }, 'method is 42' );


=head1 DESCRIPTION

This module provides a few convenience methods for testing exception based code. It is built with 
L<Test::Builder> and plays happily with L<Test::More> and friends.

If you are not already familiar with L<Test::More> now would be the time to go take a look.

You can specify the test plan when you C<use Test::Exception> in the same way as C<use Test::More>.
See L<Test::More> for details.

NOTE: Test::Exception only checks for exceptions. It will ignore other methods of stopping 
program execution - including exit(). If you have an exit() in evalled code Test::Exception
will not catch this with any of its testing functions.

=cut
84
85sub _quiet_caller (;$) { ## no critic Prototypes
86
0
    my $height = $_[0];
87
0
    $height++;
88
89
0
    if ( CORE::caller() eq 'DB' ) {
90        # passthrough the @DB::args trick
91        package DB;
92
0
        if( wantarray ) {
93
0
            if ( !@_ ) {
94
0
                return (CORE::caller($height))[0..2];
95            }
96            else {
97                # If we got here, we are within a Test::Exception test, and
98                # something is producing a stacktrace. In case this is a full
99                # trace (i.e. confess() ), we have to make sure that the sub
100                # args are not visible. If we do not do this, and the test in
101                # question is throws_ok() with a regex, it will end up matching
102                # against itself in the args to throws_ok().
103                #
104                # While it is possible (and maybe wise), to test if we are
105                # indeed running under throws_ok (by crawling the stack right
106                # up from here), the old behavior of Test::Exception was to
107                # simply obliterate @DB::args altogether in _quiet_caller, so
108                # we are just preserving the behavior to avoid surprises
109                #
110
0
                my @frame_info = CORE::caller($height);
111
0
                @DB::args = ();
112
0
                return @frame_info;
113            }
114        }
115
116        # fallback if nothing above returns
117
0
        return CORE::caller($height);
118    }
119    else {
120
0
        if( wantarray and !@_ ) {
121
0
            return (CORE::caller($height))[0..2];
122        }
123        else {
124
0
            return CORE::caller($height);
125        }
126    }
127}
128
129sub _try_as_caller {
130
0
    my $coderef = shift;
131
132    # local works here because Sub::Uplevel has already overridden caller
133
0
    local *CORE::GLOBAL::caller;
134
6
6
6
0
0
17
5
1471
    { no warnings 'redefine'; *CORE::GLOBAL::caller = \&_quiet_caller; }
135
136
0
0
    eval { uplevel 3, $coderef };
137
0
    return $@;
138};
139
140
141sub _is_exception {
142
0
    my $exception = shift;
143
0
    return ref $exception || $exception ne '';
144};
145
146
147sub _exception_as_string {
148
0
    my ( $prefix, $exception ) = @_;
149
0
    return "$prefix normal exit" unless _is_exception( $exception );
150
0
    my $class = ref $exception;
151
0
    $exception = "$class ($exception)"
152            if $class && "$exception" !~ m/^\Q$class/;
153
0
    chomp $exception;
154
0
    return "$prefix $exception";
155};
156
157
158 - 206
=over 4

=item B<throws_ok>

Tests to see that a specific exception is thrown. throws_ok() has two forms: 

  throws_ok BLOCK REGEX, TEST_DESCRIPTION
  throws_ok BLOCK CLASS, TEST_DESCRIPTION

In the first form the test passes if the stringified exception matches the give regular expression. For example:

    throws_ok { read_file( 'unreadable' ) } qr/No file/, 'no file';

If your perl does not support C<qr//> you can also pass a regex-like string, for example:

    throws_ok { read_file( 'unreadable' ) } '/No file/', 'no file';

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:

    throws_ok { $foo->bar } "Error::Simple", 'simple error';

Will only pass if the C<bar> method throws an Error::Simple exception, or a subclass of an Error::Simple exception.

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:

    my $SIMPLE = Error::Simple->new;
    throws_ok { $foo->bar } $SIMPLE, 'simple error';

Should a throws_ok() test fail it produces appropriate diagnostic messages. For example:

    not ok 3 - simple error
    #     Failed test (test.t at line 48)
    # expecting: Error::Simple exception
    # found: normal exit

Like all other Test::Exception functions you can avoid prototypes by passing a subroutine explicitly:

    throws_ok( sub {$foo->bar}, "Error::Simple", 'simple error' );

A true value is returned if the test succeeds, false otherwise. On exit $@ is guaranteed to be the cause of death (if any).

A description of the exception being checked is used if no optional test description is passed.

NOTE: Rememeber when you C<die $string_without_a_trailing_newline> perl will 
automatically add the current script line number, input line number and a newline. This will
form part of the string that throws_ok regular expressions match against.


=cut
207
208
209sub throws_ok (&$;$) {
210
0
    my ( $coderef, $expecting, $description ) = @_;
211
0
    unless (defined $expecting) {
212
0
      require Carp;
213
0
      Carp::croak( "throws_ok: must pass exception class/object or regex" );
214    }
215
0
    $description = _exception_as_string( "threw", $expecting )
216        unless defined $description;
217
0
    my $exception = _try_as_caller( $coderef );
218
0
    my $regex = $Tester->maybe_regex( $expecting );
219    my $ok = $regex
220        ? ( $exception =~ m/$regex/ )
221
0
        : eval {
222
0
            $exception->isa( ref $expecting ? ref $expecting : $expecting )
223        };
224
0
    $Tester->ok( $ok, $description );
225
0
    unless ( $ok ) {
226
0
        $Tester->diag( _exception_as_string( "expecting:", $expecting ) );
227
0
        $Tester->diag( _exception_as_string( "found:", $exception ) );
228    };
229
0
    $@ = $exception;
230
0
    return $ok;
231};
232
233
234 - 254
=item B<dies_ok>

Checks that a piece of code dies, rather than returning normally. For example:

    sub div {
        my ( $a, $b ) = @_;
        return $a / $b;
    };

    dies_ok { div( 1, 0 ) } 'divide by zero detected';

    # or if you don't like prototypes
    dies_ok( sub { div( 1, 0 ) }, 'divide by zero detected' );

A true value is returned if the test succeeds, false otherwise. On exit $@ is guaranteed to be the cause of death (if any).

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().

The test description is optional, but recommended. 

=cut
255
256sub dies_ok (&;$) {
257
0
    my ( $coderef, $description ) = @_;
258
0
    my $exception = _try_as_caller( $coderef );
259
0
    my $ok = $Tester->ok( _is_exception($exception), $description );
260
0
    $@ = $exception;
261
0
    return $ok;
262}
263
264
265 - 293
=item B<lives_ok>

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:

    sub read_file {
        my $file = shift;
        local $/;
        open my $fh, '<', $file or die "open failed ($!)\n";
        $file = <FILE>;
        return $file;
    };

    my $file;
    lives_ok { $file = read_file('test.txt') } 'file read';

    # or if you don't like prototypes
    lives_ok( sub { $file = read_file('test.txt') }, 'file read' );

Should a lives_ok() test fail it produces appropriate diagnostic messages. For example:

    not ok 1 - file read
    #     Failed test (test.t at line 15)
    # died: open failed (No such file or directory)

A true value is returned if the test succeeds, false otherwise. On exit $@ is guaranteed to be the cause of death (if any).

The test description is optional, but recommended. 

=cut
294
295sub lives_ok (&;$) {
296
0
    my ( $coderef, $description ) = @_;
297
0
    my $exception = _try_as_caller( $coderef );
298
0
    my $ok = $Tester->ok( ! _is_exception( $exception ), $description );
299
0
        $Tester->diag( _exception_as_string( "died:", $exception ) ) unless $ok;
300
0
    $@ = $exception;
301
0
    return $ok;
302}
303
304
305 - 333
=item B<lives_and>

Run a test that may throw an exception. For example, instead of doing:

  my $file;
  lives_ok { $file = read_file('answer.txt') } 'read_file worked';
  is $file, "42", 'answer was 42';

You can use lives_and() like this:

  lives_and { is read_file('answer.txt'), "42" } 'answer is 42';
  # or if you don't like prototypes
  lives_and(sub {is read_file('answer.txt'), "42"}, 'answer is 42');

Which is the same as doing

  is read_file('answer.txt'), "42\n", 'answer is 42';

unless C<read_file('answer.txt')> dies, in which case you get the same kind of error as lives_ok()

  not ok 1 - answer is 42
  #     Failed test (test.t at line 15)
  # died: open failed (No such file or directory)

A true value is returned if the test succeeds, false otherwise. On exit $@ is guaranteed to be the cause of death (if any).

The test description is optional, but recommended.

=cut
334
335sub lives_and (&;$) {
336
0
    my ( $test, $description ) = @_;
337    {
338
0
0
        local $Test::Builder::Level = $Test::Builder::Level + 1;
339
0
        my $ok = \&Test::Builder::ok;
340
6
6
6
15
4
204
        no warnings;
341        local *Test::Builder::ok = sub {
342
0
            $_[2] = $description unless defined $_[2];
343
0
            $ok->(@_);
344
0
        };
345
6
6
6
13
7
336
        use warnings;
346
0
0
        eval { $test->() } and return 1;
347    };
348
0
    my $exception = $@;
349
0
    if ( _is_exception( $exception ) ) {
350
0
        $Tester->ok( 0, $description );
351
0
        $Tester->diag( _exception_as_string( "died:", $exception ) );
352    };
353
0
    $@ = $exception;
354
0
    return;
355}
356
357=back
358
359
360 - 502
=head1 SKIPPING TEST::EXCEPTION TESTS

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:

  use strict;
  use warnings;
  use Test::More;
  
  BEGIN {
      eval "use Test::Exception";
      plan skip_all => "Test::Exception needed" if $@;
  }
  
  plan tests => 2;
  # ... tests that need Test::Exception ...

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.


=head1 BUGS

There are some edge cases in Perl's exception handling where Test::Exception will miss exceptions
thrown in DESTROY blocks. See the RT bug L<http://rt.cpan.org/Ticket/Display.html?id=24678> for
details, along with the t/edge-cases.t in the distribution test suite. These will be addressed in
a future Test::Exception release.

If you find any more bugs please let me know by e-mail, or report the problem with 
L<http://rt.cpan.org/>.


=head1 COMMUNITY

=over 4

=item perl-qa

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.

=item perlmonks

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.

=item CPAN::Forum

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>.

=item AnnoCPAN

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/>.

=back


=head1 TO DO

If you think this module should do something that it doesn't (or does something that it shouldn't) please let me know.

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>.


=head1 ACKNOWLEDGMENTS

Thanks to chromatic and Michael G Schwern for the excellent Test::Builder, without which this module wouldn't be possible.

Thanks to 
Adam Kennedy,
Andy Lester, 
Aristotle Pagaltzis, 
Ben Prew, 
Cees Hek,
Chris Dolan,
chromatic, 
Curt Sampson,
David Cantrell,
David Golden, 
David Tulloh,
David Wheeler, 
J. K. O'Brien,
Janek Schleicher,
Jim Keenan, 
Jos I. Boumans, 
Joshua ben Jore,
Jost Krieger,
Mark Fowler, 
Michael G Schwern, 
Nadim Khemir,
Paul McCann,
Perrin Harkins, 
Peter Rabbitson,
Peter Scott, 
Ricardo Signes,
Rob Muhlestein,
Scott R. Godin,
Steve Purkis,
Steve, 
Tim Bunce,
and various anonymous folk for comments, suggestions, bug reports and patches.

=head1 AUTHOR

Adrian Howard <adrianh@quietstars.com>

If you can spare the time, please drop me a line if you find this module useful.


=head1 SEE ALSO

=over 4

=item L<http://del.icio.us/tag/Test::Exception>

Delicious links on Test::Exception.

=item L<Test::Warn> & L<Test::NoWarnings>

Modules to help test warnings.

=item L<Test::Builder>

Support module for building test libraries.

=item L<Test::Simple> & L<Test::More>

Basic utilities for writing tests.

=item L<http://qa.perl.org/test-modules.html>

Overview of some of the many testing modules available on CPAN.

=item L<http://del.icio.us/tag/perl+testing>

Delicious links on perl testing.

=back


=head1 LICENCE

Copyright 2002-2007 Adrian Howard, All Rights Reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

=cut
503
5041;