4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Process\Tests;
14 use PHPUnit\Framework\TestCase;
15 use Symfony\Component\Process\Exception\LogicException;
16 use Symfony\Component\Process\Exception\ProcessTimedOutException;
17 use Symfony\Component\Process\Exception\RuntimeException;
18 use Symfony\Component\Process\InputStream;
19 use Symfony\Component\Process\PhpExecutableFinder;
20 use Symfony\Component\Process\Pipes\PipesInterface;
21 use Symfony\Component\Process\Process;
24 * @author Robert Schönthal <seroscho@googlemail.com>
26 class ProcessTest extends TestCase
28 private static $phpBin;
29 private static $process;
30 private static $sigchild;
31 private static $notEnhancedSigchild = false;
33 public static function setUpBeforeClass()
35 $phpBin = new PhpExecutableFinder();
36 self::$phpBin = getenv('SYMFONY_PROCESS_PHP_TEST_BINARY') ?: ('phpdbg' === PHP_SAPI ? 'php' : $phpBin->find());
37 if ('\\' !== DIRECTORY_SEPARATOR) {
38 // exec is mandatory to deal with sending a signal to the process
39 // see https://github.com/symfony/symfony/issues/5030 about prepending
41 self::$phpBin = 'exec '.self::$phpBin;
45 phpinfo(INFO_GENERAL);
46 self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
49 protected function tearDown()
52 self::$process->stop(0);
53 self::$process = null;
57 public function testThatProcessDoesNotThrowWarningDuringRun()
59 if ('\\' === DIRECTORY_SEPARATOR) {
60 $this->markTestSkipped('This test is transient on Windows');
62 @trigger_error('Test Error', E_USER_NOTICE);
63 $process = $this->getProcess(self::$phpBin." -r 'sleep(3)'");
65 $actualError = error_get_last();
66 $this->assertEquals('Test Error', $actualError['message']);
67 $this->assertEquals(E_USER_NOTICE, $actualError['type']);
71 * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
73 public function testNegativeTimeoutFromConstructor()
75 $this->getProcess('', null, null, null, -1);
79 * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
81 public function testNegativeTimeoutFromSetter()
83 $p = $this->getProcess('');
87 public function testFloatAndNullTimeout()
89 $p = $this->getProcess('');
92 $this->assertSame(10.0, $p->getTimeout());
95 $this->assertNull($p->getTimeout());
98 $this->assertNull($p->getTimeout());
102 * @requires extension pcntl
104 public function testStopWithTimeoutIsActuallyWorking()
106 $p = $this->getProcess(self::$phpBin.' '.__DIR__.'/NonStopableProcess.php 30');
109 while (false === strpos($p->getOutput(), 'received')) {
112 $start = microtime(true);
117 $this->assertLessThan(15, microtime(true) - $start);
120 public function testAllOutputIsActuallyReadOnTermination()
122 // this code will result in a maximum of 2 reads of 8192 bytes by calling
123 // start() and isRunning(). by the time getOutput() is called the process
124 // has terminated so the internal pipes array is already empty. normally
125 // the call to start() will not read any data as the process will not have
126 // generated output, but this is non-deterministic so we must count it as
127 // a possibility. therefore we need 2 * PipesInterface::CHUNK_SIZE plus
128 // another byte which will never be read.
129 $expectedOutputSize = PipesInterface::CHUNK_SIZE * 2 + 2;
131 $code = sprintf('echo str_repeat(\'*\', %d);', $expectedOutputSize);
132 $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg($code)));
136 // Don't call Process::run nor Process::wait to avoid any read of pipes
137 $h = new \ReflectionProperty($p, 'process');
138 $h->setAccessible(true);
139 $h = $h->getValue($p);
140 $s = @proc_get_status($h);
142 while (!empty($s['running'])) {
144 $s = proc_get_status($h);
147 $o = $p->getOutput();
149 $this->assertEquals($expectedOutputSize, strlen($o));
152 public function testCallbacksAreExecutedWithStart()
154 $process = $this->getProcess('echo foo');
155 $process->start(function ($type, $buffer) use (&$data) {
161 $this->assertSame('foo'.PHP_EOL, $data);
165 * tests results from sub processes.
167 * @dataProvider responsesCodeProvider
169 public function testProcessResponses($expected, $getter, $code)
171 $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg($code)));
174 $this->assertSame($expected, $p->$getter());
178 * tests results from sub processes.
180 * @dataProvider pipesCodeProvider
182 public function testProcessPipes($code, $size)
184 $expected = str_repeat(str_repeat('*', 1024), $size).'!';
185 $expectedLength = (1024 * $size) + 1;
187 $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg($code)));
188 $p->setInput($expected);
191 $this->assertEquals($expectedLength, strlen($p->getOutput()));
192 $this->assertEquals($expectedLength, strlen($p->getErrorOutput()));
196 * @dataProvider pipesCodeProvider
198 public function testSetStreamAsInput($code, $size)
200 $expected = str_repeat(str_repeat('*', 1024), $size).'!';
201 $expectedLength = (1024 * $size) + 1;
203 $stream = fopen('php://temporary', 'w+');
204 fwrite($stream, $expected);
207 $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg($code)));
208 $p->setInput($stream);
213 $this->assertEquals($expectedLength, strlen($p->getOutput()));
214 $this->assertEquals($expectedLength, strlen($p->getErrorOutput()));
217 public function testLiveStreamAsInput()
219 $stream = fopen('php://memory', 'r+');
220 fwrite($stream, 'hello');
223 $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('stream_copy_to_stream(STDIN, STDOUT);')));
224 $p->setInput($stream);
225 $p->start(function ($type, $data) use ($stream) {
226 if ('hello' === $data) {
232 $this->assertSame('hello', $p->getOutput());
236 * @expectedException \Symfony\Component\Process\Exception\LogicException
237 * @expectedExceptionMessage Input can not be set while the process is running.
239 public function testSetInputWhileRunningThrowsAnException()
241 $process = $this->getProcess(self::$phpBin.' -r "sleep(30);"');
244 $process->setInput('foobar');
246 $this->fail('A LogicException should have been raised.');
247 } catch (LogicException $e) {
255 * @dataProvider provideInvalidInputValues
256 * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
257 * @expectedExceptionMessage Symfony\Component\Process\Process::setInput only accepts strings, Traversable objects or stream resources.
259 public function testInvalidInput($value)
261 $process = $this->getProcess('foo');
262 $process->setInput($value);
265 public function provideInvalidInputValues()
269 array(new NonStringifiable()),
274 * @dataProvider provideInputValues
276 public function testValidInput($expected, $value)
278 $process = $this->getProcess('foo');
279 $process->setInput($value);
280 $this->assertSame($expected, $process->getInput());
283 public function provideInputValues()
288 array('input data', 'input data'),
292 public function chainedCommandsOutputProvider()
294 if ('\\' === DIRECTORY_SEPARATOR) {
296 array("2 \r\n2\r\n", '&&', '2'),
301 array("1\n1\n", ';', '1'),
302 array("2\n2\n", '&&', '2'),
307 * @dataProvider chainedCommandsOutputProvider
309 public function testChainedCommandsOutput($expected, $operator, $input)
311 $process = $this->getProcess(sprintf('echo %s %s echo %s', $input, $operator, $input));
313 $this->assertEquals($expected, $process->getOutput());
316 public function testCallbackIsExecutedForOutput()
318 $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('echo \'foo\';')));
321 $p->run(function ($type, $buffer) use (&$called) {
322 $called = $buffer === 'foo';
325 $this->assertTrue($called, 'The callback should be executed with the output');
328 public function testCallbackIsExecutedForOutputWheneverOutputIsDisabled()
330 $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('echo \'foo\';')));
334 $p->run(function ($type, $buffer) use (&$called) {
335 $called = $buffer === 'foo';
338 $this->assertTrue($called, 'The callback should be executed with the output');
341 public function testGetErrorOutput()
343 $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }')));
346 $this->assertEquals(3, preg_match_all('/ERROR/', $p->getErrorOutput(), $matches));
349 public function testFlushErrorOutput()
351 $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }')));
354 $p->clearErrorOutput();
355 $this->assertEmpty($p->getErrorOutput());
359 * @dataProvider provideIncrementalOutput
361 public function testIncrementalOutput($getOutput, $getIncrementalOutput, $uri)
363 $lock = tempnam(sys_get_temp_dir(), __FUNCTION__);
365 $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('file_put_contents($s = \''.$uri.'\', \'foo\'); flock(fopen('.var_export($lock, true).', \'r\'), LOCK_EX); file_put_contents($s, \'bar\');')));
367 $h = fopen($lock, 'w');
372 foreach (array('foo', 'bar') as $s) {
373 while (false === strpos($p->$getOutput(), $s)) {
377 $this->assertSame($s, $p->$getIncrementalOutput());
378 $this->assertSame('', $p->$getIncrementalOutput());
386 public function provideIncrementalOutput()
389 array('getOutput', 'getIncrementalOutput', 'php://stdout'),
390 array('getErrorOutput', 'getIncrementalErrorOutput', 'php://stderr'),
394 public function testGetOutput()
396 $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('$n = 0; while ($n < 3) { echo \' foo \'; $n++; }')));
399 $this->assertEquals(3, preg_match_all('/foo/', $p->getOutput(), $matches));
402 public function testFlushOutput()
404 $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('$n=0;while ($n<3) {echo \' foo \';$n++;}')));
408 $this->assertEmpty($p->getOutput());
411 public function testZeroAsOutput()
413 if ('\\' === DIRECTORY_SEPARATOR) {
414 // see http://stackoverflow.com/questions/7105433/windows-batch-echo-without-new-line
415 $p = $this->getProcess('echo | set /p dummyName=0');
417 $p = $this->getProcess('printf 0');
421 $this->assertSame('0', $p->getOutput());
424 public function testExitCodeCommandFailed()
426 if ('\\' === DIRECTORY_SEPARATOR) {
427 $this->markTestSkipped('Windows does not support POSIX exit code');
429 $this->skipIfNotEnhancedSigchild();
431 // such command run in bash return an exitcode 127
432 $process = $this->getProcess('nonexistingcommandIhopeneversomeonewouldnameacommandlikethis');
435 $this->assertGreaterThan(0, $process->getExitCode());
441 public function testTTYCommand()
443 if ('\\' === DIRECTORY_SEPARATOR) {
444 $this->markTestSkipped('Windows does not have /dev/tty support');
447 $process = $this->getProcess('echo "foo" >> /dev/null && '.self::$phpBin.' -r "usleep(100000);"');
448 $process->setTty(true);
450 $this->assertTrue($process->isRunning());
453 $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
459 public function testTTYCommandExitCode()
461 if ('\\' === DIRECTORY_SEPARATOR) {
462 $this->markTestSkipped('Windows does have /dev/tty support');
464 $this->skipIfNotEnhancedSigchild();
466 $process = $this->getProcess('echo "foo" >> /dev/null');
467 $process->setTty(true);
470 $this->assertTrue($process->isSuccessful());
474 * @expectedException \Symfony\Component\Process\Exception\RuntimeException
475 * @expectedExceptionMessage TTY mode is not supported on Windows platform.
477 public function testTTYInWindowsEnvironment()
479 if ('\\' !== DIRECTORY_SEPARATOR) {
480 $this->markTestSkipped('This test is for Windows platform only');
483 $process = $this->getProcess('echo "foo" >> /dev/null');
484 $process->setTty(false);
485 $process->setTty(true);
488 public function testExitCodeTextIsNullWhenExitCodeIsNull()
490 $this->skipIfNotEnhancedSigchild();
492 $process = $this->getProcess('');
493 $this->assertNull($process->getExitCodeText());
496 public function testPTYCommand()
498 if (!Process::isPtySupported()) {
499 $this->markTestSkipped('PTY is not supported on this operating system.');
502 $process = $this->getProcess('echo "foo"');
503 $process->setPty(true);
506 $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
507 $this->assertEquals("foo\r\n", $process->getOutput());
510 public function testMustRun()
512 $this->skipIfNotEnhancedSigchild();
514 $process = $this->getProcess('echo foo');
516 $this->assertSame($process, $process->mustRun());
517 $this->assertEquals('foo'.PHP_EOL, $process->getOutput());
520 public function testSuccessfulMustRunHasCorrectExitCode()
522 $this->skipIfNotEnhancedSigchild();
524 $process = $this->getProcess('echo foo')->mustRun();
525 $this->assertEquals(0, $process->getExitCode());
529 * @expectedException \Symfony\Component\Process\Exception\ProcessFailedException
531 public function testMustRunThrowsException()
533 $this->skipIfNotEnhancedSigchild();
535 $process = $this->getProcess('exit 1');
539 public function testExitCodeText()
541 $this->skipIfNotEnhancedSigchild();
543 $process = $this->getProcess('');
544 $r = new \ReflectionObject($process);
545 $p = $r->getProperty('exitcode');
546 $p->setAccessible(true);
548 $p->setValue($process, 2);
549 $this->assertEquals('Misuse of shell builtins', $process->getExitCodeText());
552 public function testStartIsNonBlocking()
554 $process = $this->getProcess(self::$phpBin.' -r "usleep(500000);"');
555 $start = microtime(true);
557 $end = microtime(true);
558 $this->assertLessThan(0.4, $end - $start);
562 public function testUpdateStatus()
564 $process = $this->getProcess('echo foo');
566 $this->assertTrue(strlen($process->getOutput()) > 0);
569 public function testGetExitCodeIsNullOnStart()
571 $this->skipIfNotEnhancedSigchild();
573 $process = $this->getProcess(self::$phpBin.' -r "usleep(100000);"');
574 $this->assertNull($process->getExitCode());
576 $this->assertNull($process->getExitCode());
578 $this->assertEquals(0, $process->getExitCode());
581 public function testGetExitCodeIsNullOnWhenStartingAgain()
583 $this->skipIfNotEnhancedSigchild();
585 $process = $this->getProcess(self::$phpBin.' -r "usleep(100000);"');
587 $this->assertEquals(0, $process->getExitCode());
589 $this->assertNull($process->getExitCode());
591 $this->assertEquals(0, $process->getExitCode());
594 public function testGetExitCode()
596 $this->skipIfNotEnhancedSigchild();
598 $process = $this->getProcess('echo foo');
600 $this->assertSame(0, $process->getExitCode());
603 public function testStatus()
605 $process = $this->getProcess(self::$phpBin.' -r "usleep(100000);"');
606 $this->assertFalse($process->isRunning());
607 $this->assertFalse($process->isStarted());
608 $this->assertFalse($process->isTerminated());
609 $this->assertSame(Process::STATUS_READY, $process->getStatus());
611 $this->assertTrue($process->isRunning());
612 $this->assertTrue($process->isStarted());
613 $this->assertFalse($process->isTerminated());
614 $this->assertSame(Process::STATUS_STARTED, $process->getStatus());
616 $this->assertFalse($process->isRunning());
617 $this->assertTrue($process->isStarted());
618 $this->assertTrue($process->isTerminated());
619 $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
622 public function testStop()
624 $process = $this->getProcess(self::$phpBin.' -r "sleep(31);"');
626 $this->assertTrue($process->isRunning());
628 $this->assertFalse($process->isRunning());
631 public function testIsSuccessful()
633 $this->skipIfNotEnhancedSigchild();
635 $process = $this->getProcess('echo foo');
637 $this->assertTrue($process->isSuccessful());
640 public function testIsSuccessfulOnlyAfterTerminated()
642 $this->skipIfNotEnhancedSigchild();
644 $process = $this->getProcess(self::$phpBin.' -r "usleep(100000);"');
647 $this->assertFalse($process->isSuccessful());
651 $this->assertTrue($process->isSuccessful());
654 public function testIsNotSuccessful()
656 $this->skipIfNotEnhancedSigchild();
658 $process = $this->getProcess(self::$phpBin.' -r "throw new \Exception(\'BOUM\');"');
660 $this->assertFalse($process->isSuccessful());
663 public function testProcessIsNotSignaled()
665 if ('\\' === DIRECTORY_SEPARATOR) {
666 $this->markTestSkipped('Windows does not support POSIX signals');
668 $this->skipIfNotEnhancedSigchild();
670 $process = $this->getProcess('echo foo');
672 $this->assertFalse($process->hasBeenSignaled());
675 public function testProcessWithoutTermSignal()
677 if ('\\' === DIRECTORY_SEPARATOR) {
678 $this->markTestSkipped('Windows does not support POSIX signals');
680 $this->skipIfNotEnhancedSigchild();
682 $process = $this->getProcess('echo foo');
684 $this->assertEquals(0, $process->getTermSignal());
687 public function testProcessIsSignaledIfStopped()
689 if ('\\' === DIRECTORY_SEPARATOR) {
690 $this->markTestSkipped('Windows does not support POSIX signals');
692 $this->skipIfNotEnhancedSigchild();
694 $process = $this->getProcess(self::$phpBin.' -r "sleep(32);"');
697 $this->assertTrue($process->hasBeenSignaled());
698 $this->assertEquals(15, $process->getTermSignal()); // SIGTERM
702 * @expectedException \Symfony\Component\Process\Exception\RuntimeException
703 * @expectedExceptionMessage The process has been signaled
705 public function testProcessThrowsExceptionWhenExternallySignaled()
707 if (!function_exists('posix_kill')) {
708 $this->markTestSkipped('Function posix_kill is required.');
710 $this->skipIfNotEnhancedSigchild(false);
712 $process = $this->getProcess(self::$phpBin.' -r "sleep(32.1)"');
714 posix_kill($process->getPid(), 9); // SIGKILL
719 public function testRestart()
721 $process1 = $this->getProcess(self::$phpBin.' -r "echo getmypid();"');
723 $process2 = $process1->restart();
725 $process2->wait(); // wait for output
727 // Ensure that both processed finished and the output is numeric
728 $this->assertFalse($process1->isRunning());
729 $this->assertFalse($process2->isRunning());
730 $this->assertInternalType('numeric', $process1->getOutput());
731 $this->assertInternalType('numeric', $process2->getOutput());
733 // Ensure that restart returned a new process by check that the output is different
734 $this->assertNotEquals($process1->getOutput(), $process2->getOutput());
738 * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
739 * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
741 public function testRunProcessWithTimeout()
743 $process = $this->getProcess(self::$phpBin.' -r "sleep(30);"');
744 $process->setTimeout(0.1);
745 $start = microtime(true);
748 $this->fail('A RuntimeException should have been raised');
749 } catch (RuntimeException $e) {
752 $this->assertLessThan(15, microtime(true) - $start);
758 * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
759 * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
761 public function testIterateOverProcessWithTimeout()
763 $process = $this->getProcess(self::$phpBin.' -r "sleep(30);"');
764 $process->setTimeout(0.1);
765 $start = microtime(true);
768 foreach ($process as $buffer);
769 $this->fail('A RuntimeException should have been raised');
770 } catch (RuntimeException $e) {
773 $this->assertLessThan(15, microtime(true) - $start);
778 public function testCheckTimeoutOnNonStartedProcess()
780 $process = $this->getProcess('echo foo');
781 $this->assertNull($process->checkTimeout());
784 public function testCheckTimeoutOnTerminatedProcess()
786 $process = $this->getProcess('echo foo');
788 $this->assertNull($process->checkTimeout());
792 * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
793 * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
795 public function testCheckTimeoutOnStartedProcess()
797 $process = $this->getProcess(self::$phpBin.' -r "sleep(33);"');
798 $process->setTimeout(0.1);
801 $start = microtime(true);
804 while ($process->isRunning()) {
805 $process->checkTimeout();
808 $this->fail('A ProcessTimedOutException should have been raised');
809 } catch (ProcessTimedOutException $e) {
812 $this->assertLessThan(15, microtime(true) - $start);
817 public function testIdleTimeout()
819 $process = $this->getProcess(self::$phpBin.' -r "sleep(34);"');
820 $process->setTimeout(60);
821 $process->setIdleTimeout(0.1);
826 $this->fail('A timeout exception was expected.');
827 } catch (ProcessTimedOutException $e) {
828 $this->assertTrue($e->isIdleTimeout());
829 $this->assertFalse($e->isGeneralTimeout());
830 $this->assertEquals(0.1, $e->getExceededTimeout());
834 public function testIdleTimeoutNotExceededWhenOutputIsSent()
836 $process = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('while (true) {echo \'foo \'; usleep(1000);}')));
837 $process->setTimeout(1);
840 while (false === strpos($process->getOutput(), 'foo')) {
844 $process->setIdleTimeout(0.5);
848 $this->fail('A timeout exception was expected.');
849 } catch (ProcessTimedOutException $e) {
850 $this->assertTrue($e->isGeneralTimeout(), 'A general timeout is expected.');
851 $this->assertFalse($e->isIdleTimeout(), 'No idle timeout is expected.');
852 $this->assertEquals(1, $e->getExceededTimeout());
857 * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
858 * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
860 public function testStartAfterATimeout()
862 $process = $this->getProcess(self::$phpBin.' -r "sleep(35);"');
863 $process->setTimeout(0.1);
867 $this->fail('A ProcessTimedOutException should have been raised.');
868 } catch (ProcessTimedOutException $e) {
870 $this->assertFalse($process->isRunning());
872 $this->assertTrue($process->isRunning());
878 public function testGetPid()
880 $process = $this->getProcess(self::$phpBin.' -r "sleep(36);"');
882 $this->assertGreaterThan(0, $process->getPid());
886 public function testGetPidIsNullBeforeStart()
888 $process = $this->getProcess('foo');
889 $this->assertNull($process->getPid());
892 public function testGetPidIsNullAfterRun()
894 $process = $this->getProcess('echo foo');
896 $this->assertNull($process->getPid());
900 * @requires extension pcntl
902 public function testSignal()
904 $process = $this->getProcess(self::$phpBin.' '.__DIR__.'/SignalListener.php');
907 while (false === strpos($process->getOutput(), 'Caught')) {
910 $process->signal(SIGUSR1);
913 $this->assertEquals('Caught SIGUSR1', $process->getOutput());
917 * @requires extension pcntl
919 public function testExitCodeIsAvailableAfterSignal()
921 $this->skipIfNotEnhancedSigchild();
923 $process = $this->getProcess('sleep 4');
925 $process->signal(SIGKILL);
927 while ($process->isRunning()) {
931 $this->assertFalse($process->isRunning());
932 $this->assertTrue($process->hasBeenSignaled());
933 $this->assertFalse($process->isSuccessful());
934 $this->assertEquals(137, $process->getExitCode());
938 * @expectedException \Symfony\Component\Process\Exception\LogicException
939 * @expectedExceptionMessage Can not send signal on a non running process.
941 public function testSignalProcessNotRunning()
943 $process = $this->getProcess('foo');
944 $process->signal(1); // SIGHUP
948 * @dataProvider provideMethodsThatNeedARunningProcess
950 public function testMethodsThatNeedARunningProcess($method)
952 $process = $this->getProcess('foo');
954 if (method_exists($this, 'expectException')) {
955 $this->expectException('Symfony\Component\Process\Exception\LogicException');
956 $this->expectExceptionMessage(sprintf('Process must be started before calling %s.', $method));
958 $this->setExpectedException('Symfony\Component\Process\Exception\LogicException', sprintf('Process must be started before calling %s.', $method));
961 $process->{$method}();
964 public function provideMethodsThatNeedARunningProcess()
968 array('getIncrementalOutput'),
969 array('getErrorOutput'),
970 array('getIncrementalErrorOutput'),
976 * @dataProvider provideMethodsThatNeedATerminatedProcess
977 * @expectedException \Symfony\Component\Process\Exception\LogicException
978 * @expectedExceptionMessage Process must be terminated before calling
980 public function testMethodsThatNeedATerminatedProcess($method)
982 $process = $this->getProcess(self::$phpBin.' -r "sleep(37);"');
985 $process->{$method}();
987 $this->fail('A LogicException must have been thrown');
988 } catch (\Exception $e) {
995 public function provideMethodsThatNeedATerminatedProcess()
998 array('hasBeenSignaled'),
999 array('getTermSignal'),
1000 array('hasBeenStopped'),
1001 array('getStopSignal'),
1006 * @dataProvider provideWrongSignal
1007 * @expectedException \Symfony\Component\Process\Exception\RuntimeException
1009 public function testWrongSignal($signal)
1011 if ('\\' === DIRECTORY_SEPARATOR) {
1012 $this->markTestSkipped('POSIX signals do not work on Windows');
1015 $process = $this->getProcess(self::$phpBin.' -r "sleep(38);"');
1018 $process->signal($signal);
1019 $this->fail('A RuntimeException must have been thrown');
1020 } catch (RuntimeException $e) {
1027 public function provideWrongSignal()
1031 array('Céphalopodes'),
1035 public function testDisableOutputDisablesTheOutput()
1037 $p = $this->getProcess('foo');
1038 $this->assertFalse($p->isOutputDisabled());
1039 $p->disableOutput();
1040 $this->assertTrue($p->isOutputDisabled());
1042 $this->assertFalse($p->isOutputDisabled());
1046 * @expectedException \Symfony\Component\Process\Exception\RuntimeException
1047 * @expectedExceptionMessage Disabling output while the process is running is not possible.
1049 public function testDisableOutputWhileRunningThrowsException()
1051 $p = $this->getProcess(self::$phpBin.' -r "sleep(39);"');
1053 $p->disableOutput();
1057 * @expectedException \Symfony\Component\Process\Exception\RuntimeException
1058 * @expectedExceptionMessage Enabling output while the process is running is not possible.
1060 public function testEnableOutputWhileRunningThrowsException()
1062 $p = $this->getProcess(self::$phpBin.' -r "sleep(40);"');
1063 $p->disableOutput();
1068 public function testEnableOrDisableOutputAfterRunDoesNotThrowException()
1070 $p = $this->getProcess('echo foo');
1071 $p->disableOutput();
1074 $p->disableOutput();
1075 $this->assertTrue($p->isOutputDisabled());
1079 * @expectedException \Symfony\Component\Process\Exception\LogicException
1080 * @expectedExceptionMessage Output can not be disabled while an idle timeout is set.
1082 public function testDisableOutputWhileIdleTimeoutIsSet()
1084 $process = $this->getProcess('foo');
1085 $process->setIdleTimeout(1);
1086 $process->disableOutput();
1090 * @expectedException \Symfony\Component\Process\Exception\LogicException
1091 * @expectedExceptionMessage timeout can not be set while the output is disabled.
1093 public function testSetIdleTimeoutWhileOutputIsDisabled()
1095 $process = $this->getProcess('foo');
1096 $process->disableOutput();
1097 $process->setIdleTimeout(1);
1100 public function testSetNullIdleTimeoutWhileOutputIsDisabled()
1102 $process = $this->getProcess('foo');
1103 $process->disableOutput();
1104 $this->assertSame($process, $process->setIdleTimeout(null));
1108 * @dataProvider provideOutputFetchingMethods
1109 * @expectedException \Symfony\Component\Process\Exception\LogicException
1110 * @expectedExceptionMessage Output has been disabled.
1112 public function testGetOutputWhileDisabled($fetchMethod)
1114 $p = $this->getProcess(self::$phpBin.' -r "sleep(41);"');
1115 $p->disableOutput();
1117 $p->{$fetchMethod}();
1120 public function provideOutputFetchingMethods()
1124 array('getIncrementalOutput'),
1125 array('getErrorOutput'),
1126 array('getIncrementalErrorOutput'),
1130 public function testStopTerminatesProcessCleanly()
1132 $process = $this->getProcess(self::$phpBin.' -r "echo 123; sleep(42);"');
1133 $process->run(function () use ($process) {
1136 $this->assertTrue(true, 'A call to stop() is not expected to cause wait() to throw a RuntimeException');
1139 public function testKillSignalTerminatesProcessCleanly()
1141 $process = $this->getProcess(self::$phpBin.' -r "echo 123; sleep(43);"');
1142 $process->run(function () use ($process) {
1143 $process->signal(9); // SIGKILL
1145 $this->assertTrue(true, 'A call to signal() is not expected to cause wait() to throw a RuntimeException');
1148 public function testTermSignalTerminatesProcessCleanly()
1150 $process = $this->getProcess(self::$phpBin.' -r "echo 123; sleep(44);"');
1151 $process->run(function () use ($process) {
1152 $process->signal(15); // SIGTERM
1154 $this->assertTrue(true, 'A call to signal() is not expected to cause wait() to throw a RuntimeException');
1157 public function responsesCodeProvider()
1160 //expected output / getter / code to execute
1161 //array(1,'getExitCode','exit(1);'),
1162 //array(true,'isSuccessful','exit();'),
1163 array('output', 'getOutput', 'echo \'output\';'),
1167 public function pipesCodeProvider()
1169 $variations = array(
1170 'fwrite(STDOUT, $in = file_get_contents(\'php://stdin\')); fwrite(STDERR, $in);',
1171 'include \''.__DIR__.'/PipeStdinInStdoutStdErrStreamSelect.php\';',
1174 if ('\\' === DIRECTORY_SEPARATOR) {
1175 // Avoid XL buffers on Windows because of https://bugs.php.net/bug.php?id=65650
1176 $sizes = array(1, 2, 4, 8);
1178 $sizes = array(1, 16, 64, 1024, 4096);
1182 foreach ($sizes as $size) {
1183 foreach ($variations as $code) {
1184 $codes[] = array($code, $size);
1192 * @dataProvider provideVariousIncrementals
1194 public function testIncrementalOutputDoesNotRequireAnotherCall($stream, $method)
1196 $process = $this->getProcess(self::$phpBin.' -r '.escapeshellarg('$n = 0; while ($n < 3) { file_put_contents(\''.$stream.'\', $n, 1); $n++; usleep(1000); }'), null, null, null, null);
1199 $limit = microtime(true) + 3;
1202 while ($result !== $expected && microtime(true) < $limit) {
1203 $result .= $process->$method();
1206 $this->assertSame($expected, $result);
1210 public function provideVariousIncrementals()
1213 array('php://stdout', 'getIncrementalOutput'),
1214 array('php://stderr', 'getIncrementalErrorOutput'),
1218 public function testIteratorInput()
1220 $input = function () {
1225 $process = $this->getProcess(self::$phpBin.' -r '.escapeshellarg('stream_copy_to_stream(STDIN, STDOUT);'), null, null, $input());
1227 $this->assertSame('pingpong', $process->getOutput());
1230 public function testSimpleInputStream()
1232 $input = new InputStream();
1234 $process = $this->getProcess(self::$phpBin.' -r '.escapeshellarg('echo \'ping\'; stream_copy_to_stream(STDIN, STDOUT);'));
1235 $process->setInput($input);
1237 $process->start(function ($type, $data) use ($input) {
1238 if ('ping' === $data) {
1239 $input->write('pang');
1240 } elseif (!$input->isClosed()) {
1241 $input->write('pong');
1247 $this->assertSame('pingpangpong', $process->getOutput());
1250 public function testInputStreamWithCallable()
1253 $stream = fopen('php://memory', 'w+');
1254 $stream = function () use ($stream, &$i) {
1257 fwrite($stream, ++$i);
1264 $input = new InputStream();
1265 $input->onEmpty($stream);
1266 $input->write($stream());
1268 $process = $this->getProcess(self::$phpBin.' -r '.escapeshellarg('echo fread(STDIN, 3);'));
1269 $process->setInput($input);
1270 $process->start(function ($type, $data) use ($input) {
1275 $this->assertSame('123', $process->getOutput());
1278 public function testInputStreamWithGenerator()
1280 $input = new InputStream();
1281 $input->onEmpty(function ($input) {
1286 $process = $this->getProcess(self::$phpBin.' -r '.escapeshellarg('stream_copy_to_stream(STDIN, STDOUT);'));
1287 $process->setInput($input);
1289 $input->write('ping');
1291 $this->assertSame('pingpong', $process->getOutput());
1294 public function testInputStreamOnEmpty()
1297 $input = new InputStream();
1298 $input->onEmpty(function () use (&$i) { ++$i; });
1300 $process = $this->getProcess(self::$phpBin.' -r '.escapeshellarg('echo 123; echo fread(STDIN, 1); echo 456;'));
1301 $process->setInput($input);
1302 $process->start(function ($type, $data) use ($input) {
1303 if ('123' === $data) {
1309 $this->assertSame(0, $i, 'InputStream->onEmpty callback should be called only when the input *becomes* empty');
1310 $this->assertSame('123456', $process->getOutput());
1313 public function testIteratorOutput()
1315 $input = new InputStream();
1317 $process = $this->getProcess(self::$phpBin.' -r '.escapeshellarg('fwrite(STDOUT, 123); fwrite(STDERR, 234); flush(); usleep(10000); fwrite(STDOUT, fread(STDIN, 3)); fwrite(STDERR, 456);'));
1318 $process->setInput($input);
1322 foreach ($process as $type => $data) {
1323 $output[] = array($type, $data);
1326 $expectedOutput = array(
1327 array($process::OUT, '123'),
1329 $this->assertSame($expectedOutput, $output);
1333 foreach ($process as $type => $data) {
1334 $output[] = array($type, $data);
1337 $this->assertSame('', $process->getOutput());
1338 $this->assertFalse($process->isRunning());
1340 $expectedOutput = array(
1341 array($process::OUT, '123'),
1342 array($process::ERR, '234'),
1343 array($process::OUT, '345'),
1344 array($process::ERR, '456'),
1346 $this->assertSame($expectedOutput, $output);
1349 public function testNonBlockingNorClearingIteratorOutput()
1351 $input = new InputStream();
1353 $process = $this->getProcess(self::$phpBin.' -r '.escapeshellarg('fwrite(STDOUT, fread(STDIN, 3));'));
1354 $process->setInput($input);
1358 foreach ($process->getIterator($process::ITER_NON_BLOCKING | $process::ITER_KEEP_OUTPUT) as $type => $data) {
1359 $output[] = array($type, $data);
1362 $expectedOutput = array(
1363 array($process::OUT, ''),
1365 $this->assertSame($expectedOutput, $output);
1369 foreach ($process->getIterator($process::ITER_NON_BLOCKING | $process::ITER_KEEP_OUTPUT) as $type => $data) {
1371 $output[] = array($type, $data);
1375 $this->assertSame('123', $process->getOutput());
1376 $this->assertFalse($process->isRunning());
1378 $expectedOutput = array(
1379 array($process::OUT, ''),
1380 array($process::OUT, '123'),
1382 $this->assertSame($expectedOutput, $output);
1385 public function testChainedProcesses()
1387 $p1 = new Process(self::$phpBin.' -r '.escapeshellarg('fwrite(STDERR, 123); fwrite(STDOUT, 456);'));
1388 $p2 = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('stream_copy_to_stream(STDIN, STDOUT);')));
1394 $this->assertSame('123', $p1->getErrorOutput());
1395 $this->assertSame('', $p1->getOutput());
1396 $this->assertSame('', $p2->getErrorOutput());
1397 $this->assertSame('456', $p2->getOutput());
1400 public function testSetBadEnv()
1402 $process = $this->getProcess('echo hello');
1403 $process->setEnv(array('bad%%' => '123'));
1404 $process->inheritEnvironmentVariables(true);
1408 $this->assertSame('hello'.PHP_EOL, $process->getOutput());
1409 $this->assertSame('', $process->getErrorOutput());
1412 public function testEnvBackupDoesNotDeleteExistingVars()
1414 putenv('existing_var=foo');
1415 $process = $this->getProcess('php -r "echo getenv(\'new_test_var\');"');
1416 $process->setEnv(array('existing_var' => 'bar', 'new_test_var' => 'foo'));
1417 $process->inheritEnvironmentVariables();
1421 $this->assertSame('foo', $process->getOutput());
1422 $this->assertSame('foo', getenv('existing_var'));
1423 $this->assertFalse(getenv('new_test_var'));
1426 public function testInheritEnvEnabled()
1428 $process = $this->getProcess(self::$phpBin.' -r '.escapeshellarg('echo serialize($_SERVER);'), null, array('BAR' => 'BAZ'));
1432 $this->assertSame($process, $process->inheritEnvironmentVariables(1));
1433 $this->assertTrue($process->areEnvironmentVariablesInherited());
1437 $expected = array('BAR' => 'BAZ', 'FOO' => 'BAR');
1438 $env = array_intersect_key(unserialize($process->getOutput()), $expected);
1440 $this->assertEquals($expected, $env);
1443 public function testInheritEnvDisabled()
1445 $process = $this->getProcess(self::$phpBin.' -r '.escapeshellarg('echo serialize($_SERVER);'), null, array('BAR' => 'BAZ'));
1449 $this->assertFalse($process->areEnvironmentVariablesInherited());
1453 $expected = array('BAR' => 'BAZ', 'FOO' => 'BAR');
1454 $env = array_intersect_key(unserialize($process->getOutput()), $expected);
1455 unset($expected['FOO']);
1457 $this->assertSame($expected, $env);
1461 * @param string $commandline
1462 * @param null|string $cwd
1463 * @param null|array $env
1464 * @param null|string $input
1465 * @param int $timeout
1466 * @param array $options
1470 private function getProcess($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60, array $options = array())
1472 $process = new Process($commandline, $cwd, $env, $input, $timeout, $options);
1474 if (false !== $enhance = getenv('ENHANCE_SIGCHLD')) {
1476 $process->setEnhanceSigchildCompatibility(false);
1477 $process->getExitCode();
1478 $this->fail('ENHANCE_SIGCHLD must be used together with a sigchild-enabled PHP.');
1479 } catch (RuntimeException $e) {
1480 $this->assertSame('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.', $e->getMessage());
1482 $process->setEnhanceSigchildCompatibility(true);
1484 self::$notEnhancedSigchild = true;
1489 if (self::$process) {
1490 self::$process->stop(0);
1493 return self::$process = $process;
1496 private function skipIfNotEnhancedSigchild($expectException = true)
1498 if (self::$sigchild) {
1499 if (!$expectException) {
1500 $this->markTestSkipped('PHP is compiled with --enable-sigchild.');
1501 } elseif (self::$notEnhancedSigchild) {
1502 if (method_exists($this, 'expectException')) {
1503 $this->expectException('Symfony\Component\Process\Exception\RuntimeException');
1504 $this->expectExceptionMessage('This PHP has been compiled with --enable-sigchild.');
1506 $this->setExpectedException('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild.');
1513 class NonStringifiable