2

我有负责与 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;
}
4

1 回答 1

3

Here is what came to my mind just after I posted the question. Since I'm testing on linux, I created a bash script:

#!/bin/bash
echo -ne "exec_works"

And just ran it in test:

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

The downside is that test like this will only pass under linux environment (I've never used MAC so I don't know if it runs bash scripts), but will surely fail on windows since windows can't run bash scripts natively.

The soultion for this would be to just create executable script for every OS and make test check which OS server uses and run appropriate script.

于 2013-02-16T14:55:25.727 回答