我有一个类负责与 shell 交互,有什么方法可以使用 PHPUnit 测试这样的函数吗?
public function runCommand($command, $stdin = null)
{
$descriptorspec = array(
array("pipe", "r"), // stdin
array("pipe", "w"), // stdout
array("pipe", "w"), // stderr
);
$environment = array();
$proc = proc_open(
$command,
$descriptorspec,
$pipes,
__DIR__,
$environment
);
if (!is_resource($proc)) {
return false;
}
if ($stdin !== null) {
fwrite($pipes[0], $stdin);
fclose($pipes[0]);
}
$result = stream_get_contents($pipes[1]);
fclose($pipes[1]);
if (proc_close($proc) !== 0) {
return false;
}
return $result;
}
最佳答案
这是我发布问题后想到的。由于我在 Linux 上进行测试,因此我创建了一个 bash 脚本:
#!/bin/bash
echo -ne "exec_works"
刚刚在测试中运行它:
public function testShellExecution()
{
// root tests directory constant, set in PHPUnit bootstrap file
$path = TESTDIR . "/Resources/exec_test.sh";
$this->assertEquals(
"exec_works",
$this->shellCommander->runCommand("bash $path")
);
}
缺点是这样的测试只能在linux环境下通过(我从来没有使用过MAC所以我不知道它是否运行bash脚本),但在windows上肯定会失败,因为windows无法运行bash脚本原生地。
这样做的灵魂是为每个操作系统创建可执行脚本,并进行测试检查哪个操作系统服务器使用并运行适当的脚本。
关于PHPUnit 测试 shell 执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14911321/