Perl 尝试使用模板值和模板正在正确处理的单元测试创建字符串

Perl 尝试使用模板值和模板正在正确处理的单元测试创建字符串,perl,unit-testing,template-toolkit,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

我试图创建一个测试文件,使用模板工具箱将模板值输入字符串,但我不知道要包括哪些检查/测试,以确保模板工具箱正确处理字符串。这是我的密码:

#!/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));
diag函数返回值1,从文档中可以看出,该值表示字符串已成功处理,但我一直在尝试检查stdout是什么,以便可以看到输出字符串,但可以将其打印出来。我已经尝试从terminal命令将标准输出写入一个文件,但文件中没有显示任何内容。不过,我可以将stderr写入文件。 我还尝试了不同的模板配置,如下面的代码所示。它不起作用是因为我没有运行任何测试,还是因为我以错误的方式使用模板工具包


如果回答这个问题需要任何其他必要的信息,只需在下面进行评论。

这个回答假设
$template->process
语句确实在您的生产代码中,而不是在单元测试中,并显示了如果您不能告诉它将输出重定向到变量中,如何执行此操作

您可以使用检查
STDOUT

use Test::Output;

stdout_is { $template->process( \$text, $vars ) } q{This is string number one .},
    q{Template generates the correct output};

另一种选择可能是两步测试和两步测试

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};


请注意,这两种解决方案都会消耗输出,因此它也不会干扰您的终端(它不会干扰抽头,因为Test::Harness只查看
STDOUT
)。

您这里的主要问题是
process()
将其输出发送到STDOUT,而您没有捕获它。因此,您没有看到任何扩展的输出

process()
方法采用可选的第三个参数,该参数可以采用各种有用的值。您可能希望向它传递一个对空标量变量的引用,然后用扩展模板填充该变量

$template->process(\$text, $vars, \$output);
is($output, $expected_output);

但值得注意的是,TT发行版中包含了,您可能会发现它非常有用。

我认为您描述的问题有点过于复杂。虽然提供背景很好,但真正的问题却消失了。我想您是在问如何检查模板是否创建了正确的输出,所以这就是我的回答。基本上你想测试你的模板是否有效?是的。哈哈。很抱歉我试图详细说明我不知道Template::Test。非常有用。:)我已经忘记了。但我确信这样的东西一定存在:-)现在我在想我们如何在$work中使用它来获得更多的前端覆盖。耶。:)在我的答案中还添加了一个免责声明,使其与您的答案更为不同。for Template::Test表示,随着Test::more的出现,它在很大程度上变得多余。就个人而言,我不喜欢必须将
test\u expect()
的测试嵌入到特殊格式的文件或
\u数据块中。