perl – 尝试使用模板值和单元测试创​​建一个字符串,模板正在正确处理

前端之家收集整理的这篇文章主要介绍了perl – 尝试使用模板值和单元测试创​​建一个字符串,模板正在正确处理前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试创建一个测试文件,使用模板工具包将模板值输入到字符串中,但我不知道要包含哪些检查/测试以确保模板工具包正确处理字符串.这是我的代码

#!/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是什么,所以我可以看到输出字符串,但我可以打印它.我尝试将stdout写入终端命令中的文件,但文件中没有任何内容.我可以将stderr写入文件.
我也一直在为模板尝试不同的配置,如下面的代码所示.是不行,因为我没有运行任何测试,或者我是否以错误的方式使用Template Toolkit?

如果有任何其他所需信息需要回答这个问题,请在下面评论.

解决方法

这个答案假定$template->进程语句实际上在您的生产代码中,而不是在单元测试中,并且如果您不能告诉它将输出重定向到变量 like Dave shows in his answer,则显示如何执行此操作.

您可以使用Test::Output检查STDOUT.

use Test::Output;

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

另一种选择可以是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};

请注意,这两种解决方案都会占用输出,所以它也不会弄乱您的终端(它不会弄乱TAP,因为Test :: Harness只关注STDOUT).

猜你在找的Perl相关文章