如何在子测试之前评估Perl块
发布时间:2020-12-16 06:14:27 所属栏目:大数据 来源:网络整理
导读:我想根据子测试的结果(通过/失败)为子测试描述的输出着色.这是我到目前为止所得到的 sub run_subtest { my $desc = 'subtest description'; subtest _construct_colored_description($desc) = sub { $passed = 1; #passed is global };}sub _construct_color
我想根据子测试的结果(通过/失败)为子测试描述的输出着色.这是我到目前为止所得到的
sub run_subtest { my $desc = 'subtest description'; subtest _construct_colored_description($desc) => sub { $passed = 1; #passed is global }; } sub _construct_colored_description { my $desc = shift; return colored [$passed ? 'green' : 'red'],$desc; } 我使用Term :: ANSIColor并看到了彩色输出.但是,红色/绿色的切换发生在下一个子测试中.例如,我打印了绿色测试,一个失败,仍然打印绿色,下一个测试打印为红色.这告诉我$pass和color …正在工作,但是在_construct_colored_description确定要输出的颜色之后,正在评估subtest中的块. 对于我的实际代码,请查看我的github项目https://github.com/bostonaholic/test-more-behaviour 谢谢你的帮助! 解决方法
你需要推迟对描述的评估,一个想到的解决方案就是使用回调.我们的想法是从_construct_colored_description返回闭包并在subtest函数中运行它:
my $passed = 0; sub subtest { my ($desc_cb,$test_cb) = @_; $test_cb->(); print $desc_cb->(),"n"; } sub _construct_colored_description { my $desc = shift; return sub { return $passed ? '[green]' : '[red]',$desc }; } # testing with two subtests my $desc = 'subtest description'; subtest _construct_colored_description($desc) => sub { $passed = 1; }; $desc = 'subtest description2'; subtest _construct_colored_description($desc) => sub { $passed = 0; }; 得到: [green]subtest description [red]subtest description2 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |