Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock Perl's built-in backticks operator?

I'd like to unit test a Perl program of mine that is using backticks. Is there a way to mock the backticks so that they would do something different from executing the external command?

Another question shows what I need, but in Ruby. Unfortunately, I cannot choose to use Ruby for this project, nor do I want to avoid the backticks.

like image 493
Jonas Wagner Avatar asked Sep 09 '10 16:09

Jonas Wagner


1 Answers

You can* mock the built-in readpipe function. Perl will call your mock function when it encounters a backticks or qx expression.

BEGIN {
  *CORE::GLOBAL::readpipe = \&mock_readpipe
};

sub mock_readpipe {
  wantarray ? ("foo\n") : "foo\n";
}

print readpipe("ls -R");
print `ls -R`;
print qx(ls -R);


$ perl mock-readpipe.pl
foo
foo
foo

* - if you have perl version 5.8.9 or later.

like image 138
mob Avatar answered Nov 16 '22 03:11

mob