da74a3db225af2c7a30e457c38d80a7784816a27
[yaffs-website] / ProcessTest.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\Process\Tests;
13
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;
22
23 /**
24  * @author Robert Schönthal <seroscho@googlemail.com>
25  */
26 class ProcessTest extends TestCase
27 {
28     private static $phpBin;
29     private static $process;
30     private static $sigchild;
31     private static $notEnhancedSigchild = false;
32
33     public static function setUpBeforeClass()
34     {
35         $phpBin = new PhpExecutableFinder();
36         self::$phpBin = getenv('SYMFONY_PROCESS_PHP_TEST_BINARY') ?: ('phpdbg' === \PHP_SAPI ? 'php' : $phpBin->find());
37
38         ob_start();
39         phpinfo(INFO_GENERAL);
40         self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
41     }
42
43     protected function tearDown()
44     {
45         if (self::$process) {
46             self::$process->stop(0);
47             self::$process = null;
48         }
49     }
50
51     /**
52      * @group legacy
53      * @expectedDeprecation The provided cwd does not exist. Command is currently ran against getcwd(). This behavior is deprecated since Symfony 3.4 and will be removed in 4.0.
54      */
55     public function testInvalidCwd()
56     {
57         if ('\\' === \DIRECTORY_SEPARATOR) {
58             $this->markTestSkipped('False-positive on Windows/appveyor.');
59         }
60
61         // Check that it works fine if the CWD exists
62         $cmd = new Process('echo test', __DIR__);
63         $cmd->run();
64
65         $cmd = new Process('echo test', __DIR__.'/notfound/');
66         $cmd->run();
67     }
68
69     public function testThatProcessDoesNotThrowWarningDuringRun()
70     {
71         if ('\\' === \DIRECTORY_SEPARATOR) {
72             $this->markTestSkipped('This test is transient on Windows');
73         }
74         @trigger_error('Test Error', E_USER_NOTICE);
75         $process = $this->getProcessForCode('sleep(3)');
76         $process->run();
77         $actualError = error_get_last();
78         $this->assertEquals('Test Error', $actualError['message']);
79         $this->assertEquals(E_USER_NOTICE, $actualError['type']);
80     }
81
82     /**
83      * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
84      */
85     public function testNegativeTimeoutFromConstructor()
86     {
87         $this->getProcess('', null, null, null, -1);
88     }
89
90     /**
91      * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
92      */
93     public function testNegativeTimeoutFromSetter()
94     {
95         $p = $this->getProcess('');
96         $p->setTimeout(-1);
97     }
98
99     public function testFloatAndNullTimeout()
100     {
101         $p = $this->getProcess('');
102
103         $p->setTimeout(10);
104         $this->assertSame(10.0, $p->getTimeout());
105
106         $p->setTimeout(null);
107         $this->assertNull($p->getTimeout());
108
109         $p->setTimeout(0.0);
110         $this->assertNull($p->getTimeout());
111     }
112
113     /**
114      * @requires extension pcntl
115      */
116     public function testStopWithTimeoutIsActuallyWorking()
117     {
118         $p = $this->getProcess(array(self::$phpBin, __DIR__.'/NonStopableProcess.php', 30));
119         $p->start();
120
121         while (false === strpos($p->getOutput(), 'received')) {
122             usleep(1000);
123         }
124         $start = microtime(true);
125         $p->stop(0.1);
126
127         $p->wait();
128
129         $this->assertLessThan(15, microtime(true) - $start);
130     }
131
132     public function testAllOutputIsActuallyReadOnTermination()
133     {
134         // this code will result in a maximum of 2 reads of 8192 bytes by calling
135         // start() and isRunning().  by the time getOutput() is called the process
136         // has terminated so the internal pipes array is already empty. normally
137         // the call to start() will not read any data as the process will not have
138         // generated output, but this is non-deterministic so we must count it as
139         // a possibility.  therefore we need 2 * PipesInterface::CHUNK_SIZE plus
140         // another byte which will never be read.
141         $expectedOutputSize = PipesInterface::CHUNK_SIZE * 2 + 2;
142
143         $code = sprintf('echo str_repeat(\'*\', %d);', $expectedOutputSize);
144         $p = $this->getProcessForCode($code);
145
146         $p->start();
147
148         // Don't call Process::run nor Process::wait to avoid any read of pipes
149         $h = new \ReflectionProperty($p, 'process');
150         $h->setAccessible(true);
151         $h = $h->getValue($p);
152         $s = @proc_get_status($h);
153
154         while (!empty($s['running'])) {
155             usleep(1000);
156             $s = proc_get_status($h);
157         }
158
159         $o = $p->getOutput();
160
161         $this->assertEquals($expectedOutputSize, \strlen($o));
162     }
163
164     public function testCallbacksAreExecutedWithStart()
165     {
166         $process = $this->getProcess('echo foo');
167         $process->start(function ($type, $buffer) use (&$data) {
168             $data .= $buffer;
169         });
170
171         $process->wait();
172
173         $this->assertSame('foo'.PHP_EOL, $data);
174     }
175
176     /**
177      * tests results from sub processes.
178      *
179      * @dataProvider responsesCodeProvider
180      */
181     public function testProcessResponses($expected, $getter, $code)
182     {
183         $p = $this->getProcessForCode($code);
184         $p->run();
185
186         $this->assertSame($expected, $p->$getter());
187     }
188
189     /**
190      * tests results from sub processes.
191      *
192      * @dataProvider pipesCodeProvider
193      */
194     public function testProcessPipes($code, $size)
195     {
196         $expected = str_repeat(str_repeat('*', 1024), $size).'!';
197         $expectedLength = (1024 * $size) + 1;
198
199         $p = $this->getProcessForCode($code);
200         $p->setInput($expected);
201         $p->run();
202
203         $this->assertEquals($expectedLength, \strlen($p->getOutput()));
204         $this->assertEquals($expectedLength, \strlen($p->getErrorOutput()));
205     }
206
207     /**
208      * @dataProvider pipesCodeProvider
209      */
210     public function testSetStreamAsInput($code, $size)
211     {
212         $expected = str_repeat(str_repeat('*', 1024), $size).'!';
213         $expectedLength = (1024 * $size) + 1;
214
215         $stream = fopen('php://temporary', 'w+');
216         fwrite($stream, $expected);
217         rewind($stream);
218
219         $p = $this->getProcessForCode($code);
220         $p->setInput($stream);
221         $p->run();
222
223         fclose($stream);
224
225         $this->assertEquals($expectedLength, \strlen($p->getOutput()));
226         $this->assertEquals($expectedLength, \strlen($p->getErrorOutput()));
227     }
228
229     public function testLiveStreamAsInput()
230     {
231         $stream = fopen('php://memory', 'r+');
232         fwrite($stream, 'hello');
233         rewind($stream);
234
235         $p = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);');
236         $p->setInput($stream);
237         $p->start(function ($type, $data) use ($stream) {
238             if ('hello' === $data) {
239                 fclose($stream);
240             }
241         });
242         $p->wait();
243
244         $this->assertSame('hello', $p->getOutput());
245     }
246
247     /**
248      * @expectedException \Symfony\Component\Process\Exception\LogicException
249      * @expectedExceptionMessage Input can not be set while the process is running.
250      */
251     public function testSetInputWhileRunningThrowsAnException()
252     {
253         $process = $this->getProcessForCode('sleep(30);');
254         $process->start();
255         try {
256             $process->setInput('foobar');
257             $process->stop();
258             $this->fail('A LogicException should have been raised.');
259         } catch (LogicException $e) {
260         }
261         $process->stop();
262
263         throw $e;
264     }
265
266     /**
267      * @dataProvider provideInvalidInputValues
268      * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
269      * @expectedExceptionMessage Symfony\Component\Process\Process::setInput only accepts strings, Traversable objects or stream resources.
270      */
271     public function testInvalidInput($value)
272     {
273         $process = $this->getProcess('foo');
274         $process->setInput($value);
275     }
276
277     public function provideInvalidInputValues()
278     {
279         return array(
280             array(array()),
281             array(new NonStringifiable()),
282         );
283     }
284
285     /**
286      * @dataProvider provideInputValues
287      */
288     public function testValidInput($expected, $value)
289     {
290         $process = $this->getProcess('foo');
291         $process->setInput($value);
292         $this->assertSame($expected, $process->getInput());
293     }
294
295     public function provideInputValues()
296     {
297         return array(
298             array(null, null),
299             array('24.5', 24.5),
300             array('input data', 'input data'),
301         );
302     }
303
304     public function chainedCommandsOutputProvider()
305     {
306         if ('\\' === \DIRECTORY_SEPARATOR) {
307             return array(
308                 array("2 \r\n2\r\n", '&&', '2'),
309             );
310         }
311
312         return array(
313             array("1\n1\n", ';', '1'),
314             array("2\n2\n", '&&', '2'),
315         );
316     }
317
318     /**
319      * @dataProvider chainedCommandsOutputProvider
320      */
321     public function testChainedCommandsOutput($expected, $operator, $input)
322     {
323         $process = $this->getProcess(sprintf('echo %s %s echo %s', $input, $operator, $input));
324         $process->run();
325         $this->assertEquals($expected, $process->getOutput());
326     }
327
328     public function testCallbackIsExecutedForOutput()
329     {
330         $p = $this->getProcessForCode('echo \'foo\';');
331
332         $called = false;
333         $p->run(function ($type, $buffer) use (&$called) {
334             $called = 'foo' === $buffer;
335         });
336
337         $this->assertTrue($called, 'The callback should be executed with the output');
338     }
339
340     public function testCallbackIsExecutedForOutputWheneverOutputIsDisabled()
341     {
342         $p = $this->getProcessForCode('echo \'foo\';');
343         $p->disableOutput();
344
345         $called = false;
346         $p->run(function ($type, $buffer) use (&$called) {
347             $called = 'foo' === $buffer;
348         });
349
350         $this->assertTrue($called, 'The callback should be executed with the output');
351     }
352
353     public function testGetErrorOutput()
354     {
355         $p = $this->getProcessForCode('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }');
356
357         $p->run();
358         $this->assertEquals(3, preg_match_all('/ERROR/', $p->getErrorOutput(), $matches));
359     }
360
361     public function testFlushErrorOutput()
362     {
363         $p = $this->getProcessForCode('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }');
364
365         $p->run();
366         $p->clearErrorOutput();
367         $this->assertEmpty($p->getErrorOutput());
368     }
369
370     /**
371      * @dataProvider provideIncrementalOutput
372      */
373     public function testIncrementalOutput($getOutput, $getIncrementalOutput, $uri)
374     {
375         $lock = tempnam(sys_get_temp_dir(), __FUNCTION__);
376
377         $p = $this->getProcessForCode('file_put_contents($s = \''.$uri.'\', \'foo\'); flock(fopen('.var_export($lock, true).', \'r\'), LOCK_EX); file_put_contents($s, \'bar\');');
378
379         $h = fopen($lock, 'w');
380         flock($h, LOCK_EX);
381
382         $p->start();
383
384         foreach (array('foo', 'bar') as $s) {
385             while (false === strpos($p->$getOutput(), $s)) {
386                 usleep(1000);
387             }
388
389             $this->assertSame($s, $p->$getIncrementalOutput());
390             $this->assertSame('', $p->$getIncrementalOutput());
391
392             flock($h, LOCK_UN);
393         }
394
395         fclose($h);
396     }
397
398     public function provideIncrementalOutput()
399     {
400         return array(
401             array('getOutput', 'getIncrementalOutput', 'php://stdout'),
402             array('getErrorOutput', 'getIncrementalErrorOutput', 'php://stderr'),
403         );
404     }
405
406     public function testGetOutput()
407     {
408         $p = $this->getProcessForCode('$n = 0; while ($n < 3) { echo \' foo \'; $n++; }');
409
410         $p->run();
411         $this->assertEquals(3, preg_match_all('/foo/', $p->getOutput(), $matches));
412     }
413
414     public function testFlushOutput()
415     {
416         $p = $this->getProcessForCode('$n=0;while ($n<3) {echo \' foo \';$n++;}');
417
418         $p->run();
419         $p->clearOutput();
420         $this->assertEmpty($p->getOutput());
421     }
422
423     public function testZeroAsOutput()
424     {
425         if ('\\' === \DIRECTORY_SEPARATOR) {
426             // see http://stackoverflow.com/questions/7105433/windows-batch-echo-without-new-line
427             $p = $this->getProcess('echo | set /p dummyName=0');
428         } else {
429             $p = $this->getProcess('printf 0');
430         }
431
432         $p->run();
433         $this->assertSame('0', $p->getOutput());
434     }
435
436     public function testExitCodeCommandFailed()
437     {
438         if ('\\' === \DIRECTORY_SEPARATOR) {
439             $this->markTestSkipped('Windows does not support POSIX exit code');
440         }
441         $this->skipIfNotEnhancedSigchild();
442
443         // such command run in bash return an exitcode 127
444         $process = $this->getProcess('nonexistingcommandIhopeneversomeonewouldnameacommandlikethis');
445         $process->run();
446
447         $this->assertGreaterThan(0, $process->getExitCode());
448     }
449
450     public function testTTYCommand()
451     {
452         if ('\\' === \DIRECTORY_SEPARATOR) {
453             $this->markTestSkipped('Windows does not have /dev/tty support');
454         }
455
456         $process = $this->getProcess('echo "foo" >> /dev/null && '.$this->getProcessForCode('usleep(100000);')->getCommandLine());
457         $process->setTty(true);
458         $process->start();
459         $this->assertTrue($process->isRunning());
460         $process->wait();
461
462         $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
463     }
464
465     public function testTTYCommandExitCode()
466     {
467         if ('\\' === \DIRECTORY_SEPARATOR) {
468             $this->markTestSkipped('Windows does have /dev/tty support');
469         }
470         $this->skipIfNotEnhancedSigchild();
471
472         $process = $this->getProcess('echo "foo" >> /dev/null');
473         $process->setTty(true);
474         $process->run();
475
476         $this->assertTrue($process->isSuccessful());
477     }
478
479     /**
480      * @expectedException \Symfony\Component\Process\Exception\RuntimeException
481      * @expectedExceptionMessage TTY mode is not supported on Windows platform.
482      */
483     public function testTTYInWindowsEnvironment()
484     {
485         if ('\\' !== \DIRECTORY_SEPARATOR) {
486             $this->markTestSkipped('This test is for Windows platform only');
487         }
488
489         $process = $this->getProcess('echo "foo" >> /dev/null');
490         $process->setTty(false);
491         $process->setTty(true);
492     }
493
494     public function testExitCodeTextIsNullWhenExitCodeIsNull()
495     {
496         $this->skipIfNotEnhancedSigchild();
497
498         $process = $this->getProcess('');
499         $this->assertNull($process->getExitCodeText());
500     }
501
502     public function testPTYCommand()
503     {
504         if (!Process::isPtySupported()) {
505             $this->markTestSkipped('PTY is not supported on this operating system.');
506         }
507
508         $process = $this->getProcess('echo "foo"');
509         $process->setPty(true);
510         $process->run();
511
512         $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
513         $this->assertEquals("foo\r\n", $process->getOutput());
514     }
515
516     public function testMustRun()
517     {
518         $this->skipIfNotEnhancedSigchild();
519
520         $process = $this->getProcess('echo foo');
521
522         $this->assertSame($process, $process->mustRun());
523         $this->assertEquals('foo'.PHP_EOL, $process->getOutput());
524     }
525
526     public function testSuccessfulMustRunHasCorrectExitCode()
527     {
528         $this->skipIfNotEnhancedSigchild();
529
530         $process = $this->getProcess('echo foo')->mustRun();
531         $this->assertEquals(0, $process->getExitCode());
532     }
533
534     /**
535      * @expectedException \Symfony\Component\Process\Exception\ProcessFailedException
536      */
537     public function testMustRunThrowsException()
538     {
539         $this->skipIfNotEnhancedSigchild();
540
541         $process = $this->getProcess('exit 1');
542         $process->mustRun();
543     }
544
545     public function testExitCodeText()
546     {
547         $this->skipIfNotEnhancedSigchild();
548
549         $process = $this->getProcess('');
550         $r = new \ReflectionObject($process);
551         $p = $r->getProperty('exitcode');
552         $p->setAccessible(true);
553
554         $p->setValue($process, 2);
555         $this->assertEquals('Misuse of shell builtins', $process->getExitCodeText());
556     }
557
558     public function testStartIsNonBlocking()
559     {
560         $process = $this->getProcessForCode('usleep(500000);');
561         $start = microtime(true);
562         $process->start();
563         $end = microtime(true);
564         $this->assertLessThan(0.4, $end - $start);
565         $process->stop();
566     }
567
568     public function testUpdateStatus()
569     {
570         $process = $this->getProcess('echo foo');
571         $process->run();
572         $this->assertGreaterThan(0, \strlen($process->getOutput()));
573     }
574
575     public function testGetExitCodeIsNullOnStart()
576     {
577         $this->skipIfNotEnhancedSigchild();
578
579         $process = $this->getProcessForCode('usleep(100000);');
580         $this->assertNull($process->getExitCode());
581         $process->start();
582         $this->assertNull($process->getExitCode());
583         $process->wait();
584         $this->assertEquals(0, $process->getExitCode());
585     }
586
587     public function testGetExitCodeIsNullOnWhenStartingAgain()
588     {
589         $this->skipIfNotEnhancedSigchild();
590
591         $process = $this->getProcessForCode('usleep(100000);');
592         $process->run();
593         $this->assertEquals(0, $process->getExitCode());
594         $process->start();
595         $this->assertNull($process->getExitCode());
596         $process->wait();
597         $this->assertEquals(0, $process->getExitCode());
598     }
599
600     public function testGetExitCode()
601     {
602         $this->skipIfNotEnhancedSigchild();
603
604         $process = $this->getProcess('echo foo');
605         $process->run();
606         $this->assertSame(0, $process->getExitCode());
607     }
608
609     public function testStatus()
610     {
611         $process = $this->getProcessForCode('usleep(100000);');
612         $this->assertFalse($process->isRunning());
613         $this->assertFalse($process->isStarted());
614         $this->assertFalse($process->isTerminated());
615         $this->assertSame(Process::STATUS_READY, $process->getStatus());
616         $process->start();
617         $this->assertTrue($process->isRunning());
618         $this->assertTrue($process->isStarted());
619         $this->assertFalse($process->isTerminated());
620         $this->assertSame(Process::STATUS_STARTED, $process->getStatus());
621         $process->wait();
622         $this->assertFalse($process->isRunning());
623         $this->assertTrue($process->isStarted());
624         $this->assertTrue($process->isTerminated());
625         $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
626     }
627
628     public function testStop()
629     {
630         $process = $this->getProcessForCode('sleep(31);');
631         $process->start();
632         $this->assertTrue($process->isRunning());
633         $process->stop();
634         $this->assertFalse($process->isRunning());
635     }
636
637     public function testIsSuccessful()
638     {
639         $this->skipIfNotEnhancedSigchild();
640
641         $process = $this->getProcess('echo foo');
642         $process->run();
643         $this->assertTrue($process->isSuccessful());
644     }
645
646     public function testIsSuccessfulOnlyAfterTerminated()
647     {
648         $this->skipIfNotEnhancedSigchild();
649
650         $process = $this->getProcessForCode('usleep(100000);');
651         $process->start();
652
653         $this->assertFalse($process->isSuccessful());
654
655         $process->wait();
656
657         $this->assertTrue($process->isSuccessful());
658     }
659
660     public function testIsNotSuccessful()
661     {
662         $this->skipIfNotEnhancedSigchild();
663
664         $process = $this->getProcessForCode('throw new \Exception(\'BOUM\');');
665         $process->run();
666         $this->assertFalse($process->isSuccessful());
667     }
668
669     public function testProcessIsNotSignaled()
670     {
671         if ('\\' === \DIRECTORY_SEPARATOR) {
672             $this->markTestSkipped('Windows does not support POSIX signals');
673         }
674         $this->skipIfNotEnhancedSigchild();
675
676         $process = $this->getProcess('echo foo');
677         $process->run();
678         $this->assertFalse($process->hasBeenSignaled());
679     }
680
681     public function testProcessWithoutTermSignal()
682     {
683         if ('\\' === \DIRECTORY_SEPARATOR) {
684             $this->markTestSkipped('Windows does not support POSIX signals');
685         }
686         $this->skipIfNotEnhancedSigchild();
687
688         $process = $this->getProcess('echo foo');
689         $process->run();
690         $this->assertEquals(0, $process->getTermSignal());
691     }
692
693     public function testProcessIsSignaledIfStopped()
694     {
695         if ('\\' === \DIRECTORY_SEPARATOR) {
696             $this->markTestSkipped('Windows does not support POSIX signals');
697         }
698         $this->skipIfNotEnhancedSigchild();
699
700         $process = $this->getProcessForCode('sleep(32);');
701         $process->start();
702         $process->stop();
703         $this->assertTrue($process->hasBeenSignaled());
704         $this->assertEquals(15, $process->getTermSignal()); // SIGTERM
705     }
706
707     /**
708      * @expectedException \Symfony\Component\Process\Exception\RuntimeException
709      * @expectedExceptionMessage The process has been signaled
710      */
711     public function testProcessThrowsExceptionWhenExternallySignaled()
712     {
713         if (!\function_exists('posix_kill')) {
714             $this->markTestSkipped('Function posix_kill is required.');
715         }
716         $this->skipIfNotEnhancedSigchild(false);
717
718         $process = $this->getProcessForCode('sleep(32.1);');
719         $process->start();
720         posix_kill($process->getPid(), 9); // SIGKILL
721
722         $process->wait();
723     }
724
725     public function testRestart()
726     {
727         $process1 = $this->getProcessForCode('echo getmypid();');
728         $process1->run();
729         $process2 = $process1->restart();
730
731         $process2->wait(); // wait for output
732
733         // Ensure that both processed finished and the output is numeric
734         $this->assertFalse($process1->isRunning());
735         $this->assertFalse($process2->isRunning());
736         $this->assertInternalType('numeric', $process1->getOutput());
737         $this->assertInternalType('numeric', $process2->getOutput());
738
739         // Ensure that restart returned a new process by check that the output is different
740         $this->assertNotEquals($process1->getOutput(), $process2->getOutput());
741     }
742
743     /**
744      * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
745      * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
746      */
747     public function testRunProcessWithTimeout()
748     {
749         $process = $this->getProcessForCode('sleep(30);');
750         $process->setTimeout(0.1);
751         $start = microtime(true);
752         try {
753             $process->run();
754             $this->fail('A RuntimeException should have been raised');
755         } catch (RuntimeException $e) {
756         }
757
758         $this->assertLessThan(15, microtime(true) - $start);
759
760         throw $e;
761     }
762
763     /**
764      * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
765      * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
766      */
767     public function testIterateOverProcessWithTimeout()
768     {
769         $process = $this->getProcessForCode('sleep(30);');
770         $process->setTimeout(0.1);
771         $start = microtime(true);
772         try {
773             $process->start();
774             foreach ($process as $buffer);
775             $this->fail('A RuntimeException should have been raised');
776         } catch (RuntimeException $e) {
777         }
778
779         $this->assertLessThan(15, microtime(true) - $start);
780
781         throw $e;
782     }
783
784     public function testCheckTimeoutOnNonStartedProcess()
785     {
786         $process = $this->getProcess('echo foo');
787         $this->assertNull($process->checkTimeout());
788     }
789
790     public function testCheckTimeoutOnTerminatedProcess()
791     {
792         $process = $this->getProcess('echo foo');
793         $process->run();
794         $this->assertNull($process->checkTimeout());
795     }
796
797     /**
798      * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
799      * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
800      */
801     public function testCheckTimeoutOnStartedProcess()
802     {
803         $process = $this->getProcessForCode('sleep(33);');
804         $process->setTimeout(0.1);
805
806         $process->start();
807         $start = microtime(true);
808
809         try {
810             while ($process->isRunning()) {
811                 $process->checkTimeout();
812                 usleep(100000);
813             }
814             $this->fail('A ProcessTimedOutException should have been raised');
815         } catch (ProcessTimedOutException $e) {
816         }
817
818         $this->assertLessThan(15, microtime(true) - $start);
819
820         throw $e;
821     }
822
823     public function testIdleTimeout()
824     {
825         $process = $this->getProcessForCode('sleep(34);');
826         $process->setTimeout(60);
827         $process->setIdleTimeout(0.1);
828
829         try {
830             $process->run();
831
832             $this->fail('A timeout exception was expected.');
833         } catch (ProcessTimedOutException $e) {
834             $this->assertTrue($e->isIdleTimeout());
835             $this->assertFalse($e->isGeneralTimeout());
836             $this->assertEquals(0.1, $e->getExceededTimeout());
837         }
838     }
839
840     public function testIdleTimeoutNotExceededWhenOutputIsSent()
841     {
842         $process = $this->getProcessForCode('while (true) {echo \'foo \'; usleep(1000);}');
843         $process->setTimeout(1);
844         $process->start();
845
846         while (false === strpos($process->getOutput(), 'foo')) {
847             usleep(1000);
848         }
849
850         $process->setIdleTimeout(0.5);
851
852         try {
853             $process->wait();
854             $this->fail('A timeout exception was expected.');
855         } catch (ProcessTimedOutException $e) {
856             $this->assertTrue($e->isGeneralTimeout(), 'A general timeout is expected.');
857             $this->assertFalse($e->isIdleTimeout(), 'No idle timeout is expected.');
858             $this->assertEquals(1, $e->getExceededTimeout());
859         }
860     }
861
862     /**
863      * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
864      * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
865      */
866     public function testStartAfterATimeout()
867     {
868         $process = $this->getProcessForCode('sleep(35);');
869         $process->setTimeout(0.1);
870
871         try {
872             $process->run();
873             $this->fail('A ProcessTimedOutException should have been raised.');
874         } catch (ProcessTimedOutException $e) {
875         }
876         $this->assertFalse($process->isRunning());
877         $process->start();
878         $this->assertTrue($process->isRunning());
879         $process->stop(0);
880
881         throw $e;
882     }
883
884     public function testGetPid()
885     {
886         $process = $this->getProcessForCode('sleep(36);');
887         $process->start();
888         $this->assertGreaterThan(0, $process->getPid());
889         $process->stop(0);
890     }
891
892     public function testGetPidIsNullBeforeStart()
893     {
894         $process = $this->getProcess('foo');
895         $this->assertNull($process->getPid());
896     }
897
898     public function testGetPidIsNullAfterRun()
899     {
900         $process = $this->getProcess('echo foo');
901         $process->run();
902         $this->assertNull($process->getPid());
903     }
904
905     /**
906      * @requires extension pcntl
907      */
908     public function testSignal()
909     {
910         $process = $this->getProcess(array(self::$phpBin, __DIR__.'/SignalListener.php'));
911         $process->start();
912
913         while (false === strpos($process->getOutput(), 'Caught')) {
914             usleep(1000);
915         }
916         $process->signal(SIGUSR1);
917         $process->wait();
918
919         $this->assertEquals('Caught SIGUSR1', $process->getOutput());
920     }
921
922     /**
923      * @requires extension pcntl
924      */
925     public function testExitCodeIsAvailableAfterSignal()
926     {
927         $this->skipIfNotEnhancedSigchild();
928
929         $process = $this->getProcess('sleep 4');
930         $process->start();
931         $process->signal(SIGKILL);
932
933         while ($process->isRunning()) {
934             usleep(10000);
935         }
936
937         $this->assertFalse($process->isRunning());
938         $this->assertTrue($process->hasBeenSignaled());
939         $this->assertFalse($process->isSuccessful());
940         $this->assertEquals(137, $process->getExitCode());
941     }
942
943     /**
944      * @expectedException \Symfony\Component\Process\Exception\LogicException
945      * @expectedExceptionMessage Can not send signal on a non running process.
946      */
947     public function testSignalProcessNotRunning()
948     {
949         $process = $this->getProcess('foo');
950         $process->signal(1); // SIGHUP
951     }
952
953     /**
954      * @dataProvider provideMethodsThatNeedARunningProcess
955      */
956     public function testMethodsThatNeedARunningProcess($method)
957     {
958         $process = $this->getProcess('foo');
959
960         if (method_exists($this, 'expectException')) {
961             $this->expectException('Symfony\Component\Process\Exception\LogicException');
962             $this->expectExceptionMessage(sprintf('Process must be started before calling %s.', $method));
963         } else {
964             $this->setExpectedException('Symfony\Component\Process\Exception\LogicException', sprintf('Process must be started before calling %s.', $method));
965         }
966
967         $process->{$method}();
968     }
969
970     public function provideMethodsThatNeedARunningProcess()
971     {
972         return array(
973             array('getOutput'),
974             array('getIncrementalOutput'),
975             array('getErrorOutput'),
976             array('getIncrementalErrorOutput'),
977             array('wait'),
978         );
979     }
980
981     /**
982      * @dataProvider provideMethodsThatNeedATerminatedProcess
983      * @expectedException \Symfony\Component\Process\Exception\LogicException
984      * @expectedExceptionMessage Process must be terminated before calling
985      */
986     public function testMethodsThatNeedATerminatedProcess($method)
987     {
988         $process = $this->getProcessForCode('sleep(37);');
989         $process->start();
990         try {
991             $process->{$method}();
992             $process->stop(0);
993             $this->fail('A LogicException must have been thrown');
994         } catch (\Exception $e) {
995         }
996         $process->stop(0);
997
998         throw $e;
999     }
1000
1001     public function provideMethodsThatNeedATerminatedProcess()
1002     {
1003         return array(
1004             array('hasBeenSignaled'),
1005             array('getTermSignal'),
1006             array('hasBeenStopped'),
1007             array('getStopSignal'),
1008         );
1009     }
1010
1011     /**
1012      * @dataProvider provideWrongSignal
1013      * @expectedException \Symfony\Component\Process\Exception\RuntimeException
1014      */
1015     public function testWrongSignal($signal)
1016     {
1017         if ('\\' === \DIRECTORY_SEPARATOR) {
1018             $this->markTestSkipped('POSIX signals do not work on Windows');
1019         }
1020
1021         $process = $this->getProcessForCode('sleep(38);');
1022         $process->start();
1023         try {
1024             $process->signal($signal);
1025             $this->fail('A RuntimeException must have been thrown');
1026         } catch (RuntimeException $e) {
1027             $process->stop(0);
1028         }
1029
1030         throw $e;
1031     }
1032
1033     public function provideWrongSignal()
1034     {
1035         return array(
1036             array(-4),
1037             array('Céphalopodes'),
1038         );
1039     }
1040
1041     public function testDisableOutputDisablesTheOutput()
1042     {
1043         $p = $this->getProcess('foo');
1044         $this->assertFalse($p->isOutputDisabled());
1045         $p->disableOutput();
1046         $this->assertTrue($p->isOutputDisabled());
1047         $p->enableOutput();
1048         $this->assertFalse($p->isOutputDisabled());
1049     }
1050
1051     /**
1052      * @expectedException \Symfony\Component\Process\Exception\RuntimeException
1053      * @expectedExceptionMessage Disabling output while the process is running is not possible.
1054      */
1055     public function testDisableOutputWhileRunningThrowsException()
1056     {
1057         $p = $this->getProcessForCode('sleep(39);');
1058         $p->start();
1059         $p->disableOutput();
1060     }
1061
1062     /**
1063      * @expectedException \Symfony\Component\Process\Exception\RuntimeException
1064      * @expectedExceptionMessage Enabling output while the process is running is not possible.
1065      */
1066     public function testEnableOutputWhileRunningThrowsException()
1067     {
1068         $p = $this->getProcessForCode('sleep(40);');
1069         $p->disableOutput();
1070         $p->start();
1071         $p->enableOutput();
1072     }
1073
1074     public function testEnableOrDisableOutputAfterRunDoesNotThrowException()
1075     {
1076         $p = $this->getProcess('echo foo');
1077         $p->disableOutput();
1078         $p->run();
1079         $p->enableOutput();
1080         $p->disableOutput();
1081         $this->assertTrue($p->isOutputDisabled());
1082     }
1083
1084     /**
1085      * @expectedException \Symfony\Component\Process\Exception\LogicException
1086      * @expectedExceptionMessage Output can not be disabled while an idle timeout is set.
1087      */
1088     public function testDisableOutputWhileIdleTimeoutIsSet()
1089     {
1090         $process = $this->getProcess('foo');
1091         $process->setIdleTimeout(1);
1092         $process->disableOutput();
1093     }
1094
1095     /**
1096      * @expectedException \Symfony\Component\Process\Exception\LogicException
1097      * @expectedExceptionMessage timeout can not be set while the output is disabled.
1098      */
1099     public function testSetIdleTimeoutWhileOutputIsDisabled()
1100     {
1101         $process = $this->getProcess('foo');
1102         $process->disableOutput();
1103         $process->setIdleTimeout(1);
1104     }
1105
1106     public function testSetNullIdleTimeoutWhileOutputIsDisabled()
1107     {
1108         $process = $this->getProcess('foo');
1109         $process->disableOutput();
1110         $this->assertSame($process, $process->setIdleTimeout(null));
1111     }
1112
1113     /**
1114      * @dataProvider provideOutputFetchingMethods
1115      * @expectedException \Symfony\Component\Process\Exception\LogicException
1116      * @expectedExceptionMessage Output has been disabled.
1117      */
1118     public function testGetOutputWhileDisabled($fetchMethod)
1119     {
1120         $p = $this->getProcessForCode('sleep(41);');
1121         $p->disableOutput();
1122         $p->start();
1123         $p->{$fetchMethod}();
1124     }
1125
1126     public function provideOutputFetchingMethods()
1127     {
1128         return array(
1129             array('getOutput'),
1130             array('getIncrementalOutput'),
1131             array('getErrorOutput'),
1132             array('getIncrementalErrorOutput'),
1133         );
1134     }
1135
1136     public function testStopTerminatesProcessCleanly()
1137     {
1138         $process = $this->getProcessForCode('echo 123; sleep(42);');
1139         $process->run(function () use ($process) {
1140             $process->stop();
1141         });
1142         $this->assertTrue(true, 'A call to stop() is not expected to cause wait() to throw a RuntimeException');
1143     }
1144
1145     public function testKillSignalTerminatesProcessCleanly()
1146     {
1147         $process = $this->getProcessForCode('echo 123; sleep(43);');
1148         $process->run(function () use ($process) {
1149             $process->signal(9); // SIGKILL
1150         });
1151         $this->assertTrue(true, 'A call to signal() is not expected to cause wait() to throw a RuntimeException');
1152     }
1153
1154     public function testTermSignalTerminatesProcessCleanly()
1155     {
1156         $process = $this->getProcessForCode('echo 123; sleep(44);');
1157         $process->run(function () use ($process) {
1158             $process->signal(15); // SIGTERM
1159         });
1160         $this->assertTrue(true, 'A call to signal() is not expected to cause wait() to throw a RuntimeException');
1161     }
1162
1163     public function responsesCodeProvider()
1164     {
1165         return array(
1166             //expected output / getter / code to execute
1167             //array(1,'getExitCode','exit(1);'),
1168             //array(true,'isSuccessful','exit();'),
1169             array('output', 'getOutput', 'echo \'output\';'),
1170         );
1171     }
1172
1173     public function pipesCodeProvider()
1174     {
1175         $variations = array(
1176             'fwrite(STDOUT, $in = file_get_contents(\'php://stdin\')); fwrite(STDERR, $in);',
1177             'include \''.__DIR__.'/PipeStdinInStdoutStdErrStreamSelect.php\';',
1178         );
1179
1180         if ('\\' === \DIRECTORY_SEPARATOR) {
1181             // Avoid XL buffers on Windows because of https://bugs.php.net/bug.php?id=65650
1182             $sizes = array(1, 2, 4, 8);
1183         } else {
1184             $sizes = array(1, 16, 64, 1024, 4096);
1185         }
1186
1187         $codes = array();
1188         foreach ($sizes as $size) {
1189             foreach ($variations as $code) {
1190                 $codes[] = array($code, $size);
1191             }
1192         }
1193
1194         return $codes;
1195     }
1196
1197     /**
1198      * @dataProvider provideVariousIncrementals
1199      */
1200     public function testIncrementalOutputDoesNotRequireAnotherCall($stream, $method)
1201     {
1202         $process = $this->getProcessForCode('$n = 0; while ($n < 3) { file_put_contents(\''.$stream.'\', $n, 1); $n++; usleep(1000); }', null, null, null, null);
1203         $process->start();
1204         $result = '';
1205         $limit = microtime(true) + 3;
1206         $expected = '012';
1207
1208         while ($result !== $expected && microtime(true) < $limit) {
1209             $result .= $process->$method();
1210         }
1211
1212         $this->assertSame($expected, $result);
1213         $process->stop();
1214     }
1215
1216     public function provideVariousIncrementals()
1217     {
1218         return array(
1219             array('php://stdout', 'getIncrementalOutput'),
1220             array('php://stderr', 'getIncrementalErrorOutput'),
1221         );
1222     }
1223
1224     public function testIteratorInput()
1225     {
1226         $input = function () {
1227             yield 'ping';
1228             yield 'pong';
1229         };
1230
1231         $process = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);', null, null, $input());
1232         $process->run();
1233         $this->assertSame('pingpong', $process->getOutput());
1234     }
1235
1236     public function testSimpleInputStream()
1237     {
1238         $input = new InputStream();
1239
1240         $process = $this->getProcessForCode('echo \'ping\'; echo fread(STDIN, 4); echo fread(STDIN, 4);');
1241         $process->setInput($input);
1242
1243         $process->start(function ($type, $data) use ($input) {
1244             if ('ping' === $data) {
1245                 $input->write('pang');
1246             } elseif (!$input->isClosed()) {
1247                 $input->write('pong');
1248                 $input->close();
1249             }
1250         });
1251
1252         $process->wait();
1253         $this->assertSame('pingpangpong', $process->getOutput());
1254     }
1255
1256     public function testInputStreamWithCallable()
1257     {
1258         $i = 0;
1259         $stream = fopen('php://memory', 'w+');
1260         $stream = function () use ($stream, &$i) {
1261             if ($i < 3) {
1262                 rewind($stream);
1263                 fwrite($stream, ++$i);
1264                 rewind($stream);
1265
1266                 return $stream;
1267             }
1268         };
1269
1270         $input = new InputStream();
1271         $input->onEmpty($stream);
1272         $input->write($stream());
1273
1274         $process = $this->getProcessForCode('echo fread(STDIN, 3);');
1275         $process->setInput($input);
1276         $process->start(function ($type, $data) use ($input) {
1277             $input->close();
1278         });
1279
1280         $process->wait();
1281         $this->assertSame('123', $process->getOutput());
1282     }
1283
1284     public function testInputStreamWithGenerator()
1285     {
1286         $input = new InputStream();
1287         $input->onEmpty(function ($input) {
1288             yield 'pong';
1289             $input->close();
1290         });
1291
1292         $process = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);');
1293         $process->setInput($input);
1294         $process->start();
1295         $input->write('ping');
1296         $process->wait();
1297         $this->assertSame('pingpong', $process->getOutput());
1298     }
1299
1300     public function testInputStreamOnEmpty()
1301     {
1302         $i = 0;
1303         $input = new InputStream();
1304         $input->onEmpty(function () use (&$i) { ++$i; });
1305
1306         $process = $this->getProcessForCode('echo 123; echo fread(STDIN, 1); echo 456;');
1307         $process->setInput($input);
1308         $process->start(function ($type, $data) use ($input) {
1309             if ('123' === $data) {
1310                 $input->close();
1311             }
1312         });
1313         $process->wait();
1314
1315         $this->assertSame(0, $i, 'InputStream->onEmpty callback should be called only when the input *becomes* empty');
1316         $this->assertSame('123456', $process->getOutput());
1317     }
1318
1319     public function testIteratorOutput()
1320     {
1321         $input = new InputStream();
1322
1323         $process = $this->getProcessForCode('fwrite(STDOUT, 123); fwrite(STDERR, 234); flush(); usleep(10000); fwrite(STDOUT, fread(STDIN, 3)); fwrite(STDERR, 456);');
1324         $process->setInput($input);
1325         $process->start();
1326         $output = array();
1327
1328         foreach ($process as $type => $data) {
1329             $output[] = array($type, $data);
1330             break;
1331         }
1332         $expectedOutput = array(
1333             array($process::OUT, '123'),
1334         );
1335         $this->assertSame($expectedOutput, $output);
1336
1337         $input->write(345);
1338
1339         foreach ($process as $type => $data) {
1340             $output[] = array($type, $data);
1341         }
1342
1343         $this->assertSame('', $process->getOutput());
1344         $this->assertFalse($process->isRunning());
1345
1346         $expectedOutput = array(
1347             array($process::OUT, '123'),
1348             array($process::ERR, '234'),
1349             array($process::OUT, '345'),
1350             array($process::ERR, '456'),
1351         );
1352         $this->assertSame($expectedOutput, $output);
1353     }
1354
1355     public function testNonBlockingNorClearingIteratorOutput()
1356     {
1357         $input = new InputStream();
1358
1359         $process = $this->getProcessForCode('fwrite(STDOUT, fread(STDIN, 3));');
1360         $process->setInput($input);
1361         $process->start();
1362         $output = array();
1363
1364         foreach ($process->getIterator($process::ITER_NON_BLOCKING | $process::ITER_KEEP_OUTPUT) as $type => $data) {
1365             $output[] = array($type, $data);
1366             break;
1367         }
1368         $expectedOutput = array(
1369             array($process::OUT, ''),
1370         );
1371         $this->assertSame($expectedOutput, $output);
1372
1373         $input->write(123);
1374
1375         foreach ($process->getIterator($process::ITER_NON_BLOCKING | $process::ITER_KEEP_OUTPUT) as $type => $data) {
1376             if ('' !== $data) {
1377                 $output[] = array($type, $data);
1378             }
1379         }
1380
1381         $this->assertSame('123', $process->getOutput());
1382         $this->assertFalse($process->isRunning());
1383
1384         $expectedOutput = array(
1385             array($process::OUT, ''),
1386             array($process::OUT, '123'),
1387         );
1388         $this->assertSame($expectedOutput, $output);
1389     }
1390
1391     public function testChainedProcesses()
1392     {
1393         $p1 = $this->getProcessForCode('fwrite(STDERR, 123); fwrite(STDOUT, 456);');
1394         $p2 = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);');
1395         $p2->setInput($p1);
1396
1397         $p1->start();
1398         $p2->run();
1399
1400         $this->assertSame('123', $p1->getErrorOutput());
1401         $this->assertSame('', $p1->getOutput());
1402         $this->assertSame('', $p2->getErrorOutput());
1403         $this->assertSame('456', $p2->getOutput());
1404     }
1405
1406     public function testSetBadEnv()
1407     {
1408         $process = $this->getProcess('echo hello');
1409         $process->setEnv(array('bad%%' => '123'));
1410         $process->inheritEnvironmentVariables(true);
1411
1412         $process->run();
1413
1414         $this->assertSame('hello'.PHP_EOL, $process->getOutput());
1415         $this->assertSame('', $process->getErrorOutput());
1416     }
1417
1418     public function testEnvBackupDoesNotDeleteExistingVars()
1419     {
1420         putenv('existing_var=foo');
1421         $_ENV['existing_var'] = 'foo';
1422         $process = $this->getProcess('php -r "echo getenv(\'new_test_var\');"');
1423         $process->setEnv(array('existing_var' => 'bar', 'new_test_var' => 'foo'));
1424         $process->inheritEnvironmentVariables();
1425
1426         $process->run();
1427
1428         $this->assertSame('foo', $process->getOutput());
1429         $this->assertSame('foo', getenv('existing_var'));
1430         $this->assertFalse(getenv('new_test_var'));
1431
1432         putenv('existing_var');
1433         unset($_ENV['existing_var']);
1434     }
1435
1436     public function testEnvIsInherited()
1437     {
1438         $process = $this->getProcessForCode('echo serialize($_SERVER);', null, array('BAR' => 'BAZ', 'EMPTY' => ''));
1439
1440         putenv('FOO=BAR');
1441         $_ENV['FOO'] = 'BAR';
1442
1443         $process->run();
1444
1445         $expected = array('BAR' => 'BAZ', 'EMPTY' => '', 'FOO' => 'BAR');
1446         $env = array_intersect_key(unserialize($process->getOutput()), $expected);
1447
1448         $this->assertEquals($expected, $env);
1449
1450         putenv('FOO');
1451         unset($_ENV['FOO']);
1452     }
1453
1454     /**
1455      * @group legacy
1456      */
1457     public function testInheritEnvDisabled()
1458     {
1459         $process = $this->getProcessForCode('echo serialize($_SERVER);', null, array('BAR' => 'BAZ'));
1460
1461         putenv('FOO=BAR');
1462         $_ENV['FOO'] = 'BAR';
1463
1464         $this->assertSame($process, $process->inheritEnvironmentVariables(false));
1465         $this->assertFalse($process->areEnvironmentVariablesInherited());
1466
1467         $process->run();
1468
1469         $expected = array('BAR' => 'BAZ', 'FOO' => 'BAR');
1470         $env = array_intersect_key(unserialize($process->getOutput()), $expected);
1471         unset($expected['FOO']);
1472
1473         $this->assertSame($expected, $env);
1474
1475         putenv('FOO');
1476         unset($_ENV['FOO']);
1477     }
1478
1479     public function testGetCommandLine()
1480     {
1481         $p = new Process(array('/usr/bin/php'));
1482
1483         $expected = '\\' === \DIRECTORY_SEPARATOR ? '"/usr/bin/php"' : "'/usr/bin/php'";
1484         $this->assertSame($expected, $p->getCommandLine());
1485     }
1486
1487     /**
1488      * @dataProvider provideEscapeArgument
1489      */
1490     public function testEscapeArgument($arg)
1491     {
1492         $p = new Process(array(self::$phpBin, '-r', 'echo $argv[1];', $arg));
1493         $p->run();
1494
1495         $this->assertSame((string) $arg, $p->getOutput());
1496     }
1497
1498     /**
1499      * @dataProvider provideEscapeArgument
1500      * @group legacy
1501      */
1502     public function testEscapeArgumentWhenInheritEnvDisabled($arg)
1503     {
1504         $p = new Process(array(self::$phpBin, '-r', 'echo $argv[1];', $arg), null, array('BAR' => 'BAZ'));
1505         $p->inheritEnvironmentVariables(false);
1506         $p->run();
1507
1508         $this->assertSame((string) $arg, $p->getOutput());
1509     }
1510
1511     public function testRawCommandLine()
1512     {
1513         $p = new Process(sprintf('"%s" -r %s "a" "" "b"', self::$phpBin, escapeshellarg('print_r($argv);')));
1514         $p->run();
1515
1516         $expected = <<<EOTXT
1517 Array
1518 (
1519     [0] => -
1520     [1] => a
1521     [2] => 
1522     [3] => b
1523 )
1524
1525 EOTXT;
1526         $this->assertSame($expected, str_replace('Standard input code', '-', $p->getOutput()));
1527     }
1528
1529     public function provideEscapeArgument()
1530     {
1531         yield array('a"b%c%');
1532         yield array('a"b^c^');
1533         yield array("a\nb'c");
1534         yield array('a^b c!');
1535         yield array("a!b\tc");
1536         yield array('a\\\\"\\"');
1537         yield array('éÉèÈàÀöä');
1538         yield array(null);
1539         yield array(1);
1540         yield array(1.1);
1541     }
1542
1543     public function testEnvArgument()
1544     {
1545         $env = array('FOO' => 'Foo', 'BAR' => 'Bar');
1546         $cmd = '\\' === \DIRECTORY_SEPARATOR ? 'echo !FOO! !BAR! !BAZ!' : 'echo $FOO $BAR $BAZ';
1547         $p = new Process($cmd, null, $env);
1548         $p->run(null, array('BAR' => 'baR', 'BAZ' => 'baZ'));
1549
1550         $this->assertSame('Foo baR baZ', rtrim($p->getOutput()));
1551         $this->assertSame($env, $p->getEnv());
1552     }
1553
1554     /**
1555      * @param string      $commandline
1556      * @param string|null $cwd
1557      * @param array|null  $env
1558      * @param string|null $input
1559      * @param int         $timeout
1560      * @param array       $options
1561      *
1562      * @return Process
1563      */
1564     private function getProcess($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60)
1565     {
1566         $process = new Process($commandline, $cwd, $env, $input, $timeout);
1567         $process->inheritEnvironmentVariables();
1568
1569         if (false !== $enhance = getenv('ENHANCE_SIGCHLD')) {
1570             try {
1571                 $process->setEnhanceSigchildCompatibility(false);
1572                 $process->getExitCode();
1573                 $this->fail('ENHANCE_SIGCHLD must be used together with a sigchild-enabled PHP.');
1574             } catch (RuntimeException $e) {
1575                 $this->assertSame('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.', $e->getMessage());
1576                 if ($enhance) {
1577                     $process->setEnhanceSigchildCompatibility(true);
1578                 } else {
1579                     self::$notEnhancedSigchild = true;
1580                 }
1581             }
1582         }
1583
1584         if (self::$process) {
1585             self::$process->stop(0);
1586         }
1587
1588         return self::$process = $process;
1589     }
1590
1591     /**
1592      * @return Process
1593      */
1594     private function getProcessForCode($code, $cwd = null, array $env = null, $input = null, $timeout = 60)
1595     {
1596         return $this->getProcess(array(self::$phpBin, '-r', $code), $cwd, $env, $input, $timeout);
1597     }
1598
1599     private function skipIfNotEnhancedSigchild($expectException = true)
1600     {
1601         if (self::$sigchild) {
1602             if (!$expectException) {
1603                 $this->markTestSkipped('PHP is compiled with --enable-sigchild.');
1604             } elseif (self::$notEnhancedSigchild) {
1605                 if (method_exists($this, 'expectException')) {
1606                     $this->expectException('Symfony\Component\Process\Exception\RuntimeException');
1607                     $this->expectExceptionMessage('This PHP has been compiled with --enable-sigchild.');
1608                 } else {
1609                     $this->setExpectedException('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild.');
1610                 }
1611             }
1612         }
1613     }
1614 }
1615
1616 class NonStringifiable
1617 {
1618 }