gpt4 book ai didi

perl - 如何在不丢失程序退出代码的情况下使用 Test::More 在 perl 程序中测试 subs?

转载 作者:行者123 更新时间:2023-12-04 01:15:29 25 4
gpt4 key购买 nike

在编写中小型 perl 程序时,我想用“Test::More”测试一些函数。

我的想法是能够像“./supertool.pl --test”这样调用我的程序来进行测试。虽然能够使用“./supertool.pl”进行正常的程序使用。

但是当我添加“use Test::More qw(no_plan);”时在头部部分,它混淆了程序输出及其退出代码。

这是一个可以在控制台中调用的例子:'./supertool.pl;回声$? ; echo "预期: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 返回其对象)来设置计划/跳过,即使在 Test::More< 中有一个 plan 函数 本身。

这是为了保持一致性,因为对于 output 我们确实需要 Test::Builder,作为 Test::Builder 的进一步示例,在可能需要的情况下,人们可以在其中找到更多工具。 Test::More 建立在这个模块之上,我建议仔细阅读它。

声明 no_plan 的替代方法是在程序的最后使用 done_testing,以 $run_tests 为条件(但不是在 END block ,请参阅文档)。

另一种方法是将所有测试放在 SKIP block 中,用于 conditional testing

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方法,要么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;
}

或者重置,针对不同的情况或上下文

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

当程序在没有任何参数的情况下被调用时,所有这些都不打印任何内容并具有退出代码 0,或者在使用“true”参数调用时运行测试并打印消息。 所有这些都经过了(超过 1 个)测试 block 的测试,为简洁起见,此处省略。

之所以需要处理上面的一些细节,是因为测试框架旨在用于专用程序,而不是用于测试正在运行的程序中的部分。虽然也可以这样使用它,但有些事情会变得更加复杂。

参见 Test2 ,或者它的套件 Test2::Suite ,以获得更新的替代方案。


也就是说,当传递给程序时,Perl 为“true”,因此不是 0 或空字符串 "''"

关于perl - 如何在不丢失程序退出代码的情况下使用 Test::More 在 perl 程序中测试 subs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63503575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com