How to evaluate Perl block before subtest

I want to color the output of the subtest description based on the result (pass / fail) of the subtest. That's what i still have

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 use use Term::ANSIColor and saw a color output. However, the transition from red / green occurs at the next test. For example, I printed green tests, one failed, still prints green, and the next test prints red. This tells me that $passed and colored ... work, but the block in subtest is evaluated after _construct_colored_description determines the color for the output.

For my actual code check my github project https://github.com/bostonaholic/test-more-behaviour

Thank you for your help!

+4
source share
1 answer

You need to defer evaluation of the description, one solution that comes to mind uses a callback for it. The idea is to return the closure from _construct_colored_description and run it in the 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 
+2
source

All Articles