2

I have class responsible for interaction with shell, is there any way I can test functions such as this one with 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;
}
7
  • I do not see any exec() command, with will be the one executing the shell command. Commented Feb 16, 2013 at 14:40
  • proc_open, doesn't it execute $command in shell? Commented Feb 16, 2013 at 14:43
  • @fedorqui $proc = proc_open( Commented Feb 16, 2013 at 14:43
  • You are right! Excuse me, I did not know this function. Commented Feb 16, 2013 at 14:44
  • 1
    So what about executing a basic runCommand("ls -l /tmp")? Commented Feb 16, 2013 at 14:48

1 Answer 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.