File Coverage

File:local/lib/perl5/Test/Warn.pm
Coverage:11.9%

linestmtbrancondsubtimecode
1 - 241
=head1 NAME

Test::Warn - Perl extension to test methods for warnings

=head1 SYNOPSIS

  use Test::Warn;

  warning_is    {foo(-dri => "/")} "Unknown Parameter 'dri'", "dri != dir gives warning";
  warnings_are  {bar(1,1)} ["Width very small", "Height very small"];

  warning_is    {add(2,2)} undef, "No warnings for calc 2+2"; # or
  warnings_are  {add(2,2)} [],    "No warnings for calc 2+2"; # what reads better :-)

  warning_like  {foo(-dri => "/")} qr/unknown param/i, "an unknown parameter test";
  warnings_like {bar(1,1)} [qr/width.*small/i, qr/height.*small/i];

  warning_is    {foo()} {carped => "didn't find the right parameters"};
  warnings_like {foo()} [qr/undefined/,qr/undefined/,{carped => qr/no result/i}];

  warning_like {foo(undef)}                 'uninitialized';
  warning_like {bar(file => '/etc/passwd')} 'io';

  warning_like {eval q/"$x"; $x;/} 
               [qw/void uninitialized/], 
               "some warnings at compile time";

  warnings_exist {...} [qr/expected warning/], "Expected warning is thrown";

=head1 DESCRIPTION

A good style of Perl programming calls for a lot of diverse regression tests.

This module provides a few convenience methods for testing warning based code.

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

=head2 FUNCTIONS

=over 4

=item warning_is BLOCK STRING, TEST_NAME

Tests that BLOCK gives the specified warning exactly once.
The test fails if the BLOCK warns more than once or does not warn at all.
If the string is undef, 
then the tests succeeds if the BLOCK doesn't give any warning.
Another way to say that there are no warnings in the block
is C<warnings_are {foo()} [], "no warnings">.

If you want to test for a warning given by Carp,
you have to write something like:
C<warning_is {carp "msg"} {carped =E<gt> 'msg'}, "Test for a carped warning">.
The test will fail if a "normal" warning is found instead of a "carped" one.

Note: C<warn "foo"> would print something like C<foo at -e line 1>. 
This method ignores everything after the "at". Thus to match this warning
you would have to call C<warning_is {warn "foo"} "foo", "Foo succeeded">.
If you need to test for a warning at an exactly line,
try something like C<warning_like {warn "foo"} qr/at XYZ.dat line 5/>.

warning_is and warning_are are only aliases to the same method.
So you also could write
C<warning_is {foo()} [], "no warning"> or something similar.
I decided to give two methods the same name to improve readability.

A true value is returned if the test succeeds, false otherwise.

The test name is optional, but recommended.


=item warnings_are BLOCK ARRAYREF, TEST_NAME

Tests to see that BLOCK gives exactly the specified warnings.
The test fails if the warnings from BLOCK are not exactly the ones in ARRAYREF.
If the ARRAYREF is equal to [],
then the test succeeds if the BLOCK doesn't give any warning.

Please read also the notes to warning_is as these methods are only aliases.

