PHPUnit 测试 shell 执行

标签 php phpunit

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

相关文章:

php - 如何在 Laravel 上正确更新模型?方法 Illuminate\Database\Eloquent\Collection::update 不存在

php - phpunit 中的 dbunit 没有截断表

php - 使用 vfsStream 将文件插入特定目录/节点

PHPUnit 模拟函数?

php - 如何对继承对象进行单元测试?

php - 如何检查 Doctrine 实体是否持久化并刷新到数据库?

javascript - 如何在jquery中通过图像上传发送文本输入值

javascript - PHP - 提交缺少名称属性的 HTML 表单

php - 如何使用 php 将 excel 数据导入现有的 mysql 表

php - 如何解决 Laravel 上数据从 Excel 到 MySQL 的变化值