我正在编写一个Perl模块,并且我正在使用carp向调用程序抛回一个非致命警告。
carp警告运行良好-我正在检查输入参数是否满足特定条件-如果它不满足条件,则向carp发送警告,并且模块继续使用参数的默认值,而不是调用程序传递的默认值。该警告只是通知正在使用默认参数,而不是传入的参数。
我的问题在于我的测试脚本。我的测试脚本向模块发送了一个错误的参数,我正在尝试捕获返回的警告消息,并确保我得到了正确的警告消息。
我的模块看起来像这样:
else {
carp "value must be numeric - using default value";
}我的测试脚本如下所示:
eval {
#call to my module
};
like (
$@,
qr/value must be numeric/,
"Should abort on non-numeric value"
);当我运行测试时,我可以在屏幕上看到警告(它必须转到STDERR),但是$@变量的内容是'‘-空白。
以下是我的测试脚本的输出:
t/04bad_method_calls....ok 10/12value must be numeric - using default value at ...
# Failed test 'Should abort on non-numeric value'
# at t/04bad_method_calls.t line 98.
t/04bad_method_calls....NOK 12
# '' doesn't match '(?-xism:value must be numeric)'
# Looks like you failed 1 test of 12.如果我将carp更改为croak,我的测试脚本就会工作-它会捕获错误消息(但我只想发出警告,而不是中止)。
老实说,我对eval不是最好的理解--也许这不是捕捉carp的警告输出的最好方法。我尝试使用$SIG{__WARN__},但也是空的。
有什么方法可以捕获carp的输出吗?这不是最大的问题,因为这只是在我的测试脚本中,但我仍然希望让我的测试脚本正常工作。
提前感谢!
发布于 2009-01-27 15:00:44
从这个页面http://perldoc.perl.org/perlvar.html中,看起来您想要将本地$SIG{__WARN__}设置为一个子例程,该例程将把警告转换为您的测试脚本的致命错误。他们给出的例子是:
local $SIG{__WARN__} = sub { die $_[0] };
eval $proggie;发布于 2009-01-27 16:06:24
另一种捕获警告和所有STDERR输出的方法:
my $stderr = '';
{
local *STDERR;
open STDERR, '>', \$stderr;
do_stuf_here();
}
like( $stderr, qr/my result/, 'test stderr output' );你可以做一个奇特的测试函数:
sub stderr_test (&$$) {
my ( $code, $pattern, $text ) = @_;
my $result = '';
{
local *STDERR;
open STDERR, '>', \$result;
$code->();
}
if ( UNIVERSAL::isa( $pattern, 'Regexp' ) ) {
like( $result, $pattern, $text );
}
else {
is( $result, $pattern, $text );
}
}
# usage
stderr_test {do_stuf_here} qr/my expected STDERR output/,
'stderr is like';
stderr_test {do_stuf_here} 'my expected STDERR output',
'stderr is exactly';发布于 2009-01-27 18:09:01
如果您从测试脚本执行此操作,则可以使用Test::*模块为您捕获输出。我更喜欢Test::Output。
https://stackoverflow.com/questions/483622
复制相似问题