If you want more than one test for carped warnings, try this:
C<warnings_are {carp "c1"; carp "c2"} {carped => ['c1','c2'];> or
C<warnings_are {foo()} ["Warning 1", {carped => ["Carp 1", "Carp 2"]}, "Warning 2"]>.
Note that C<{carped => ...}> must always be a hash ref.

=item warning_like BLOCK REGEXP, TEST_NAME

Tests that BLOCK gives exactly one warning and it can be matched by
the given regexp.
If the string is undef, 
then the tests succeeds if the BLOCK doesn't give any warning.

The REGEXP is matched against the whole warning line,
which in general has the form "WARNING at __FILE__ line __LINE__".
So you can check for a warning in the file Foo.pm on line 5 with
C<warning_like {bar()} qr/at Foo.pm line 5/, "Testname">.
I don't know whether it makes sense to do such a test :-(
However, you should be prepared as a matching with 'at', 'file', '\d'
or similar will always pass. 
Think to the qr/^foo/ if you want to test for warning "foo something" in file foo.pl.

You can also write the regexp in a string as "/.../"
instead of using the qr/.../ syntax.
Note that the slashes are important in the string,
as strings without slashes are reserved for warning categories
(to match warning categories as can be seen in the perllexwarn man page).

Similar to C<warning_is>,
you can test for warnings via C<carp> with:
C<warning_like {bar()} {carped => qr/bar called too early/i};>

Similar to C<warning_is>/C<warnings_are>,
C<warning_like> and C<warnings_like> are only aliases to the same methods.

A true value is returned if the test succeeds, false otherwise.

The test name is optional, but recommended.

=item warning_like BLOCK STRING, TEST_NAME

Tests whether a BLOCK gives exactly one warning of the passed category.
The categories are grouped in a tree,
like it is expressed in perllexwarn.
Also see L</BUGS AND LIMITATIONS>.


Thanks to the grouping in a tree,
it's simple possible to test for an 'io' warning,
instead for testing for a 'closed|exec|layer|newline|pipe|unopened' warning.

Note, that warnings occurring at compile time,
can only be caught in an eval block. So

  warning_like {eval q/"$x"; $x;/} 
               [qw/void uninitialized/], 
               "some warnings at compile time";

will work,
while it wouldn't work without the eval.

Note, that it isn't possible yet,
to test for own categories,
created with warnings::register.

=item warnings_like BLOCK ARRAYREF, TEST_NAME

Tests to see that BLOCK gives exactly the number of the specified warnings
and all the warnings have to match in the defined order to the 
passed regexes.

Please read also the notes to warning_like as these methods are only aliases.

Similar to C<warnings_are>,
you can test for multiple warnings via C<carp>
and for warning categories, too:

  warnings_like {foo()} 
                [qr/bar warning/,
                 qr/bar warning/,
                 {carped => qr/bar warning/i},
                 'io'
                ],
                "I hope, you'll never have to write a test for so many warnings :-)";

=item warnings_exist BLOCK STRING|ARRAYREF, TEST_NAME

Same as warning_like, but will warn() all warnings that do not match the supplied regex/category,
instead of registering an error. Use this test when you just want to make sure that specific
warnings were generated, and couldn't care less if other warnings happened in the same block
of code.

  warnings_exist {...} [qr/expected warning/], "Expected warning is thrown";

  warnings_exist {...} ['uninitialized'], "Expected warning is thrown";

=back

=head2 EXPORT

C<warning_is>,
C<warnings_are>,
C<warning_like>,
C<warnings_like>,
C<warnings_exist> by default.

=head1 BUGS AND LIMITATIONS

Category check is done as qr/category_name/. In some case this works, like for
category 'uninitialized'. For 'utf8' it does not work. Perl does not have a list
of warnings, so it is not possible to generate one for Test::Warn.
If you want to add a warning to a category, send a pull request. Modifications
should be done to %warnings_in_category. You should look into perl source to check
how warning is looking exactly.

Please note that warnings with newlines inside are making a lot of trouble.
The only sensible way to handle them is to use are the C<warning_like> or
C<warnings_like> methods. Background for these problems is that there is no
really secure way to distinguish between warnings with newlines and a tracing
stacktrace.

If a method has it's own warn handler,
overwriting C<$SIG{__WARN__}>,
my test warning methods won't get these warnings.

The C<warning_like BLOCK CATEGORY, TEST_NAME> method isn't extremely tested.
Please use this calling style with higher attention and
tell me if you find a bug.

=head1 TODO

Improve this documentation.

The code has some parts doubled - especially in the test scripts.
This is really awkward and must be changed.

Please feel free to suggest improvements.

=head1 SEE ALSO

Have a look to the similar modules: L<Test::Exception>, L<Test::Trap>.

=head1 THANKS

Many thanks to Adrian Howard, chromatic and Michael G. Schwern,
who have given me a lot of ideas.

=head1 AUTHOR

Janek Schleicher, E<lt>bigj AT kamelfreund.deE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright 2002 by Janek Schleicher

Copyright 2007-2014 by Alexandr Ciornii, L<http://chorny.net/>

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

=cut
242
243
244package Test::Warn;
245
246
6
6
48
9
use 5.006;
247
6
6
6
9
5
69
use strict;
248
6
6
6
12
4
134
use warnings;
249
250#use Array::Compare;
251
6
6
6
132
60
35
use Sub::Uplevel 0.12;
252
253our $VERSION = '0.30';
254
255require Exporter;
256
257our @ISA = qw(Exporter);
258
259our %EXPORT_TAGS = ( 'all' => [ qw(
260    @EXPORT     
261) ] );
262
263our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
264
265our @EXPORT = qw(
266    warning_is   warnings_are
267    warning_like warnings_like
268    warnings_exist
269);
270
271
6
6
6
11
5
106
use Test::Builder;
272my $Tester = Test::Builder->new;
273
274{
275
6
6
6
9
4
3394
no warnings 'once';
276*warning_is = *warnings_are;
277*warning_like = *warnings_like;
278}
279
280sub warnings_are (&$;$) {
281
0
    my $block       = shift;
282
0
0
    my @exp_warning = map {_canonical_exp_warning($_)}
283                          _to_array_if_necessary( shift() || [] );
284
0
    my $testname    = shift;
285
0
    my @got_warning = ();
286    local $SIG{__WARN__} = sub {
287
0
        my ($called_from) = caller(0);  # to find out Carping methods
288
0
        push @got_warning, _canonical_got_warning($called_from, shift());
289
0
    };
290
0
    uplevel 1,$block;
291
0
    my $ok = _cmp_is( \@got_warning, \@exp_warning );
292
0
    $Tester->ok( $ok, $testname );
293
0
    $ok or _diag_found_warning(@got_warning),
294           _diag_exp_warning(@exp_warning);
295
0
    return $ok;
296}
297
298
299sub warnings_like (&$;$) {
300
0
    my $block       = shift;
301
0
0
    my @exp_warning = map {_canonical_exp_warning($_)}
302                          _to_array_if_necessary( shift() || [] );
303
0
    my $testname    = shift;
304
0
    my @got_warning = ();
305    local $SIG{__WARN__} = sub {
306
0
        my ($called_from) = caller(0);  # to find out Carping methods
307
0
        push @got_warning, _canonical_got_warning($called_from, shift());
308
0
    };
309
0
    uplevel 1,$block;
310
0
    my $ok = _cmp_like( \@got_warning, \@exp_warning );
311
0
    $Tester->ok( $ok, $testname );
312
0
    $ok or _diag_found_warning(@got_warning),
313           _diag_exp_warning(@exp_warning);
314
0
    return $ok;
315}
316
317sub warnings_exist (&$;$) {
318
0
    my $block       = shift;
319
0
0
    my @exp_warning = map {_canonical_exp_warning($_)}
320                          _to_array_if_necessary( shift() || [] );
321
0
    my $testname    = shift;
322
0
    my @got_warning = ();
323    local $SIG{__WARN__} = sub {
324
0
        my ($called_from) = caller(0);  # to find out Carping methods
325
0
        my $wrn_text=shift;
326
0
        my $wrn_rec=_canonical_got_warning($called_from, $wrn_text);
327
0
        foreach my $wrn (@exp_warning) {
328
0
          if (_cmp_got_to_exp_warning_like($wrn_rec,$wrn)) {
329
0
            push @got_warning, $wrn_rec;
330
0
            return;
331          }
332        }
333
0
        warn $wrn_text;
334
0
    };
335
0
    uplevel 1,$block;
336
0
    my $ok = _cmp_like( \@got_warning, \@exp_warning );
337
0
    $Tester->ok( $ok, $testname );
338
0
    $ok or _diag_found_warning(@got_warning),
339           _diag_exp_warning(@exp_warning);
340
0
    return $ok;
341}
342
343
344sub _to_array_if_necessary {
345
0
0
    return (ref($_[0]) eq 'ARRAY') ? @{$_[0]} : ($_[0]);
346}
347
348sub _canonical_got_warning {
349
0
    my ($called_from, $msg) = @_;
350
0
    my $warn_kind = $called_from eq 'Carp' ? 'carped' : 'warn';
351
0
    my @warning_stack = split /\n/, $msg;     # some stuff of uplevel is included
352
0
    return {$warn_kind => $warning_stack[0]}; # return only the real message
353}
354
355sub _canonical_exp_warning {
356
0
    my ($exp) = @_;
357
0
    if (ref($exp) eq 'HASH') {             # could be {carped => ...}
358
0
        my $to_carp = $exp->{carped} or return; # undefined message are ignored
359
0
        return (ref($to_carp) eq 'ARRAY')  # is {carped => [ ..., ...] }
360
0
0
            ? map({ {carped => $_} } grep {defined $_} @$to_carp)
361            : +{carped => $to_carp};
362    }
363
0
    return {warn => $exp};
364}
365
366sub _cmp_got_to_exp_warning {
367
0
0
    my ($got_kind, $got_msg) = %{ shift() };
368
0
0
    my ($exp_kind, $exp_msg) = %{ shift() };
369
0
    return 0 if ($got_kind eq 'warn') && ($exp_kind eq 'carped');
370
0
    my $cmp = $got_msg =~ /^\Q$exp_msg\E at .+ line \d+\.?$/;
371
0
    return $cmp;
372}
373
374sub _cmp_got_to_exp_warning_like {
375
0
0
    my ($got_kind, $got_msg) = %{ shift() };
376
0
0
    my ($exp_kind, $exp_msg) = %{ shift() };
377
0
    return 0 if ($got_kind eq 'warn') && ($exp_kind eq 'carped');
378
0
    if (my $re = $Tester->maybe_regex($exp_msg)) { #qr// or '//'
379
0
        my $cmp = $got_msg =~ /$re/;
380
0
        return $cmp;
381    } else {
382
0
        return Test::Warn::Categorization::warning_like_category($got_msg,$exp_msg);
383    }
384}
385
386
387sub _cmp_is {
388
0
0
    my @got  = @{ shift() };
389
0
0
    my @exp  = @{ shift() };
390
0
    scalar @got == scalar @exp or return 0;
391
0
    my $cmp = 1;
392
0
    $cmp &&= _cmp_got_to_exp_warning($got[$_],$exp[$_]) for (0 .. $#got);
393
0
    return $cmp;
394}
395
396sub _cmp_like {
397
0
0
    my @got  = @{ shift() };
398
0
0
    my @exp  = @{ shift() };
399
0
    scalar @got == scalar @exp or return 0;
400
0
    my $cmp = 1;
401
0
    $cmp &&= _cmp_got_to_exp_warning_like($got[$_],$exp[$_]) for (0 .. $#got);
402
0
    return $cmp;
403}
404
405sub _diag_found_warning {
406
0
    foreach (@_) {
407
0
        if (ref($_) eq 'HASH') {
408
0
0
0
            ${$_}{carped} ? $Tester->diag("found carped warning: ${$_}{carped}")
409
0
                          : $Tester->diag("found warning: ${$_}{warn}");
410        } else {
411
0
            $Tester->diag( "found warning: $_" );
412        }
413    }
414
0
    $Tester->diag( "didn't find a warning" ) unless @_;
415}
416
417sub _diag_exp_warning {
418
0
    foreach (@_) {
419
0
        if (ref($_) eq 'HASH') {
420
0
0
0
            ${$_}{carped} ? $Tester->diag("expected to find carped warning: ${$_}{carped}")
421
0
                          : $Tester->diag("expected to find warning: ${$_}{warn}");
422        } else {
423
0
            $Tester->diag( "expected to find warning: $_" );
424        }
425    }
426
0
    $Tester->diag( "didn't expect to find a warning" ) unless @_;
427}
428
429package Test::Warn::Categorization;
430
431
6
6
6
18
5
839
use Carp;
432
433my $bits = \%warnings::Bits;
434my @warnings = sort grep {
435  my $warn_bits = $bits->{$_};
436  #!grep { $_ ne $warn_bits && ($_ & $warn_bits) eq $_ } values %$bits;
437} keys %$bits;
438
439my %warnings_in_category = (
440  'utf8' => ['Wide character in \w+\b',],
441);
442
443sub _warning_category_regexp {
444
0
    my $category = shift;
445
0
    my $category_bits = $bits->{$category} or return;
446    my @category_warnings
447
0
0
      = grep { ($bits->{$_} & $category_bits) eq $bits->{$_} } @warnings;
448
449
0
    my @list =
450
0
0
      map { exists $warnings_in_category{$_}? (@{ $warnings_in_category{$_}}) : ($_) }
451      @category_warnings;
452
0
    my $re = join "|", @list;
453
0
    return qr/$re/;
454}
455
456sub warning_like_category {
457
0
    my ($warning, $category) = @_;
458
0
    my $re = _warning_category_regexp($category) or
459        carp("Unknown warning category '$category'"),return;
460
0
    my $ok = $warning =~ /$re/;
461
0
    return $ok;
462}
463
4641;