How do I evaluate Perl block before subtest
I'm wanting to color the output of a subtest description based on the result (pass/fail) of the subtest. Here's what I've got so far
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;
}
I am use use Term::ANSIColor
and have seen the colored output. However, the switch from red/green is happening on the next subtest. For instance, I have printed green tests, one fails, still prints green and the next test prints red. This tells me that $passed
and the colored ...
is working, but the block in subtest
is being evaluated after the _construct_colored_description
is determining the color to outp开发者_C百科ut.
For my actual code, checkout my github project https://github.com/bostonaholic/test-more-behaviour
Thanks for your help!
You need to postpone evaluation of description, one solution that comes to mind is using callback for it. The idea is to return closure from _construct_colored_description
and run it in subtest
function:
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;
};
Gives:
[green]subtest description
[red]subtest description2
精彩评论