Pau*_*ell 5 perl unit-testing template-toolkit
我正在尝试创建一个测试文件,使用模板工具包将模板值输入到字符串中,但我不知道要包含哪些检查/测试以确保模板工具包正确处理字符串。这是我的代码:
#!/usr/bin/env perl
use lib ('./t/lib/');
use strict;
use warnings;
use Template;
use Test::More tests => 1;
# options/configuration for template
my $config = {
#PRE_PROCESS => 1, # means the templates processed can use the same global vars defined earlier
#INTERPOLATE => 1,
#EVAL_PERL => 1,
RELATIVE => 1,
OUTPUT_PATH => './out',
};
my $template = Template->new($config);
# input string
my $text = "This is string number [%num%] .";
# template placeholder variables
my $vars = {
num => "one",
};
# processes imput string and inserts placeholder values
my $create_temp = $template->process(\$text, $vars)
|| die "Template process failed: ", $template->error(), "\n";
#is(($template->process(\$text, $vars)), '1' , 'The template is processing correctly');
# If process method is executed successfully it should have a return value of 1
diag($template->process(\$text, $vars));
Run Code Online (Sandbox Code Playgroud)
diag 函数返回值 1,从文档来看,这意味着该字符串已成功处理,但我一直在尝试检查 stdout 是什么,以便我可以看到输出字符串,但我可以打印它。我尝试从终端命令将标准输出写入文件,但文件中没有显示任何内容。我可以将 stderr 写入文件。我还尝试了模板的不同配置,如下面的代码所示。它不起作用是因为我没有运行任何测试,还是我以错误的方式使用了模板工具包?
如果回答此问题需要任何其他必需信息,请在下面评论。
这个答案假设该$template->process语句确实在您的生产代码中,而不是在单元测试中,并且展示了如果您不能只是告诉它将输出重定向到变量中,就像 Dave 在他的答案中所示的那样,该怎么做。
您可以使用Test::Output来检查STDOUT。
use Test::Output;
stdout_is { $template->process( \$text, $vars ) } q{This is string number one .},
q{Template generates the correct output};
Run Code Online (Sandbox Code Playgroud)
另一种选择是Capture::Tiny和两步测试。
use Capture::Tiny 'capture_stdout';
my $output = capture_stdout {
ok $template->process( \$text, $vars ), q{Template processes successfully};
};
is $output, q{This is string number one .}, q{... and the output is correct};
Run Code Online (Sandbox Code Playgroud)
请注意,这两种解决方案都会消耗输出,因此它也不会干扰您的终端(它不会干扰 TAP,因为 Test::Harness 只查看STDOUT)。