A
A
Askar Fuzaylov2015-06-20 14:56:46
PHP
Askar Fuzaylov, 2015-06-20 14:56:46

How to test code that works with shell commands?

How to test classes and methods that use such a method?

protected function exec()
    {
        $descriptorSpec = array(
            0 => array('pipe', 'r'),
            1 => array('pipe', 'w'),
            2 => array('pipe', 'a')
        );

        Response::addRecord('Command: ' . $this->getCommand());
        $process = proc_open($this->getCommand(), $descriptorSpec, $pipes, $this->directory);
        if (is_resource($process)) {
            Response::addRecord('Response: ' . stream_get_contents($pipes[1]));
            fclose($pipes[1]);

            return proc_close($process);
        }

        return false;
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
D', 2015-06-20
@Denormalization

I would make a wrapper to work with proc_open\proc_close\etc...
Then you can just lock this wrapper and only test the logic.

D
Dmitry, 2015-06-20
@EvilsInterrupt

Well, you yourself have formulated the answer to your question. I'll try to explain. A unit test, a good test, has the quality of being easy to write! Even the question will not arise, about how to write something? If writing is difficult, then you may be trying to write a test for code that performs more than one task!
Now I see that at least two unrelated actions will be performed in your method:
1. Creating a descriptor
2. Performing some action using this descriptor
They must be tested separately! For action #1 you can write tests:
1. Positive: when 0, 1, 2
2. Negative: when less than zero or greater than 2
For action #2: You can also write at least two tests with a valid and invalid descriptor

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question