Search code examples
perldevel-cover

Devel::Cover Branch coverage on conditional ternary operator


I'm running cover from Devel::Cover on a module and getting 50% of branch coverage in lines that use the conditional ternary operator i.e.

return @rgb ? map { hex $_ } @rgb : undef;

Is this OK? Do I have to change the code to use if/else blocks in order to gain the 100% of coverage?

I'm new to Devel::Cover so any insight that you could provide about this, will be really helpful.

Thanks


Solution

  • You are not getting coverage for the false branch of the ternary, because your tests do not cover a case where @rgb is empty. In that case, the map will never be called, but it will return undef (or () like @ikegami suggested).

    The ternary is the same as this:

    if (@rgb) { 
      return map { hex $_ } @rgb;
    } else {
      return undef;
    }
    

    So there is a branch there that has not been covered by the test.

    You have several options:

    • go with the empty list and just remove the ternary like ikegami suggested, and take into account that you don't ensure the program does what you want if @rgb has no elements
    • add an # uncoverable branch false comment as described in https://metacpan.org/pod/Devel::Cover#UNCOVERABLE-CRITERIA
    • write a test case where it expects @rgb not to have elements

      is foo('no_rgbs'), undef, 'returns undef when there are no elements';