如何对打印到屏幕上的 Perl 函数进行单元测试? [英] How can I unit test Perl functions that print to the screen?
问题描述
我正在尝试使用 Test::More 对 Perl 函数进行单元测试打印到屏幕上.
我了解此输出可能会干扰诸如 prove 之类的工具.
如何捕获此输出以便我可以使用 diag()
打印它,并对输出本身运行测试?
UPDATE: 恕我直言,这个问题的正确答案应该是使用 Test::Output:
#!/usr/bin/perl使用严格;使用警告;使用测试::更多测试=>1;使用测试::输出;sub myfunc { 打印这是一个测试\n"}stdout_is(\&myfunc, "这是一个测试\n", 'myfunc() 返回测试输出');
输出:
<前>C:\Temp> tm1..1ok 1 - myfunc() 返回测试输出我将原始答案留作参考,因为我相信它仍然说明了一种有用的技术.
您可以在调用函数之前本地化 STDOUT
并重新打开为标量,然后恢复:
#!/usr/bin/perl使用严格;使用警告;使用测试::更多测试=>1;sub myfunc { 打印这是一个测试\n"}子调用{我的 $sub = shift;我的 $stdout;{本地*标准输出;打开标准输出, '>', \$stdout或者死无法将标准输出打开到标量:$!";$sub->(@_);关闭标准输出或者死无法关闭重定向的标准输出:$!";}返回 $stdout;}chomp(my $ret = invoke(\&myfunc));ok($ret eq "This is a test", "myfunc() 打印测试字符串");diag("myfunc() 打印了 '$ret'");
输出:
<前>C:\Temp> tm1..1ok 1 - myfunc() 打印测试字符串# myfunc() 打印这是一个测试"对于 5.8 之前的 perl
版本,您可能需要使用 IO::Scalar,但我不太了解 5.8 之前的工作原理.
I'm trying to use Test::More to unit test Perl functions that print to the screen.
I understand that this output may interfere with tools such as prove.
How can I capture this output so I can print it with diag()
, and also run tests on the output itself?
UPDATE: IMHO, the correct answer to this question ought to be to use Test::Output:
#!/usr/bin/perl
use strict; use warnings;
use Test::More tests => 1;
use Test::Output;
sub myfunc { print "This is a test\n" }
stdout_is(\&myfunc, "This is a test\n", 'myfunc() returns test output');
Output:
C:\Temp> tm 1..1 ok 1 - myfunc() returns test output
I am leaving the original answer for reference as, I believe, it still illustrates a useful technique.
You can localize STDOUT
and reopen to a scalar before calling the function, restore afterward:
#!/usr/bin/perl
use strict; use warnings;
use Test::More tests => 1;
sub myfunc { print "This is a test\n" }
sub invoke {
my $sub = shift;
my $stdout;
{
local *STDOUT;
open STDOUT, '>', \$stdout
or die "Cannot open STDOUT to a scalar: $!";
$sub->(@_);
close STDOUT
or die "Cannot close redirected STDOUT: $!";
}
return $stdout;
}
chomp(my $ret = invoke(\&myfunc));
ok($ret eq "This is a test", "myfunc() prints test string" );
diag("myfunc() printed '$ret'");
Output:
C:\Temp> tm 1..1 ok 1 - myfunc() prints test string # myfunc() printed 'This is a test'
For versions of perl
older than 5.8, you probably need to use IO::Scalar, but I do not know much about how things worked before 5.8.
这篇关于如何对打印到屏幕上的 Perl 函数进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!