如何解决如何在不丢失程序退出代码的情况下使用Test :: More测试perl程序中的子程序?
编写小型到中型的perl程序时,我具有要使用“ Test :: More”进行测试的功能。
这个想法是要能够调用“ ./supertool.pl --test”之类的程序来进行测试。可以正常使用程序时使用“ ./supertool.pl”。
但是当我添加“使用Test :: More qw(no_plan);”时在头部,它使程序输出及其退出代码乱码。
这是一个可以在控制台中调用的示例,例如:'./supertool.pl;回声$? ;回声“预期:0”。
#!/usr/bin/perl
use strict;
use warnings;
use Test::More qw(no_plan);
if (0)
{
note("one test");
test__x();
done_testing;
}
exit(0);
sub test_x
{
ok( 1,"1 is ok" );
}
输出为:
1..0
255
Expected: 0
但是我希望输出是
0
Expected: 0
是否可以对Test :: More进行调整,使其不打印“ 1..0”,并且在不进行任何测试时不破坏程序的退出代码?
解决方法
有几种方法可以获取所需的行为。
一种方法是根据该命令行选项告诉您不会运行测试
use warnings;
use strict;
use feature 'say';
use Test::More;
my $run_tests = shift;
if ($run_tests) {
Test::More->builder->no_plan;
}
else {
Test::More->builder->output('/dev/null');
Test::More->builder->skip_all('Not testing');
}
#...
if ($run_tests) {
note("one test");
test_x();
}
sub test_x { ok( 1,"1 is ok" ) }
由于需要将输出重定向到/dev/null
,因此不会显示用于跳过的消息,但仅作为示例提供(其中必须有内容)。
我使用后端Test::Builder模块(Test::More->builder
返回其对象)中的方法来设置计划/跳过,即使plan
本身有一个Test::More
函数
这是为了保持一致性,因为对于output
,我们确实需要Test::Builder
,而作为Test::Builder
的其他示例,在可能需要的情况下,人们可以找到更多的工具。 Test::More
是建立在这种模式之上的,我建议您仔细阅读。
声明no_plan
的另一种方法是在程序的最后使用done_testing
,该条件以$run_tests
为条件(但不在END
块中,请参阅docs)。
另一种方法是将所有测试放在conditional testing的SKIP
块中
use warnings;
use strict;
use feature 'say';
use Test::More qw(no_plan);
my $run_tests = shift;
SKIP: {
skip_test() if not $run_test;
note("one test");
test_x();
}
sub test_x { ok( 1,"1 is ok" ) }
sub skip_test {
Test::More->builder->output('/dev/null');
skip "Not testing";
}
根据问题的需要将输出再次发送到/dev/null
。
我们还可以直接使用Test::Builder
的{{1}}方法
skip
或use warnings;
use strict;
use feature 'say';
use Test::More qw(no_plan);
my $run_tests = shift;
if ($run_tests) {
note("one test");
test_x();
}
else { skip_test() }
sub test_x { ok( 1,"1 is ok" ) }
sub skip_test {
Test::More->builder->output('/dev/null');
Test::More->builder->skip;
}
,用于不同的情况或上下文
reset
最后最好使用use warnings;
use strict;
use feature 'say';
use Test::More qw(no_plan);
my $run_tests = shift;
if ($run_tests) {
note("one test");
test_x();
}
else { Test::More->builder->reset }
# At the very end of the program (not in END block though)
done_testing if $run_tests;
sub test_x { ok( 1,"1 is ok" ) }
。
所有这些都不显示任何内容,并且在不带任何参数的情况下调用程序时,退出代码为done_testing
,或者在以“ true”参数调用时运行测试并打印消息。†全部其中有更多(超过1个)测试块进行了测试,为简洁起见,在此省略。
需要处理上面的一些细节,因为测试框架旨在用于专用程序中,而不是用于测试正在运行的程序中的片段。而且虽然可以以这种方式使用它,但有些事情变得更加复杂。
请参阅Test2或它的套件Test2::Suite,以获取更新的选择。
†即,传递给程序的Perl为“ true”,而不是0
或空字符串0
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。