我写一个Perl模块,和我使用的鲤鱼抛出一个非致命警告返回给调用程序。

在鲤鱼预警工作正常 - 我检查如果输入参数满足一定的条件 - 如果它不符合条件,警告与鲤鱼发送和模块将继续使用默认的参数,而不是一调用程序通过。警告只是以通知默认的参数被用来代替在参数传递。

我的问题是我的测试脚本。我的测试脚本发送一个错误的参数到模块,以及我试图赶上回来的警告信息,并确保我得到了正确的警告消息。

我的模块看起来是这样的:

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.

如果我改变了鲤鱼的叫声,我的测试脚本工作 - 它捕捉到该错误消息(但我只是想提醒,不要中止)

说实话,我没有EVAL最了解 - 也许这是不是赶上鲤鱼输出警告的最佳方式。我尝试使用$ SIG {的 WARN },但是是空的为好。

有什么办法来捕捉鲤鱼输出?这不是最大的问题,因为这只是在我的测试脚本,但我还是想获得我的测试脚本才能正常工作。

提前感谢!

有帮助吗?

解决方案

在该页面中, http://perldoc.perl.org/perlvar.html ,它看起来像你想的地方$SIG{__WARN__}设置为一个子程序,它会变成警告到测试脚本的致命错误。他们给出的例子是:

local $SIG{__WARN__} = sub { die $_[0] };
eval $proggie;

其他提示

另一种方式如何捕捉警告和也所有STERR输出:

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';

如果你从一个测试脚本这样做,你可以使用测试:: *模块捕获为你输出。我倾向于喜欢测试::输出

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top