bca7ddd9af10db79d142421d7bb69a8b5cbe7b04
[yaffs-website] / vendor / symfony / process / Tests / 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     /**
451      * @group tty
452      */
453     public function testTTYCommand()
454     {
455         if ('\\' === DIRECTORY_SEPARATOR) {
456             $this->markTestSkipped('Windows does not have /dev/tty support');
457         }
458
459         $process = $this->getProcess('echo "foo" >> /dev/null && '.$this->getProcessForCode('usleep(100000);')->getCommandLine());
460         $process->setTty(true);
461         $process->start();
462         $this->assertTrue($process->isRunning());
463         $process->wait();
464
465         $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
466     }
467
468     /**
469      * @group tty
470      */
471     public function testTTYCommandExitCode()
472     {
473         if ('\\' === DIRECTORY_SEPARATOR) {
474             $this->markTestSkipped('Windows does have /dev/tty support');
475         }
476         $this->skipIfNotEnhancedSigchild();
477
478         $process = $this->getProcess('echo "foo" >> /dev/null');
479         $process->setTty(true);
480         $process->run();
481
482         $this->assertTrue($process->isSuccessful());
483     }
484
485     /**
486      * @expectedException \Symfony\Component\Process\Exception\RuntimeException
487      * @expectedExceptionMessage TTY mode is not supported on Windows platform.
488      */
489     public function testTTYInWindowsEnvironment()
490     {
491         if ('\\' !== DIRECTORY_SEPARATOR) {
492             $this->markTestSkipped('This test is for Windows platform only');
493         }
494
495         $process = $this->getProcess('echo "foo" >> /dev/null');
496         $process->setTty(false);
497         $process->setTty(true);
498     }
499
500     public function testExitCodeTextIsNullWhenExitCodeIsNull()
501     {
502         $this->skipIfNotEnhancedSigchild();
503
504         $process = $this->getProcess('');
505         $this->assertNull($process->getExitCodeText());
506     }
507
508     public function testPTYCommand()
509     {
510         if (!Process::isPtySupported()) {
511             $this->markTestSkipped('PTY is not supported on this operating system.');
512         }
513
514         $process = $this->getProcess('echo "foo"');
515         $process->setPty(true);
516         $process->run();
517
518         $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
519         $this->assertEquals("foo\r\n", $process->getOutput());
520     }
521
522     public function testMustRun()
523     {
524         $this->skipIfNotEnhancedSigchild();
525
526         $process = $this->getProcess('echo foo');
527
528         $this->assertSame($process, $process->mustRun());
529         $this->assertEquals('foo'.PHP_EOL, $process->getOutput());
530     }
531
532     public function testSuccessfulMustRunHasCorrectExitCode()
533     {
534         $this->skipIfNotEnhancedSigchild();
535
536         $process = $this->getProcess('echo foo')->mustRun();
537         $this->assertEquals(0, $process->getExitCode());
538     }
539
540     /**
541      * @expectedException \Symfony\Component\Process\Exception\ProcessFailedException
542      */
543     public function testMustRunThrowsException()
544     {
545         $this->skipIfNotEnhancedSigchild();
546
547         $process = $this->getProcess('exit 1');
548         $process->mustRun();
549     }
550
551     public function testExitCodeText()
552     {
553         $this->skipIfNotEnhancedSigchild();
554
555         $process = $this->getProcess('');
556         $r = new \ReflectionObject($process);
557         $p = $r->getProperty('exitcode');
558         $p->setAccessible(true);
559
560         $p->setValue($process, 2);
561         $this->assertEquals('Misuse of shell builtins', $process->getExitCodeText());
562     }
563
564     public function testStartIsNonBlocking()
565     {
566         $process = $this->getProcessForCode('usleep(500000);');
567         $start = microtime(true);
568         $process->start();
569         $end = microtime(true);
570         $this->assertLessThan(0.4, $end - $start);
571         $process->stop();
572     }
573
574     public function testUpdateStatus()
575     {
576         $process = $this->getProcess('echo foo');
577         $process->run();
578         $this->assertGreaterThan(0, strlen($process->getOutput()));
579     }
580
581     public function testGetExitCodeIsNullOnStart()
582     {
583         $this->skipIfNotEnhancedSigchild();
584
585         $process = $this->getProcessForCode('usleep(100000);');
586         $this->assertNull($process->getExitCode());
587         $process->start();
588         $this->assertNull($process->getExitCode());
589         $process->wait();
590         $this->assertEquals(0, $process->getExitCode());
591     }
592
593     public function testGetExitCodeIsNullOnWhenStartingAgain()
594     {
595         $this->skipIfNotEnhancedSigchild();
596
597         $process = $this->getProcessForCode('usleep(100000);');
598         $process->run();
599         $this->assertEquals(0, $process->getExitCode());
600         $process->start();
601         $this->assertNull($process->getExitCode());
602         $process->wait();
603         $this->assertEquals(0, $process->getExitCode());
604     }
605
606     public function testGetExitCode()
607     {
608         $this->skipIfNotEnhancedSigchild();
609
610         $process = $this->getProcess('echo foo');
611         $process->run();
612         $this->assertSame(0, $process->getExitCode());
613     }
614
615     public function testStatus()
616     {
617         $process = $this->getProcessForCode('usleep(100000);');
618         $this->assertFalse($process->isRunning());
619         $this->assertFalse($process->isStarted());
620         $this->assertFalse($process->isTerminated());
621         $this->assertSame(Process::STATUS_READY, $process->getStatus());
622         $process->start();
623         $this->assertTrue($process->isRunning());
624         $this->assertTrue($process->isStarted());
625         $this->assertFalse($process->isTerminated());
626         $this->assertSame(Process::STATUS_STARTED, $process->getStatus());
627         $process->wait();
628         $this->assertFalse($process->isRunning());
629         $this->assertTrue($process->isStarted());
630         $this->assertTrue($process->isTerminated());
631         $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
632     }
633
634     public function testStop()
635     {
636         $process = $this->getProcessForCode('sleep(31);');
637         $process->start();
638         $this->assertTrue($process->isRunning());
639         $process->stop();
640         $this->assertFalse($process->isRunning());
641     }
642
643     public function testIsSuccessful()
644     {
645         $this->skipIfNotEnhancedSigchild();
646
647         $process = $this->getProcess('echo foo');
648         $process->run();
649         $this->assertTrue($process->isSuccessful());
650     }
651
652     public function testIsSuccessfulOnlyAfterTerminated()
653     {
654         $this->skipIfNotEnhancedSigchild();
655
656         $process = $this->getProcessForCode('usleep(100000);');
657         $process->start();
658
659         $this->assertFalse($process->isSuccessful());
660
661         $process->wait();
662
663         $this->assertTrue($process->isSuccessful());
664     }
665
666     public function testIsNotSuccessful()
667     {
668         $this->skipIfNotEnhancedSigchild();
669
670         $process = $this->getProcessForCode('throw new \Exception(\'BOUM\');');
671         $process->run();
672         $this->assertFalse($process->isSuccessful());
673     }
674
675     public function testProcessIsNotSignaled()
676     {
677         if ('\\' === DIRECTORY_SEPARATOR) {
678             $this->markTestSkipped('Windows does not support POSIX signals');
679         }
680         $this->skipIfNotEnhancedSigchild();
681
682         $process = $this->getProcess('echo foo');
683         $process->run();
684         $this->assertFalse($process->hasBeenSignaled());
685     }
686
687     public function testProcessWithoutTermSignal()
688     {
689         if ('\\' === DIRECTORY_SEPARATOR) {
690             $this->markTestSkipped('Windows does not support POSIX signals');
691         }
692         $this->skipIfNotEnhancedSigchild();
693
694         $process = $this->getProcess('echo foo');
695         $process->run();
696         $this->assertEquals(0, $process->getTermSignal());
697     }
698
699     public function testProcessIsSignaledIfStopped()
700     {
701         if ('\\' === DIRECTORY_SEPARATOR) {
702             $this->markTestSkipped('Windows does not support POSIX signals');
703         }
704         $this->skipIfNotEnhancedSigchild();
705
706         $process = $this->getProcessForCode('sleep(32);');
707         $process->start();
708         $process->stop();
709         $this->assertTrue($process->hasBeenSignaled());
710         $this->assertEquals(15, $process->getTermSignal()); // SIGTERM
711     }
712
713     /**
714      * @expectedException \Symfony\Component\Process\Exception\RuntimeException
715      * @expectedExceptionMessage The process has been signaled
716      */
717     public function testProcessThrowsExceptionWhenExternallySignaled()
718     {
719         if (!function_exists('posix_kill')) {
720             $this->markTestSkipped('Function posix_kill is required.');
721         }
722         $this->skipIfNotEnhancedSigchild(false);
723
724         $process = $this->getProcessForCode('sleep(32.1);');
725         $process->start();
726         posix_kill($process->getPid(), 9); // SIGKILL
727
728         $process->wait();
729     }
730
731     public function testRestart()
732     {
733         $process1 = $this->getProcessForCode('echo getmypid();');
734         $process1->run();
735         $process2 = $process1->restart();
736
737         $process2->wait(); // wait for output
738
739         // Ensure that both processed finished and the output is numeric
740         $this->assertFalse($process1->isRunning());
741         $this->assertFalse($process2->isRunning());
742         $this->assertInternalType('numeric', $process1->getOutput());
743         $this->assertInternalType('numeric', $process2->getOutput());
744
745         // Ensure that restart returned a new process by check that the output is different
746         $this->assertNotEquals($process1->getOutput(), $process2->getOutput());
747     }
748
749     /**
750      * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
751      * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
752      */
753     public function testRunProcessWithTimeout()
754     {
755         $process = $this->getProcessForCode('sleep(30);');
756         $process->setTimeout(0.1);
757         $start = microtime(true);
758         try {
759             $process->run();
760             $this->fail('A RuntimeException should have been raised');
761         } catch (RuntimeException $e) {
762         }
763
764         $this->assertLessThan(15, microtime(true) - $start);
765
766         throw $e;
767     }
768
769     /**
770      * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
771      * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
772      */
773     public function testIterateOverProcessWithTimeout()
774     {
775         $process = $this->getProcessForCode('sleep(30);');
776         $process->setTimeout(0.1);
777         $start = microtime(true);
778         try {
779             $process->start();
780             foreach ($process as $buffer);
781             $this->fail('A RuntimeException should have been raised');
782         } catch (RuntimeException $e) {
783         }
784
785         $this->assertLessThan(15, microtime(true) - $start);
786
787         throw $e;
788     }
789
790     public function testCheckTimeoutOnNonStartedProcess()
791     {
792         $process = $this->getProcess('echo foo');
793         $this->assertNull($process->checkTimeout());
794     }
795
796     public function testCheckTimeoutOnTerminatedProcess()
797     {
798         $process = $this->getProcess('echo foo');
799         $process->run();
800         $this->assertNull($process->checkTimeout());
801     }
802
803     /**
804      * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
805      * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
806      */
807     public function testCheckTimeoutOnStartedProcess()
808     {
809         $process = $this->getProcessForCode('sleep(33);');
810         $process->setTimeout(0.1);
811
812         $process->start();
813         $start = microtime(true);
814
815         try {
816             while ($process->isRunning()) {
817                 $process->checkTimeout();
818                 usleep(100000);
819             }
820             $this->fail('A ProcessTimedOutException should have been raised');
821         } catch (ProcessTimedOutException $e) {
822         }
823
824         $this->assertLessThan(15, microtime(true) - $start);
825
826         throw $e;
827     }
828
829     public function testIdleTimeout()
830     {
831         $process = $this->getProcessForCode('sleep(34);');
832         $process->setTimeout(60);
833         $process->setIdleTimeout(0.1);
834
835         try {
836             $process->run();
837
838             $this->fail('A timeout exception was expected.');
839         } catch (ProcessTimedOutException $e) {
840             $this->assertTrue($e->isIdleTimeout());
841             $this->assertFalse($e->isGeneralTimeout());
842             $this->assertEquals(0.1, $e->getExceededTimeout());
843         }
844     }
845
846     public function testIdleTimeoutNotExceededWhenOutputIsSent()
847     {
848         $process = $this->getProcessForCode('while (true) {echo \'foo \'; usleep(1000);}');
849         $process->setTimeout(1);
850         $process->start();
851
852         while (false === strpos($process->getOutput(), 'foo')) {
853             usleep(1000);
854         }
855
856         $process->setIdleTimeout(0.5);
857
858         try {
859             $process->wait();
860             $this->fail('A timeout exception was expected.');
861         } catch (ProcessTimedOutException $e) {
862             $this->assertTrue($e->isGeneralTimeout(), 'A general timeout is expected.');
863             $this->assertFalse($e->isIdleTimeout(), 'No idle timeout is expected.');
864             $this->assertEquals(1, $e->getExceededTimeout());
865         }
866     }
867
868     /**
869      * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
870      * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
871      */
872     public function testStartAfterATimeout()
873     {
874         $process = $this->getProcessForCode('sleep(35);');
875         $process->setTimeout(0.1);
876
877         try {
878             $process->run();
879             $this->fail('A ProcessTimedOutException should have been raised.');
880         } catch (ProcessTimedOutException $e) {
881         }
882         $this->assertFalse($process->isRunning());
883         $process->start();
884         $this->assertTrue($process->isRunning());
885         $process->stop(0);
886
887         throw $e;
888     }
889
890     public function testGetPid()
891     {
892         $process = $this->getProcessForCode('sleep(36);');
893         $process->start();
894         $this->assertGreaterThan(0, $process->getPid());
895         $process->stop(0);
896     }
897
898     public function testGetPidIsNullBeforeStart()
899     {
900         $process = $this->getProcess('foo');
901         $this->assertNull($process->getPid());
902     }
903
904     public function testGetPidIsNullAfterRun()
905     {
906         $process = $this->getProcess('echo foo');
907         $process->run();
908         $this->assertNull($process->getPid());
909     }
910
911     /**
912      * @requires extension pcntl
913      */
914     public function testSignal()
915     {
916         $process = $this->getProcess(array(self::$phpBin, __DIR__.'/SignalListener.php'));
917         $process->start();
918
919         while (false === strpos($process->getOutput(), 'Caught')) {
920             usleep(1000);
921         }
922         $process->signal(SIGUSR1);
923         $process->wait();
924
925         $this->assertEquals('Caught SIGUSR1', $process->getOutput());
926     }
927
928     /**
929      * @requires extension pcntl
930      */
931     public function testExitCodeIsAvailableAfterSignal()
932     {
933         $this->skipIfNotEnhancedSigchild();
934
935         $process = $this->getProcess('sleep 4');
936         $process->start();
937         $process->signal(SIGKILL);
938
939         while ($process->isRunning()) {
940             usleep(10000);
941         }
942
943         $this->assertFalse($process->isRunning());
944         $this->assertTrue($process->hasBeenSignaled());
945         $this->assertFalse($process->isSuccessful());
946         $this->assertEquals(137, $process->getExitCode());
947     }
948
949     /**
950      * @expectedException \Symfony\Component\Process\Exception\LogicException
951      * @expectedExceptionMessage Can not send signal on a non running process.
952      */
953     public function testSignalProcessNotRunning()
954     {
955         $process = $this->getProcess('foo');
956         $process->signal(1); // SIGHUP
957     }
958
959     /**
960      * @dataProvider provideMethodsThatNeedARunningProcess
961      */
962     public function testMethodsThatNeedARunningProcess($method)
963     {
964         $process = $this->getProcess('foo');
965
966         if (method_exists($this, 'expectException')) {
967             $this->expectException('Symfony\Component\Process\Exception\LogicException');
968             $this->expectExceptionMessage(sprintf('Process must be started before calling %s.', $method));
969         } else {
970             $this->setExpectedException('Symfony\Component\Process\Exception\LogicException', sprintf('Process must be started before calling %s.', $method));
971         }
972
973         $process->{$method}();
974     }
975
976     public function provideMethodsThatNeedARunningProcess()
977     {
978         return array(
979             array('getOutput'),
980             array('getIncrementalOutput'),
981             array('getErrorOutput'),
982             array('getIncrementalErrorOutput'),
983             array('wait'),
984         );
985     }
986
987     /**
988      * @dataProvider provideMethodsThatNeedATerminatedProcess
989      * @expectedException \Symfony\Component\Process\Exception\LogicException
990      * @expectedExceptionMessage Process must be terminated before calling
991      */
992     public function testMethodsThatNeedATerminatedProcess($method)
993     {
994         $process = $this->getProcessForCode('sleep(37);');
995         $process->start();
996         try {
997             $process->{$method}();
998             $process->stop(0);
999             $this->fail('A LogicException must have been thrown');
1000         } catch (\Exception $e) {
1001         }
1002         $process->stop(0);
1003
1004         throw $e;
1005     }
1006
1007     public function provideMethodsThatNeedATerminatedProcess()
1008     {
1009         return array(
1010             array('hasBeenSignaled'),
1011             array('getTermSignal'),
1012             array('hasBeenStopped'),
1013             array('getStopSignal'),
1014         );
1015     }
1016
1017     /**
1018      * @dataProvider provideWrongSignal
1019      * @expectedException \Symfony\Component\Process\Exception\RuntimeException
1020      */
1021     public function testWrongSignal($signal)
1022     {
1023         if ('\\' === DIRECTORY_SEPARATOR) {
1024             $this->markTestSkipped('POSIX signals do not work on Windows');
1025         }
1026
1027         $process = $this->getProcessForCode('sleep(38);');
1028         $process->start();
1029         try {
1030             $process->signal($signal);
1031             $this->fail('A RuntimeException must have been thrown');
1032         } catch (RuntimeException $e) {
1033             $process->stop(0);
1034         }
1035
1036         throw $e;
1037     }
1038
1039     public function provideWrongSignal()
1040     {
1041         return array(
1042             array(-4),
1043             array('Céphalopodes'),
1044         );
1045     }
1046
1047     public function testDisableOutputDisablesTheOutput()
1048     {
1049         $p = $this->getProcess('foo');
1050         $this->assertFalse($p->isOutputDisabled());
1051         $p->disableOutput();
1052         $this->assertTrue($p->isOutputDisabled());
1053         $p->enableOutput();
1054         $this->assertFalse($p->isOutputDisabled());
1055     }
1056
1057     /**
1058      * @expectedException \Symfony\Component\Process\Exception\RuntimeException
1059      * @expectedExceptionMessage Disabling output while the process is running is not possible.
1060      */
1061     public function testDisableOutputWhileRunningThrowsException()
1062     {
1063         $p = $this->getProcessForCode('sleep(39);');
1064         $p->start();
1065         $p->disableOutput();
1066     }
1067
1068     /**
1069      * @expectedException \Symfony\Component\Process\Exception\RuntimeException
1070      * @expectedExceptionMessage Enabling output while the process is running is not possible.
1071      */
1072     public function testEnableOutputWhileRunningThrowsException()
1073     {
1074         $p = $this->getProcessForCode('sleep(40);');
1075         $p->disableOutput();
1076         $p->start();
1077         $p->enableOutput();
1078     }
1079
1080     public function testEnableOrDisableOutputAfterRunDoesNotThrowException()
1081     {
1082         $p = $this->getProcess('echo foo');
1083         $p->disableOutput();
1084         $p->run();
1085         $p->enableOutput();
1086         $p->disableOutput();
1087         $this->assertTrue($p->isOutputDisabled());
1088     }
1089
1090     /**
1091      * @expectedException \Symfony\Component\Process\Exception\LogicException
1092      * @expectedExceptionMessage Output can not be disabled while an idle timeout is set.
1093      */
1094     public function testDisableOutputWhileIdleTimeoutIsSet()
1095     {
1096         $process = $this->getProcess('foo');
1097         $process->setIdleTimeout(1);
1098         $process->disableOutput();
1099     }
1100
1101     /**
1102      * @expectedException \Symfony\Component\Process\Exception\LogicException
1103      * @expectedExceptionMessage timeout can not be set while the output is disabled.
1104      */
1105     public function testSetIdleTimeoutWhileOutputIsDisabled()
1106     {
1107         $process = $this->getProcess('foo');
1108         $process->disableOutput();
1109         $process->setIdleTimeout(1);
1110     }
1111
1112     public function testSetNullIdleTimeoutWhileOutputIsDisabled()
1113     {
1114         $process = $this->getProcess('foo');
1115         $process->disableOutput();
1116         $this->assertSame($process, $process->setIdleTimeout(null));
1117     }
1118
1119     /**
1120      * @dataProvider provideOutputFetchingMethods
1121      * @expectedException \Symfony\Component\Process\Exception\LogicException
1122      * @expectedExceptionMessage Output has been disabled.
1123      */
1124     public function testGetOutputWhileDisabled($fetchMethod)
1125     {
1126         $p = $this->getProcessForCode('sleep(41);');
1127         $p->disableOutput();
1128         $p->start();
1129         $p->{$fetchMethod}();
1130     }
1131
1132     public function provideOutputFetchingMethods()
1133     {
1134         return array(
1135             array('getOutput'),
1136             array('getIncrementalOutput'),
1137             array('getErrorOutput'),
1138             array('getIncrementalErrorOutput'),
1139         );
1140     }
1141
1142     public function testStopTerminatesProcessCleanly()
1143     {
1144         $process = $this->getProcessForCode('echo 123; sleep(42);');
1145         $process->run(function () use ($process) {
1146             $process->stop();
1147         });
1148         $this->assertTrue(true, 'A call to stop() is not expected to cause wait() to throw a RuntimeException');
1149     }
1150
1151     public function testKillSignalTerminatesProcessCleanly()
1152     {
1153         $process = $this->getProcessForCode('echo 123; sleep(43);');
1154         $process->run(function () use ($process) {
1155             $process->signal(9); // SIGKILL
1156         });
1157         $this->assertTrue(true, 'A call to signal() is not expected to cause wait() to throw a RuntimeException');
1158     }
1159
1160     public function testTermSignalTerminatesProcessCleanly()
1161     {
1162         $process = $this->getProcessForCode('echo 123; sleep(44);');
1163         $process->run(function () use ($process) {
1164             $process->signal(15); // SIGTERM
1165         });
1166         $this->assertTrue(true, 'A call to signal() is not expected to cause wait() to throw a RuntimeException');
1167     }
1168
1169     public function responsesCodeProvider()
1170     {
1171         return array(
1172             //expected output / getter / code to execute
1173             //array(1,'getExitCode','exit(1);'),
1174             //array(true,'isSuccessful','exit();'),
1175             array('output', 'getOutput', 'echo \'output\';'),
1176         );
1177     }
1178
1179     public function pipesCodeProvider()
1180     {
1181         $variations = array(
1182             'fwrite(STDOUT, $in = file_get_contents(\'php://stdin\')); fwrite(STDERR, $in);',
1183             'include \''.__DIR__.'/PipeStdinInStdoutStdErrStreamSelect.php\';',
1184         );
1185
1186         if ('\\' === DIRECTORY_SEPARATOR) {
1187             // Avoid XL buffers on Windows because of https://bugs.php.net/bug.php?id=65650
1188             $sizes = array(1, 2, 4, 8);
1189         } else {
1190             $sizes = array(1, 16, 64, 1024, 4096);
1191         }
1192
1193         $codes = array();
1194         foreach ($sizes as $size) {
1195             foreach ($variations as $code) {
1196                 $codes[] = array($code, $size);
1197             }
1198         }
1199
1200         return $codes;
1201     }
1202
1203     /**
1204      * @dataProvider provideVariousIncrementals
1205      */
1206     public function testIncrementalOutputDoesNotRequireAnotherCall($stream, $method)
1207     {
1208         $process = $this->getProcessForCode('$n = 0; while ($n < 3) { file_put_contents(\''.$stream.'\', $n, 1); $n++; usleep(1000); }', null, null, null, null);
1209         $process->start();
1210         $result = '';
1211         $limit = microtime(true) + 3;
1212         $expected = '012';
1213
1214         while ($result !== $expected && microtime(true) < $limit) {
1215             $result .= $process->$method();
1216         }
1217
1218         $this->assertSame($expected, $result);
1219         $process->stop();
1220     }
1221
1222     public function provideVariousIncrementals()
1223     {
1224         return array(
1225             array('php://stdout', 'getIncrementalOutput'),
1226             array('php://stderr', 'getIncrementalErrorOutput'),
1227         );
1228     }
1229
1230     public function testIteratorInput()
1231     {
1232         $input = function () {
1233             yield 'ping';
1234             yield 'pong';
1235         };
1236
1237         $process = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);', null, null, $input());
1238         $process->run();
1239         $this->assertSame('pingpong', $process->getOutput());
1240     }
1241
1242     public function testSimpleInputStream()
1243     {
1244         $input = new InputStream();
1245
1246         $process = $this->getProcessForCode('echo \'ping\'; echo fread(STDIN, 4); echo fread(STDIN, 4);');
1247         $process->setInput($input);
1248
1249         $process->start(function ($type, $data) use ($input) {
1250             if ('ping' === $data) {
1251                 $input->write('pang');
1252             } elseif (!$input->isClosed()) {
1253                 $input->write('pong');
1254                 $input->close();
1255             }
1256         });
1257
1258         $process->wait();
1259         $this->assertSame('pingpangpong', $process->getOutput());
1260     }
1261
1262     public function testInputStreamWithCallable()
1263     {
1264         $i = 0;
1265         $stream = fopen('php://memory', 'w+');
1266         $stream = function () use ($stream, &$i) {
1267             if ($i < 3) {
1268                 rewind($stream);
1269                 fwrite($stream, ++$i);
1270                 rewind($stream);
1271
1272                 return $stream;
1273             }
1274         };
1275
1276         $input = new InputStream();
1277         $input->onEmpty($stream);
1278         $input->write($stream());
1279
1280         $process = $this->getProcessForCode('echo fread(STDIN, 3);');
1281         $process->setInput($input);
1282         $process->start(function ($type, $data) use ($input) {
1283             $input->close();
1284         });
1285
1286         $process->wait();
1287         $this->assertSame('123', $process->getOutput());
1288     }
1289
1290     public function testInputStreamWithGenerator()
1291     {
1292         $input = new InputStream();
1293         $input->onEmpty(function ($input) {
1294             yield 'pong';
1295             $input->close();
1296         });
1297
1298         $process = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);');
1299         $process->setInput($input);
1300         $process->start();
1301         $input->write('ping');
1302         $process->wait();
1303         $this->assertSame('pingpong', $process->getOutput());
1304     }
1305
1306     public function testInputStreamOnEmpty()
1307     {
1308         $i = 0;
1309         $input = new InputStream();
1310         $input->onEmpty(function () use (&$i) { ++$i; });
1311
1312         $process = $this->getProcessForCode('echo 123; echo fread(STDIN, 1); echo 456;');
1313         $process->setInput($input);
1314         $process->start(function ($type, $data) use ($input) {
1315             if ('123' === $data) {
1316                 $input->close();
1317             }
1318         });
1319         $process->wait();
1320
1321         $this->assertSame(0, $i, 'InputStream->onEmpty callback should be called only when the input *becomes* empty');
1322         $this->assertSame('123456', $process->getOutput());
1323     }
1324
1325     public function testIteratorOutput()
1326     {
1327         $input = new InputStream();
1328
1329         $process = $this->getProcessForCode('fwrite(STDOUT, 123); fwrite(STDERR, 234); flush(); usleep(10000); fwrite(STDOUT, fread(STDIN, 3)); fwrite(STDERR, 456);');
1330         $process->setInput($input);
1331         $process->start();
1332         $output = array();
1333
1334         foreach ($process as $type => $data) {
1335             $output[] = array($type, $data);
1336             break;
1337         }
1338         $expectedOutput = array(
1339             array($process::OUT, '123'),
1340         );
1341         $this->assertSame($expectedOutput, $output);
1342
1343         $input->write(345);
1344
1345         foreach ($process as $type => $data) {
1346             $output[] = array($type, $data);
1347         }
1348
1349         $this->assertSame('', $process->getOutput());
1350         $this->assertFalse($process->isRunning());
1351
1352         $expectedOutput = array(
1353             array($process::OUT, '123'),
1354             array($process::ERR, '234'),
1355             array($process::OUT, '345'),
1356             array($process::ERR, '456'),
1357         );
1358         $this->assertSame($expectedOutput, $output);
1359     }
1360
1361     public function testNonBlockingNorClearingIteratorOutput()
1362     {
1363         $input = new InputStream();
1364
1365         $process = $this->getProcessForCode('fwrite(STDOUT, fread(STDIN, 3));');
1366         $process->setInput($input);
1367         $process->start();
1368         $output = array();
1369
1370         foreach ($process->getIterator($process::ITER_NON_BLOCKING | $process::ITER_KEEP_OUTPUT) as $type => $data) {
1371             $output[] = array($type, $data);
1372             break;
1373         }
1374         $expectedOutput = array(
1375             array($process::OUT, ''),
1376         );
1377         $this->assertSame($expectedOutput, $output);
1378
1379         $input->write(123);
1380
1381         foreach ($process->getIterator($process::ITER_NON_BLOCKING | $process::ITER_KEEP_OUTPUT) as $type => $data) {
1382             if ('' !== $data) {
1383                 $output[] = array($type, $data);
1384             }
1385         }
1386
1387         $this->assertSame('123', $process->getOutput());
1388         $this->assertFalse($process->isRunning());
1389
1390         $expectedOutput = array(
1391             array($process::OUT, ''),
1392             array($process::OUT, '123'),
1393         );
1394         $this->assertSame($expectedOutput, $output);
1395     }
1396
1397     public function testChainedProcesses()
1398     {
1399         $p1 = $this->getProcessForCode('fwrite(STDERR, 123); fwrite(STDOUT, 456);');
1400         $p2 = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);');
1401         $p2->setInput($p1);
1402
1403         $p1->start();
1404         $p2->run();
1405
1406         $this->assertSame('123', $p1->getErrorOutput());
1407         $this->assertSame('', $p1->getOutput());
1408         $this->assertSame('', $p2->getErrorOutput());
1409         $this->assertSame('456', $p2->getOutput());
1410     }
1411
1412     public function testSetBadEnv()
1413     {
1414         $process = $this->getProcess('echo hello');
1415         $process->setEnv(array('bad%%' => '123'));
1416         $process->inheritEnvironmentVariables(true);
1417
1418         $process->run();
1419
1420         $this->assertSame('hello'.PHP_EOL, $process->getOutput());
1421         $this->assertSame('', $process->getErrorOutput());
1422     }
1423
1424     public function testEnvBackupDoesNotDeleteExistingVars()
1425     {
1426         putenv('existing_var=foo');
1427         $_ENV['existing_var'] = 'foo';
1428         $process = $this->getProcess('php -r "echo getenv(\'new_test_var\');"');
1429         $process->setEnv(array('existing_var' => 'bar', 'new_test_var' => 'foo'));
1430         $process->inheritEnvironmentVariables();
1431
1432         $process->run();
1433
1434         $this->assertSame('foo', $process->getOutput());
1435         $this->assertSame('foo', getenv('existing_var'));
1436         $this->assertFalse(getenv('new_test_var'));
1437
1438         putenv('existing_var');
1439         unset($_ENV['existing_var']);
1440     }
1441
1442     public function testEnvIsInherited()
1443     {
1444         $process = $this->getProcessForCode('echo serialize($_SERVER);', null, array('BAR' => 'BAZ', 'EMPTY' => ''));
1445
1446         putenv('FOO=BAR');
1447         $_ENV['FOO'] = 'BAR';
1448
1449         $process->run();
1450
1451         $expected = array('BAR' => 'BAZ', 'EMPTY' => '', 'FOO' => 'BAR');
1452         $env = array_intersect_key(unserialize($process->getOutput()), $expected);
1453
1454         $this->assertEquals($expected, $env);
1455
1456         putenv('FOO');
1457         unset($_ENV['FOO']);
1458     }
1459
1460     /**
1461      * @group legacy
1462      */
1463     public function testInheritEnvDisabled()
1464     {
1465         $process = $this->getProcessForCode('echo serialize($_SERVER);', null, array('BAR' => 'BAZ'));
1466
1467         putenv('FOO=BAR');
1468         $_ENV['FOO'] = 'BAR';
1469
1470         $this->assertSame($process, $process->inheritEnvironmentVariables(false));
1471         $this->assertFalse($process->areEnvironmentVariablesInherited());
1472
1473         $process->run();
1474
1475         $expected = array('BAR' => 'BAZ', 'FOO' => 'BAR');
1476         $env = array_intersect_key(unserialize($process->getOutput()), $expected);
1477         unset($expected['FOO']);
1478
1479         $this->assertSame($expected, $env);
1480
1481         putenv('FOO');
1482         unset($_ENV['FOO']);
1483     }
1484
1485     public function testGetCommandLine()
1486     {
1487         $p = new Process(array('/usr/bin/php'));
1488
1489         $expected = '\\' === DIRECTORY_SEPARATOR ? '"/usr/bin/php"' : "'/usr/bin/php'";
1490         $this->assertSame($expected, $p->getCommandLine());
1491     }
1492
1493     /**
1494      * @dataProvider provideEscapeArgument
1495      */
1496     public function testEscapeArgument($arg)
1497     {
1498         $p = new Process(array(self::$phpBin, '-r', 'echo $argv[1];', $arg));
1499         $p->run();
1500
1501         $this->assertSame($arg, $p->getOutput());
1502     }
1503
1504     /**
1505      * @dataProvider provideEscapeArgument
1506      * @group legacy
1507      */
1508     public function testEscapeArgumentWhenInheritEnvDisabled($arg)
1509     {
1510         $p = new Process(array(self::$phpBin, '-r', 'echo $argv[1];', $arg), null, array('BAR' => 'BAZ'));
1511         $p->inheritEnvironmentVariables(false);
1512         $p->run();
1513
1514         $this->assertSame($arg, $p->getOutput());
1515     }
1516
1517     public function testRawCommandLine()
1518     {
1519         $p = new Process(sprintf('"%s" -r %s "a" "" "b"', self::$phpBin, escapeshellarg('print_r($argv);')));
1520         $p->run();
1521
1522         $expected = <<<EOTXT
1523 Array
1524 (
1525     [0] => -
1526     [1] => a
1527     [2] => 
1528     [3] => b
1529 )
1530
1531 EOTXT;
1532         $this->assertSame($expected, str_replace('Standard input code', '-', $p->getOutput()));
1533     }
1534
1535     public function provideEscapeArgument()
1536     {
1537         yield array('a"b%c%');
1538         yield array('a"b^c^');
1539         yield array("a\nb'c");
1540         yield array('a^b c!');
1541         yield array("a!b\tc");
1542         yield array('a\\\\"\\"');
1543         yield array('éÉèÈàÀöä');
1544     }
1545
1546     public function testEnvArgument()
1547     {
1548         $env = array('FOO' => 'Foo', 'BAR' => 'Bar');
1549         $cmd = '\\' === DIRECTORY_SEPARATOR ? 'echo !FOO! !BAR! !BAZ!' : 'echo $FOO $BAR $BAZ';
1550         $p = new Process($cmd, null, $env);
1551         $p->run(null, array('BAR' => 'baR', 'BAZ' => 'baZ'));
1552
1553         $this->assertSame('Foo baR baZ', rtrim($p->getOutput()));
1554         $this->assertSame($env, $p->getEnv());
1555     }
1556
1557     /**
1558      * @param string      $commandline
1559      * @param null|string $cwd
1560      * @param null|array  $env
1561      * @param null|string $input
1562      * @param int         $timeout
1563      * @param array       $options
1564      *
1565      * @return Process
1566      */
1567     private function getProcess($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60)
1568     {
1569         $process = new Process($commandline, $cwd, $env, $input, $timeout);
1570         $process->inheritEnvironmentVariables();
1571
1572         if (false !== $enhance = getenv('ENHANCE_SIGCHLD')) {
1573             try {
1574                 $process->setEnhanceSigchildCompatibility(false);
1575                 $process->getExitCode();
1576                 $this->fail('ENHANCE_SIGCHLD must be used together with a sigchild-enabled PHP.');
1577             } catch (RuntimeException $e) {
1578                 $this->assertSame('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.', $e->getMessage());
1579                 if ($enhance) {
1580                     $process->setEnhanceSigchildCompatibility(true);
1581                 } else {
1582                     self::$notEnhancedSigchild = true;
1583                 }
1584             }
1585         }
1586
1587         if (self::$process) {
1588             self::$process->stop(0);
1589         }
1590
1591         return self::$process = $process;
1592     }
1593
1594     /**
1595      * @return Process
1596      */
1597     private function getProcessForCode($code, $cwd = null, array $env = null, $input = null, $timeout = 60)
1598     {
1599         return $this->getProcess(array(self::$phpBin, '-r', $code), $cwd, $env, $input, $timeout);
1600     }
1601
1602     private function skipIfNotEnhancedSigchild($expectException = true)
1603     {
1604         if (self::$sigchild) {
1605             if (!$expectException) {
1606                 $this->markTestSkipped('PHP is compiled with --enable-sigchild.');
1607             } elseif (self::$notEnhancedSigchild) {
1608                 if (method_exists($this, 'expectException')) {
1609                     $this->expectException('Symfony\Component\Process\Exception\RuntimeException');
1610                     $this->expectExceptionMessage('This PHP has been compiled with --enable-sigchild.');
1611                 } else {
1612                     $this->setExpectedException('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild.');
1613                 }
1614             }
1615         }
1616     }
1617 }
1618
1619 class NonStringifiable
1620 {
1621 }