Monk::Thomas has asked for the wisdom of the Perl Monks concerning the following question:

Hello fellow monks

In one of my modules I have two functions and I'm not able to come up with a testcase for the else-branch of one of them.

Here's the code:

[...] use Carp; use Scalar::Util qw(openhandle); [...] sub read_value { my $input = shift; my $length = shift; if (ref $input eq 'SCALAR') { return _read_value_from_sref($input, $length); } elsif (defined openhandle($input)) { return _read_value_from_fh($input, $length); } else { croak("Invalid usage!\n"); } } sub _read_value_from_fh { my $fh = shift; my $length = shift; my $curpos = tell $fh; my $filelength = (stat $fh)[7]; if ($curpos + $length > $filelength) { # can not read beyond end of file return; } if (read $fh, (my $value), $length) { return $value; } # don't know how to provoke the else-branch for testing else { carp("Something bad happened!\n"); # try to return to previous position seek $fh, 0, $curpos; return; } }

Is the else-branch dead code and can be removed or is there a condition which would be able to reach it? I tried to read beyond EOF, close the file handle, remove read permissions, calling _read_value_from_fh() to directly, feeding a negative length but nothing 'worked'.

bye
thomas

Replies are listed 'Best First'.
Re: Unable to reach branch - Dead code or defensive programming?
by MidLifeXis (Monsignor) on Feb 24, 2015 at 20:27 UTC

    How about the case where a file is truncated between the stat call and the read call. Definitely not dead code. Hard to test, possibly. If you wish to test it, you could wrap the read call into another sub, and mock that sub within your test.

    --MidLifeXis

Re: Unable to reach branch - Dead code or defensive programming?
by poj (Abbot) on Feb 24, 2015 at 19:47 UTC
    Maybe try $length = 0
    poj
Re: Unable to reach branch - Dead code or defensive programming?
by Anonymous Monk on Feb 24, 2015 at 19:55 UTC