perl Testing读书笔记(测试警告信息)

上一篇 / 下一篇  2012-04-15 16:55:43 / 个人分类:perl相关

 

Test::Warn 提供了测试警告信息的方法

下面是例子:warnings.pl

#!/usr/bin/perl

use Test::More tests => 4;
use Test::Warn;

sub add_positives {
 my ( $l, $r ) = @_;
 warn "first argument ($l) was negative" if $l < 0;
 warn "second argument ($r) was negative" if $r < 0;
 return $l + $r; 
}

warning_is { is( add_positives( 8, -3 ), 5) }
    "second argument (-3) was negative";
warnings_are { is( add_positives( -8, -3 ), -11 ) }
    [
        'first argument (-8) was negative',
        'second argument (-3) was negative'
    ];

运行结果如下:

D:\loveperl>prove -v warnings.pl
warnings....1..4
ok 1
ok 2
ok 3
ok 4
ok
All tests successful.
Files=1, Tests=4,  0 wallclock secs ( 0.00 cusr +  0.00 csys =  0.00 CPU)

如果预期的警告信息和实际的警告信息不能完全准确匹配,那么可以使用正则表达式匹配其中部分的字符串,可以使用warnings_like

下面是例子:warnings2.pl

#!/usr/bin/perl

use Test::More tests => 4;
use Test::Warn;

sub add_positives {
 my ( $l, $r ) = @_;
 warn "first argument ($l) was negative" if $l < 0;
 warn "second argument ($r) was negative" if $r < 0;
 return $l + $r; 
}


warning_like { is( add_positives ( 8, -3 ), 5 ) } qr/negative/;
warning_like { is( add_positives( -8, -3 ), -11) }
  [ qr/first.*negative/, qr/second.*negative/ ];

运行结果如下:

D:\loveperl>prove -v warnings2.pl
warnings2....1..4
ok 1
ok 2
ok 3
ok 4
ok
All tests successful.
Files=1, Tests=4,  0 wallclock secs ( 0.00 cusr +  0.00 csys =  0.00 CPU)

 

如果是确定所有的测试都不产生任何警告信息,就是用Test::NoWarnings模块

下面是例子:nowarn.pl

#!/usr/bin/perl

use Test::More tests => 3;
use Test::NoWarnings;

sub add_positives {
 my ( $l, $r ) = @_;
 warn "first argument ($l) was negative" if $l < 0;
 warn "second argument ($r) was negative" if $r < 0;
 return $l + $r; 
}

is( add_positives ( 4, 6 ), 10 );
is( add_positives( 8, -3), 5);

运行结果如下:

D:\loveperl>prove -v warnings2.pl
warnings2....1..4
ok 1
ok 2
ok 3
ok 4
ok
All tests successful.
Files=1, Tests=4,  0 wallclock secs ( 0.00 cusr +  0.00 csys =  0.00 CPU)

D:\loveperl>prove -v nowarn.pl
nowarn....1..3
ok 1
ok 2

not ok 3 - no warnings
#   Failed test 'no warnings'
#   at C:/Perl/site/lib/Test/NoWarnings.pm line 45.
# There were 1 warning(s)
#       Previous test 1 ''
#       second argument (-3) was negative at nowarn.pl line 9.
#  at nowarn.pl line 9
#       main::add_positives(8, -3) called at nowarn.pl line 14
#
# Looks like you failed 1 test of 3.
dubious
        Test returned status 1 (wstat 256, 0x100)
DIED. FAILED test 3
        Failed 1/3 tests, 66.67% okay
Failed Test Stat Wstat Total Fail  List of Failed
-----------------------------------------------------------------------------
nowarn.pl      1   256     3    1  3
Failed 1/1 test scripts. 1/3 subtests failed.
Files=1, Tests=3,  1 wallclock secs ( 0.00 cusr +  0.00 csys =  0.00 CPU)
Failed 1/1 test programs. 1/3 subtests failed.


TAG:

 

评分:0

我来说两句

Open Toolbar