加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 23:21:06 所属栏目:大数据 来源:网络整理
导读:我正在尝试创建一个测试文件,使用模板工具包将模板值输入到字符串中,但我不知道要包含哪些检查/测试以确保模板工具包正确处理字符串.这是我的代码: #!/usr/bin/env perluse lib ('./t/lib/');use strict;use warnings;use Template;use Test::More tests =
我正在尝试创建一个测试文件,使用模板工具包将模板值输入到字符串中,但我不知道要包含哪些检查/测试以确保模板工具包正确处理字符串.这是我的代码:

#!/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).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读