【问题标题】:Mock perl backtick's return code and output模拟 perl 反引号的返回码和输出
【发布时间】:2019-07-15 23:12:36
【问题描述】:

我正在尝试在 perl 中编写一个单元测试用例,我需要模拟通过反引号运行的命令输出及其返回码两次。

考虑如下代码流

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);
}

现在我需要模拟非零返回码。 我怎样才能做到这一点?

我有类似下面的东西,但这只是模拟输出,但返回码总是 0

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

我正在使用 Perl 5.10。而且我无法使用反引号更改执行命令。

【问题讨论】:

标签: unit-testing perl mocking


【解决方案1】:

Backticks/readpipe$? 中返回退出状态,因此您只需在模拟的读取管道函数中设置$?

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";
  }
}

【讨论】:

  • 像魅力一样工作。谢谢@mob
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-04
  • 1970-01-01
  • 1970-01-01
  • 2011-04-10
  • 2023-03-23
  • 2019-09-10
  • 1970-01-01
相关资源
最近更新 更多