views:

293

answers:

2

When running an applications test suite I want to promote all Perl compile and run-time warnings (eg the "Uninitialized variable" warning) to fatal errors so that I and the other developers investigate and fix the code generating the warning. But I only want to do this during development and CI testing. In production, the warnings should just stay as warnings.

I tried the following: In "t/lib" I created a module TestHelper.pm:

# TestHelper.pm
use warnings FATAL => qw( all );
1;

Then called the test suite like this:

$ PERL5LIB=$PERL5LIB:./t/lib PERL5OPT=-MTestHelper.pm prove -l t/*.t

But this did not have the desired effect of promoting all warnings to fatal errors. I got the warnings as normal but the warnings did not appear to be treated as fatal. Note that all my test.t scripts have the line "use warnings;" in them -- perhaps this over-rides the one in TestHelper.pm because "use warnings" has a local scope?

Instead I've done this:

# TestHelper.pm
# Promote all warnings to fatal 
$SIG{__WARN__} = sub { die @_; };
1;

This works but has a code smell about it. I also don't like that it bombs out on the first warning. I'd rather the test suite ran in full, logging all warnings, but that the test status ultimately failed because the code ran with warnings.

Is there a better way to achieve this end result?

+11  A: 

I think you're looking for Test::NoWarnings.

cjm
That module is exactly what I need, thanks. You know it works more or less the same as friedo suggests above. :-)
Hissohathair
+10  A: 

The reason use warnings FATAL => qw( all ); isn't working for you is because use warnings is lexically scoped. So any warnings produced inside TestHelper.pm would be fatal, but warnings produced elsewhere will work as normal.

If you want to enable fatal warnings globally, I think a $SIG{__WARN__} handler is probably the only way to do it. If you don't want it to blow up on the first warning, you could let your handler store them in an array, then check it in an END block.

my @WARNINGS;
$SIG{__WARN__} = sub { push @WARNINGS, shift };

END { 
    if ( @WARNINGS )  {       
        print STDERR "There were warnings!\n";
        print "$_\n" for @WARNINGS;
        exit 1;
    }
}
friedo
I understand that "use warnings" is lexically scoped. But my TestHelper.pm didn't have a "package" declaration. Is one implied when I pass "-MTestHelper" via PERL5OPTS?
Hissohathair
Lexical scoping has nothing to do with packages. It runs from the point of declaration to the end of the file (or the ending curly brace, if it was inside curly braces). It never affects code in another file.
cjm
Ah. Excellent, thanks.
Hissohathair

related questions