gpt4 book ai didi

PHPUnit 测试 shell 执行

转载 作者:行者123 更新时间:2023-12-04 05:11:17 29 4
gpt4 key购买 nike

我有一个负责与 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com