Yogesh Patil
Yogesh Patil

Reputation: 888

Mock perl backtick's return code and output

I am trying to write a unit test case in perl where i need to mock output of command run via backticks and its return code twice.

Consider code flow like below

sub foo {
  my $out = `ls -R`;
  my $ret = $?;

  if( $ret == 0 ) {
    $out = `ls -R > foo.txt`;
  } elsif {
    # some retry logic
    # i want to cover this code path
  }
  return ($ret, $out);
}

Now i need to mock non zero return codes. How can i acheive that?

I have something like below, but this only mocks output but return code is always 0

BEGIN {
  *CORE::GLOBAL::readpipe = sub($) {
    my $var = $_[0];
    return 1;
  }
};

I am using Perl 5.10. and i cannot change using backticks to execute the command.

Upvotes: 4

Views: 228

Answers (1)

mob
mob

Reputation: 118605

Backticks/readpipe return the exit status in $?, so you will just want to set $? in your mocked readpipe function.

BEGIN {
  *CORE::GLOBAL::readpipe = \&mock_readpipe
};
sub mock_readpipe {
  my $var = $_[0];
  if ($var =~ /cat|dog/) {
      $? = 1 >> 8;  # simulate exit code 1
      return;
  } else if (wantarray) {
      $? = 0;
      return ("foo\n", "bar\n");
  } else {
      $? = 0;
      return "foo\nbar\n";
  }
}

Upvotes: 3

Related Questions