ProcessTest.php 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Process\Tests;
  11. use Symfony\Component\Process\Exception\LogicException;
  12. use Symfony\Component\Process\Exception\ProcessTimedOutException;
  13. use Symfony\Component\Process\Exception\RuntimeException;
  14. use Symfony\Component\Process\InputStream;
  15. use Symfony\Component\Process\PhpExecutableFinder;
  16. use Symfony\Component\Process\Pipes\PipesInterface;
  17. use Symfony\Component\Process\Process;
  18. /**
  19. * @author Robert Schönthal <seroscho@googlemail.com>
  20. */
  21. class ProcessTest extends \PHPUnit_Framework_TestCase
  22. {
  23. private static $phpBin;
  24. private static $process;
  25. private static $sigchild;
  26. private static $notEnhancedSigchild = false;
  27. public static function setUpBeforeClass()
  28. {
  29. $phpBin = new PhpExecutableFinder();
  30. self::$phpBin = getenv('SYMFONY_PROCESS_PHP_TEST_BINARY') ?: ('phpdbg' === PHP_SAPI ? 'php' : $phpBin->find());
  31. if ('\\' !== DIRECTORY_SEPARATOR) {
  32. // exec is mandatory to deal with sending a signal to the process
  33. // see https://github.com/symfony/symfony/issues/5030 about prepending
  34. // command with exec
  35. self::$phpBin = 'exec '.self::$phpBin;
  36. }
  37. ob_start();
  38. phpinfo(INFO_GENERAL);
  39. self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
  40. }
  41. protected function tearDown()
  42. {
  43. if (self::$process) {
  44. self::$process->stop(0);
  45. self::$process = null;
  46. }
  47. }
  48. public function testThatProcessDoesNotThrowWarningDuringRun()
  49. {
  50. if ('\\' === DIRECTORY_SEPARATOR) {
  51. $this->markTestSkipped('This test is transient on Windows');
  52. }
  53. @trigger_error('Test Error', E_USER_NOTICE);
  54. $process = $this->getProcess(self::$phpBin." -r 'sleep(3)'");
  55. $process->run();
  56. $actualError = error_get_last();
  57. $this->assertEquals('Test Error', $actualError['message']);
  58. $this->assertEquals(E_USER_NOTICE, $actualError['type']);
  59. }
  60. /**
  61. * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
  62. */
  63. public function testNegativeTimeoutFromConstructor()
  64. {
  65. $this->getProcess('', null, null, null, -1);
  66. }
  67. /**
  68. * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
  69. */
  70. public function testNegativeTimeoutFromSetter()
  71. {
  72. $p = $this->getProcess('');
  73. $p->setTimeout(-1);
  74. }
  75. public function testFloatAndNullTimeout()
  76. {
  77. $p = $this->getProcess('');
  78. $p->setTimeout(10);
  79. $this->assertSame(10.0, $p->getTimeout());
  80. $p->setTimeout(null);
  81. $this->assertNull($p->getTimeout());
  82. $p->setTimeout(0.0);
  83. $this->assertNull($p->getTimeout());
  84. }
  85. /**
  86. * @requires extension pcntl
  87. */
  88. public function testStopWithTimeoutIsActuallyWorking()
  89. {
  90. $p = $this->getProcess(self::$phpBin.' '.__DIR__.'/NonStopableProcess.php 30');
  91. $p->start();
  92. while (false === strpos($p->getOutput(), 'received')) {
  93. usleep(1000);
  94. }
  95. $start = microtime(true);
  96. $p->stop(0.1);
  97. $p->wait();
  98. $this->assertLessThan(15, microtime(true) - $start);
  99. }
  100. public function testAllOutputIsActuallyReadOnTermination()
  101. {
  102. // this code will result in a maximum of 2 reads of 8192 bytes by calling
  103. // start() and isRunning(). by the time getOutput() is called the process
  104. // has terminated so the internal pipes array is already empty. normally
  105. // the call to start() will not read any data as the process will not have
  106. // generated output, but this is non-deterministic so we must count it as
  107. // a possibility. therefore we need 2 * PipesInterface::CHUNK_SIZE plus
  108. // another byte which will never be read.
  109. $expectedOutputSize = PipesInterface::CHUNK_SIZE * 2 + 2;
  110. $code = sprintf('echo str_repeat(\'*\', %d);', $expectedOutputSize);
  111. $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg($code)));
  112. $p->start();
  113. // Don't call Process::run nor Process::wait to avoid any read of pipes
  114. $h = new \ReflectionProperty($p, 'process');
  115. $h->setAccessible(true);
  116. $h = $h->getValue($p);
  117. $s = @proc_get_status($h);
  118. while (!empty($s['running'])) {
  119. usleep(1000);
  120. $s = proc_get_status($h);
  121. }
  122. $o = $p->getOutput();
  123. $this->assertEquals($expectedOutputSize, strlen($o));
  124. }
  125. public function testCallbacksAreExecutedWithStart()
  126. {
  127. $process = $this->getProcess('echo foo');
  128. $process->start(function ($type, $buffer) use (&$data) {
  129. $data .= $buffer;
  130. });
  131. $process->wait();
  132. $this->assertSame('foo'.PHP_EOL, $data);
  133. }
  134. /**
  135. * tests results from sub processes.
  136. *
  137. * @dataProvider responsesCodeProvider
  138. */
  139. public function testProcessResponses($expected, $getter, $code)
  140. {
  141. $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg($code)));
  142. $p->run();
  143. $this->assertSame($expected, $p->$getter());
  144. }
  145. /**
  146. * tests results from sub processes.
  147. *
  148. * @dataProvider pipesCodeProvider
  149. */
  150. public function testProcessPipes($code, $size)
  151. {
  152. $expected = str_repeat(str_repeat('*', 1024), $size).'!';
  153. $expectedLength = (1024 * $size) + 1;
  154. $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg($code)));
  155. $p->setInput($expected);
  156. $p->run();
  157. $this->assertEquals($expectedLength, strlen($p->getOutput()));
  158. $this->assertEquals($expectedLength, strlen($p->getErrorOutput()));
  159. }
  160. /**
  161. * @dataProvider pipesCodeProvider
  162. */
  163. public function testSetStreamAsInput($code, $size)
  164. {
  165. $expected = str_repeat(str_repeat('*', 1024), $size).'!';
  166. $expectedLength = (1024 * $size) + 1;
  167. $stream = fopen('php://temporary', 'w+');
  168. fwrite($stream, $expected);
  169. rewind($stream);
  170. $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg($code)));
  171. $p->setInput($stream);
  172. $p->run();
  173. fclose($stream);
  174. $this->assertEquals($expectedLength, strlen($p->getOutput()));
  175. $this->assertEquals($expectedLength, strlen($p->getErrorOutput()));
  176. }
  177. public function testLiveStreamAsInput()
  178. {
  179. $stream = fopen('php://memory', 'r+');
  180. fwrite($stream, 'hello');
  181. rewind($stream);
  182. $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('stream_copy_to_stream(STDIN, STDOUT);')));
  183. $p->setInput($stream);
  184. $p->start(function ($type, $data) use ($stream) {
  185. if ('hello' === $data) {
  186. fclose($stream);
  187. }
  188. });
  189. $p->wait();
  190. $this->assertSame('hello', $p->getOutput());
  191. }
  192. /**
  193. * @expectedException \Symfony\Component\Process\Exception\LogicException
  194. * @expectedExceptionMessage Input can not be set while the process is running.
  195. */
  196. public function testSetInputWhileRunningThrowsAnException()
  197. {
  198. $process = $this->getProcess(self::$phpBin.' -r "sleep(30);"');
  199. $process->start();
  200. try {
  201. $process->setInput('foobar');
  202. $process->stop();
  203. $this->fail('A LogicException should have been raised.');
  204. } catch (LogicException $e) {
  205. }
  206. $process->stop();
  207. throw $e;
  208. }
  209. /**
  210. * @dataProvider provideInvalidInputValues
  211. * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
  212. * @expectedExceptionMessage Symfony\Component\Process\Process::setInput only accepts strings, Traversable objects or stream resources.
  213. */
  214. public function testInvalidInput($value)
  215. {
  216. $process = $this->getProcess('foo');
  217. $process->setInput($value);
  218. }
  219. public function provideInvalidInputValues()
  220. {
  221. return array(
  222. array(array()),
  223. array(new NonStringifiable()),
  224. );
  225. }
  226. /**
  227. * @dataProvider provideInputValues
  228. */
  229. public function testValidInput($expected, $value)
  230. {
  231. $process = $this->getProcess('foo');
  232. $process->setInput($value);
  233. $this->assertSame($expected, $process->getInput());
  234. }
  235. public function provideInputValues()
  236. {
  237. return array(
  238. array(null, null),
  239. array('24.5', 24.5),
  240. array('input data', 'input data'),
  241. );
  242. }
  243. public function chainedCommandsOutputProvider()
  244. {
  245. if ('\\' === DIRECTORY_SEPARATOR) {
  246. return array(
  247. array("2 \r\n2\r\n", '&&', '2'),
  248. );
  249. }
  250. return array(
  251. array("1\n1\n", ';', '1'),
  252. array("2\n2\n", '&&', '2'),
  253. );
  254. }
  255. /**
  256. * @dataProvider chainedCommandsOutputProvider
  257. */
  258. public function testChainedCommandsOutput($expected, $operator, $input)
  259. {
  260. $process = $this->getProcess(sprintf('echo %s %s echo %s', $input, $operator, $input));
  261. $process->run();
  262. $this->assertEquals($expected, $process->getOutput());
  263. }
  264. public function testCallbackIsExecutedForOutput()
  265. {
  266. $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('echo \'foo\';')));
  267. $called = false;
  268. $p->run(function ($type, $buffer) use (&$called) {
  269. $called = $buffer === 'foo';
  270. });
  271. $this->assertTrue($called, 'The callback should be executed with the output');
  272. }
  273. public function testCallbackIsExecutedForOutputWheneverOutputIsDisabled()
  274. {
  275. $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('echo \'foo\';')));
  276. $p->disableOutput();
  277. $called = false;
  278. $p->run(function ($type, $buffer) use (&$called) {
  279. $called = $buffer === 'foo';
  280. });
  281. $this->assertTrue($called, 'The callback should be executed with the output');
  282. }
  283. public function testGetErrorOutput()
  284. {
  285. $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }')));
  286. $p->run();
  287. $this->assertEquals(3, preg_match_all('/ERROR/', $p->getErrorOutput(), $matches));
  288. }
  289. public function testFlushErrorOutput()
  290. {
  291. $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }')));
  292. $p->run();
  293. $p->clearErrorOutput();
  294. $this->assertEmpty($p->getErrorOutput());
  295. }
  296. /**
  297. * @dataProvider provideIncrementalOutput
  298. */
  299. public function testIncrementalOutput($getOutput, $getIncrementalOutput, $uri)
  300. {
  301. $lock = tempnam(sys_get_temp_dir(), __FUNCTION__);
  302. $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('file_put_contents($s = \''.$uri.'\', \'foo\'); flock(fopen('.var_export($lock, true).', \'r\'), LOCK_EX); file_put_contents($s, \'bar\');')));
  303. $h = fopen($lock, 'w');
  304. flock($h, LOCK_EX);
  305. $p->start();
  306. foreach (array('foo', 'bar') as $s) {
  307. while (false === strpos($p->$getOutput(), $s)) {
  308. usleep(1000);
  309. }
  310. $this->assertSame($s, $p->$getIncrementalOutput());
  311. $this->assertSame('', $p->$getIncrementalOutput());
  312. flock($h, LOCK_UN);
  313. }
  314. fclose($h);
  315. }
  316. public function provideIncrementalOutput()
  317. {
  318. return array(
  319. array('getOutput', 'getIncrementalOutput', 'php://stdout'),
  320. array('getErrorOutput', 'getIncrementalErrorOutput', 'php://stderr'),
  321. );
  322. }
  323. public function testGetOutput()
  324. {
  325. $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('$n = 0; while ($n < 3) { echo \' foo \'; $n++; }')));
  326. $p->run();
  327. $this->assertEquals(3, preg_match_all('/foo/', $p->getOutput(), $matches));
  328. }
  329. public function testFlushOutput()
  330. {
  331. $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('$n=0;while ($n<3) {echo \' foo \';$n++;}')));
  332. $p->run();
  333. $p->clearOutput();
  334. $this->assertEmpty($p->getOutput());
  335. }
  336. public function testZeroAsOutput()
  337. {
  338. if ('\\' === DIRECTORY_SEPARATOR) {
  339. // see http://stackoverflow.com/questions/7105433/windows-batch-echo-without-new-line
  340. $p = $this->getProcess('echo | set /p dummyName=0');
  341. } else {
  342. $p = $this->getProcess('printf 0');
  343. }
  344. $p->run();
  345. $this->assertSame('0', $p->getOutput());
  346. }
  347. public function testExitCodeCommandFailed()
  348. {
  349. if ('\\' === DIRECTORY_SEPARATOR) {
  350. $this->markTestSkipped('Windows does not support POSIX exit code');
  351. }
  352. $this->skipIfNotEnhancedSigchild();
  353. // such command run in bash return an exitcode 127
  354. $process = $this->getProcess('nonexistingcommandIhopeneversomeonewouldnameacommandlikethis');
  355. $process->run();
  356. $this->assertGreaterThan(0, $process->getExitCode());
  357. }
  358. public function testTTYCommand()
  359. {
  360. if ('\\' === DIRECTORY_SEPARATOR) {
  361. $this->markTestSkipped('Windows does not have /dev/tty support');
  362. }
  363. $process = $this->getProcess('echo "foo" >> /dev/null && '.self::$phpBin.' -r "usleep(100000);"');
  364. $process->setTty(true);
  365. $process->start();
  366. $this->assertTrue($process->isRunning());
  367. $process->wait();
  368. $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
  369. }
  370. public function testTTYCommandExitCode()
  371. {
  372. if ('\\' === DIRECTORY_SEPARATOR) {
  373. $this->markTestSkipped('Windows does have /dev/tty support');
  374. }
  375. $this->skipIfNotEnhancedSigchild();
  376. $process = $this->getProcess('echo "foo" >> /dev/null');
  377. $process->setTty(true);
  378. $process->run();
  379. $this->assertTrue($process->isSuccessful());
  380. }
  381. /**
  382. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  383. * @expectedExceptionMessage TTY mode is not supported on Windows platform.
  384. */
  385. public function testTTYInWindowsEnvironment()
  386. {
  387. if ('\\' !== DIRECTORY_SEPARATOR) {
  388. $this->markTestSkipped('This test is for Windows platform only');
  389. }
  390. $process = $this->getProcess('echo "foo" >> /dev/null');
  391. $process->setTty(false);
  392. $process->setTty(true);
  393. }
  394. public function testExitCodeTextIsNullWhenExitCodeIsNull()
  395. {
  396. $this->skipIfNotEnhancedSigchild();
  397. $process = $this->getProcess('');
  398. $this->assertNull($process->getExitCodeText());
  399. }
  400. public function testPTYCommand()
  401. {
  402. if (!Process::isPtySupported()) {
  403. $this->markTestSkipped('PTY is not supported on this operating system.');
  404. }
  405. $process = $this->getProcess('echo "foo"');
  406. $process->setPty(true);
  407. $process->run();
  408. $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
  409. $this->assertEquals("foo\r\n", $process->getOutput());
  410. }
  411. public function testMustRun()
  412. {
  413. $this->skipIfNotEnhancedSigchild();
  414. $process = $this->getProcess('echo foo');
  415. $this->assertSame($process, $process->mustRun());
  416. $this->assertEquals('foo'.PHP_EOL, $process->getOutput());
  417. }
  418. public function testSuccessfulMustRunHasCorrectExitCode()
  419. {
  420. $this->skipIfNotEnhancedSigchild();
  421. $process = $this->getProcess('echo foo')->mustRun();
  422. $this->assertEquals(0, $process->getExitCode());
  423. }
  424. /**
  425. * @expectedException \Symfony\Component\Process\Exception\ProcessFailedException
  426. */
  427. public function testMustRunThrowsException()
  428. {
  429. $this->skipIfNotEnhancedSigchild();
  430. $process = $this->getProcess('exit 1');
  431. $process->mustRun();
  432. }
  433. public function testExitCodeText()
  434. {
  435. $this->skipIfNotEnhancedSigchild();
  436. $process = $this->getProcess('');
  437. $r = new \ReflectionObject($process);
  438. $p = $r->getProperty('exitcode');
  439. $p->setAccessible(true);
  440. $p->setValue($process, 2);
  441. $this->assertEquals('Misuse of shell builtins', $process->getExitCodeText());
  442. }
  443. public function testStartIsNonBlocking()
  444. {
  445. $process = $this->getProcess(self::$phpBin.' -r "usleep(500000);"');
  446. $start = microtime(true);
  447. $process->start();
  448. $end = microtime(true);
  449. $this->assertLessThan(0.4, $end - $start);
  450. $process->stop();
  451. }
  452. public function testUpdateStatus()
  453. {
  454. $process = $this->getProcess('echo foo');
  455. $process->run();
  456. $this->assertTrue(strlen($process->getOutput()) > 0);
  457. }
  458. public function testGetExitCodeIsNullOnStart()
  459. {
  460. $this->skipIfNotEnhancedSigchild();
  461. $process = $this->getProcess(self::$phpBin.' -r "usleep(100000);"');
  462. $this->assertNull($process->getExitCode());
  463. $process->start();
  464. $this->assertNull($process->getExitCode());
  465. $process->wait();
  466. $this->assertEquals(0, $process->getExitCode());
  467. }
  468. public function testGetExitCodeIsNullOnWhenStartingAgain()
  469. {
  470. $this->skipIfNotEnhancedSigchild();
  471. $process = $this->getProcess(self::$phpBin.' -r "usleep(100000);"');
  472. $process->run();
  473. $this->assertEquals(0, $process->getExitCode());
  474. $process->start();
  475. $this->assertNull($process->getExitCode());
  476. $process->wait();
  477. $this->assertEquals(0, $process->getExitCode());
  478. }
  479. public function testGetExitCode()
  480. {
  481. $this->skipIfNotEnhancedSigchild();
  482. $process = $this->getProcess('echo foo');
  483. $process->run();
  484. $this->assertSame(0, $process->getExitCode());
  485. }
  486. public function testStatus()
  487. {
  488. $process = $this->getProcess(self::$phpBin.' -r "usleep(100000);"');
  489. $this->assertFalse($process->isRunning());
  490. $this->assertFalse($process->isStarted());
  491. $this->assertFalse($process->isTerminated());
  492. $this->assertSame(Process::STATUS_READY, $process->getStatus());
  493. $process->start();
  494. $this->assertTrue($process->isRunning());
  495. $this->assertTrue($process->isStarted());
  496. $this->assertFalse($process->isTerminated());
  497. $this->assertSame(Process::STATUS_STARTED, $process->getStatus());
  498. $process->wait();
  499. $this->assertFalse($process->isRunning());
  500. $this->assertTrue($process->isStarted());
  501. $this->assertTrue($process->isTerminated());
  502. $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
  503. }
  504. public function testStop()
  505. {
  506. $process = $this->getProcess(self::$phpBin.' -r "sleep(31);"');
  507. $process->start();
  508. $this->assertTrue($process->isRunning());
  509. $process->stop();
  510. $this->assertFalse($process->isRunning());
  511. }
  512. public function testIsSuccessful()
  513. {
  514. $this->skipIfNotEnhancedSigchild();
  515. $process = $this->getProcess('echo foo');
  516. $process->run();
  517. $this->assertTrue($process->isSuccessful());
  518. }
  519. public function testIsSuccessfulOnlyAfterTerminated()
  520. {
  521. $this->skipIfNotEnhancedSigchild();
  522. $process = $this->getProcess(self::$phpBin.' -r "usleep(100000);"');
  523. $process->start();
  524. $this->assertFalse($process->isSuccessful());
  525. $process->wait();
  526. $this->assertTrue($process->isSuccessful());
  527. }
  528. public function testIsNotSuccessful()
  529. {
  530. $this->skipIfNotEnhancedSigchild();
  531. $process = $this->getProcess(self::$phpBin.' -r "throw new \Exception(\'BOUM\');"');
  532. $process->run();
  533. $this->assertFalse($process->isSuccessful());
  534. }
  535. public function testProcessIsNotSignaled()
  536. {
  537. if ('\\' === DIRECTORY_SEPARATOR) {
  538. $this->markTestSkipped('Windows does not support POSIX signals');
  539. }
  540. $this->skipIfNotEnhancedSigchild();
  541. $process = $this->getProcess('echo foo');
  542. $process->run();
  543. $this->assertFalse($process->hasBeenSignaled());
  544. }
  545. public function testProcessWithoutTermSignal()
  546. {
  547. if ('\\' === DIRECTORY_SEPARATOR) {
  548. $this->markTestSkipped('Windows does not support POSIX signals');
  549. }
  550. $this->skipIfNotEnhancedSigchild();
  551. $process = $this->getProcess('echo foo');
  552. $process->run();
  553. $this->assertEquals(0, $process->getTermSignal());
  554. }
  555. public function testProcessIsSignaledIfStopped()
  556. {
  557. if ('\\' === DIRECTORY_SEPARATOR) {
  558. $this->markTestSkipped('Windows does not support POSIX signals');
  559. }
  560. $this->skipIfNotEnhancedSigchild();
  561. $process = $this->getProcess(self::$phpBin.' -r "sleep(32);"');
  562. $process->start();
  563. $process->stop();
  564. $this->assertTrue($process->hasBeenSignaled());
  565. $this->assertEquals(15, $process->getTermSignal()); // SIGTERM
  566. }
  567. /**
  568. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  569. * @expectedExceptionMessage The process has been signaled
  570. */
  571. public function testProcessThrowsExceptionWhenExternallySignaled()
  572. {
  573. if (!function_exists('posix_kill')) {
  574. $this->markTestSkipped('Function posix_kill is required.');
  575. }
  576. $this->skipIfNotEnhancedSigchild(false);
  577. $process = $this->getProcess(self::$phpBin.' -r "sleep(32.1)"');
  578. $process->start();
  579. posix_kill($process->getPid(), 9); // SIGKILL
  580. $process->wait();
  581. }
  582. public function testRestart()
  583. {
  584. $process1 = $this->getProcess(self::$phpBin.' -r "echo getmypid();"');
  585. $process1->run();
  586. $process2 = $process1->restart();
  587. $process2->wait(); // wait for output
  588. // Ensure that both processed finished and the output is numeric
  589. $this->assertFalse($process1->isRunning());
  590. $this->assertFalse($process2->isRunning());
  591. $this->assertTrue(is_numeric($process1->getOutput()));
  592. $this->assertTrue(is_numeric($process2->getOutput()));
  593. // Ensure that restart returned a new process by check that the output is different
  594. $this->assertNotEquals($process1->getOutput(), $process2->getOutput());
  595. }
  596. /**
  597. * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
  598. * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
  599. */
  600. public function testRunProcessWithTimeout()
  601. {
  602. $process = $this->getProcess(self::$phpBin.' -r "sleep(30);"');
  603. $process->setTimeout(0.1);
  604. $start = microtime(true);
  605. try {
  606. $process->run();
  607. $this->fail('A RuntimeException should have been raised');
  608. } catch (RuntimeException $e) {
  609. }
  610. $this->assertLessThan(15, microtime(true) - $start);
  611. throw $e;
  612. }
  613. /**
  614. * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
  615. * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
  616. */
  617. public function testIterateOverProcessWithTimeout()
  618. {
  619. $process = $this->getProcess(self::$phpBin.' -r "sleep(30);"');
  620. $process->setTimeout(0.1);
  621. $start = microtime(true);
  622. try {
  623. $process->start();
  624. foreach ($process as $buffer);
  625. $this->fail('A RuntimeException should have been raised');
  626. } catch (RuntimeException $e) {
  627. }
  628. $this->assertLessThan(15, microtime(true) - $start);
  629. throw $e;
  630. }
  631. public function testCheckTimeoutOnNonStartedProcess()
  632. {
  633. $process = $this->getProcess('echo foo');
  634. $this->assertNull($process->checkTimeout());
  635. }
  636. public function testCheckTimeoutOnTerminatedProcess()
  637. {
  638. $process = $this->getProcess('echo foo');
  639. $process->run();
  640. $this->assertNull($process->checkTimeout());
  641. }
  642. /**
  643. * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
  644. * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
  645. */
  646. public function testCheckTimeoutOnStartedProcess()
  647. {
  648. $process = $this->getProcess(self::$phpBin.' -r "sleep(33);"');
  649. $process->setTimeout(0.1);
  650. $process->start();
  651. $start = microtime(true);
  652. try {
  653. while ($process->isRunning()) {
  654. $process->checkTimeout();
  655. usleep(100000);
  656. }
  657. $this->fail('A ProcessTimedOutException should have been raised');
  658. } catch (ProcessTimedOutException $e) {
  659. }
  660. $this->assertLessThan(15, microtime(true) - $start);
  661. throw $e;
  662. }
  663. public function testIdleTimeout()
  664. {
  665. $process = $this->getProcess(self::$phpBin.' -r "sleep(34);"');
  666. $process->setTimeout(60);
  667. $process->setIdleTimeout(0.1);
  668. try {
  669. $process->run();
  670. $this->fail('A timeout exception was expected.');
  671. } catch (ProcessTimedOutException $e) {
  672. $this->assertTrue($e->isIdleTimeout());
  673. $this->assertFalse($e->isGeneralTimeout());
  674. $this->assertEquals(0.1, $e->getExceededTimeout());
  675. }
  676. }
  677. public function testIdleTimeoutNotExceededWhenOutputIsSent()
  678. {
  679. $process = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('while (true) {echo \'foo \'; usleep(1000);}')));
  680. $process->setTimeout(1);
  681. $process->start();
  682. while (false === strpos($process->getOutput(), 'foo')) {
  683. usleep(1000);
  684. }
  685. $process->setIdleTimeout(0.5);
  686. try {
  687. $process->wait();
  688. $this->fail('A timeout exception was expected.');
  689. } catch (ProcessTimedOutException $e) {
  690. $this->assertTrue($e->isGeneralTimeout(), 'A general timeout is expected.');
  691. $this->assertFalse($e->isIdleTimeout(), 'No idle timeout is expected.');
  692. $this->assertEquals(1, $e->getExceededTimeout());
  693. }
  694. }
  695. /**
  696. * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
  697. * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
  698. */
  699. public function testStartAfterATimeout()
  700. {
  701. $process = $this->getProcess(self::$phpBin.' -r "sleep(35);"');
  702. $process->setTimeout(0.1);
  703. try {
  704. $process->run();
  705. $this->fail('A ProcessTimedOutException should have been raised.');
  706. } catch (ProcessTimedOutException $e) {
  707. }
  708. $this->assertFalse($process->isRunning());
  709. $process->start();
  710. $this->assertTrue($process->isRunning());
  711. $process->stop(0);
  712. throw $e;
  713. }
  714. public function testGetPid()
  715. {
  716. $process = $this->getProcess(self::$phpBin.' -r "sleep(36);"');
  717. $process->start();
  718. $this->assertGreaterThan(0, $process->getPid());
  719. $process->stop(0);
  720. }
  721. public function testGetPidIsNullBeforeStart()
  722. {
  723. $process = $this->getProcess('foo');
  724. $this->assertNull($process->getPid());
  725. }
  726. public function testGetPidIsNullAfterRun()
  727. {
  728. $process = $this->getProcess('echo foo');
  729. $process->run();
  730. $this->assertNull($process->getPid());
  731. }
  732. /**
  733. * @requires extension pcntl
  734. */
  735. public function testSignal()
  736. {
  737. $process = $this->getProcess(self::$phpBin.' '.__DIR__.'/SignalListener.php');
  738. $process->start();
  739. while (false === strpos($process->getOutput(), 'Caught')) {
  740. usleep(1000);
  741. }
  742. $process->signal(SIGUSR1);
  743. $process->wait();
  744. $this->assertEquals('Caught SIGUSR1', $process->getOutput());
  745. }
  746. /**
  747. * @requires extension pcntl
  748. */
  749. public function testExitCodeIsAvailableAfterSignal()
  750. {
  751. $this->skipIfNotEnhancedSigchild();
  752. $process = $this->getProcess('sleep 4');
  753. $process->start();
  754. $process->signal(SIGKILL);
  755. while ($process->isRunning()) {
  756. usleep(10000);
  757. }
  758. $this->assertFalse($process->isRunning());
  759. $this->assertTrue($process->hasBeenSignaled());
  760. $this->assertFalse($process->isSuccessful());
  761. $this->assertEquals(137, $process->getExitCode());
  762. }
  763. /**
  764. * @expectedException \Symfony\Component\Process\Exception\LogicException
  765. * @expectedExceptionMessage Can not send signal on a non running process.
  766. */
  767. public function testSignalProcessNotRunning()
  768. {
  769. $process = $this->getProcess('foo');
  770. $process->signal(1); // SIGHUP
  771. }
  772. /**
  773. * @dataProvider provideMethodsThatNeedARunningProcess
  774. */
  775. public function testMethodsThatNeedARunningProcess($method)
  776. {
  777. $process = $this->getProcess('foo');
  778. $this->setExpectedException('Symfony\Component\Process\Exception\LogicException', sprintf('Process must be started before calling %s.', $method));
  779. $process->{$method}();
  780. }
  781. public function provideMethodsThatNeedARunningProcess()
  782. {
  783. return array(
  784. array('getOutput'),
  785. array('getIncrementalOutput'),
  786. array('getErrorOutput'),
  787. array('getIncrementalErrorOutput'),
  788. array('wait'),
  789. );
  790. }
  791. /**
  792. * @dataProvider provideMethodsThatNeedATerminatedProcess
  793. * @expectedException \Symfony\Component\Process\Exception\LogicException
  794. * @expectedExceptionMessage Process must be terminated before calling
  795. */
  796. public function testMethodsThatNeedATerminatedProcess($method)
  797. {
  798. $process = $this->getProcess(self::$phpBin.' -r "sleep(37);"');
  799. $process->start();
  800. try {
  801. $process->{$method}();
  802. $process->stop(0);
  803. $this->fail('A LogicException must have been thrown');
  804. } catch (\Exception $e) {
  805. }
  806. $process->stop(0);
  807. throw $e;
  808. }
  809. public function provideMethodsThatNeedATerminatedProcess()
  810. {
  811. return array(
  812. array('hasBeenSignaled'),
  813. array('getTermSignal'),
  814. array('hasBeenStopped'),
  815. array('getStopSignal'),
  816. );
  817. }
  818. /**
  819. * @dataProvider provideWrongSignal
  820. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  821. */
  822. public function testWrongSignal($signal)
  823. {
  824. if ('\\' === DIRECTORY_SEPARATOR) {
  825. $this->markTestSkipped('POSIX signals do not work on Windows');
  826. }
  827. $process = $this->getProcess(self::$phpBin.' -r "sleep(38);"');
  828. $process->start();
  829. try {
  830. $process->signal($signal);
  831. $this->fail('A RuntimeException must have been thrown');
  832. } catch (RuntimeException $e) {
  833. $process->stop(0);
  834. }
  835. throw $e;
  836. }
  837. public function provideWrongSignal()
  838. {
  839. return array(
  840. array(-4),
  841. array('Céphalopodes'),
  842. );
  843. }
  844. public function testDisableOutputDisablesTheOutput()
  845. {
  846. $p = $this->getProcess('foo');
  847. $this->assertFalse($p->isOutputDisabled());
  848. $p->disableOutput();
  849. $this->assertTrue($p->isOutputDisabled());
  850. $p->enableOutput();
  851. $this->assertFalse($p->isOutputDisabled());
  852. }
  853. /**
  854. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  855. * @expectedExceptionMessage Disabling output while the process is running is not possible.
  856. */
  857. public function testDisableOutputWhileRunningThrowsException()
  858. {
  859. $p = $this->getProcess(self::$phpBin.' -r "sleep(39);"');
  860. $p->start();
  861. $p->disableOutput();
  862. }
  863. /**
  864. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  865. * @expectedExceptionMessage Enabling output while the process is running is not possible.
  866. */
  867. public function testEnableOutputWhileRunningThrowsException()
  868. {
  869. $p = $this->getProcess(self::$phpBin.' -r "sleep(40);"');
  870. $p->disableOutput();
  871. $p->start();
  872. $p->enableOutput();
  873. }
  874. public function testEnableOrDisableOutputAfterRunDoesNotThrowException()
  875. {
  876. $p = $this->getProcess('echo foo');
  877. $p->disableOutput();
  878. $p->run();
  879. $p->enableOutput();
  880. $p->disableOutput();
  881. $this->assertTrue($p->isOutputDisabled());
  882. }
  883. /**
  884. * @expectedException \Symfony\Component\Process\Exception\LogicException
  885. * @expectedExceptionMessage Output can not be disabled while an idle timeout is set.
  886. */
  887. public function testDisableOutputWhileIdleTimeoutIsSet()
  888. {
  889. $process = $this->getProcess('foo');
  890. $process->setIdleTimeout(1);
  891. $process->disableOutput();
  892. }
  893. /**
  894. * @expectedException \Symfony\Component\Process\Exception\LogicException
  895. * @expectedExceptionMessage timeout can not be set while the output is disabled.
  896. */
  897. public function testSetIdleTimeoutWhileOutputIsDisabled()
  898. {
  899. $process = $this->getProcess('foo');
  900. $process->disableOutput();
  901. $process->setIdleTimeout(1);
  902. }
  903. public function testSetNullIdleTimeoutWhileOutputIsDisabled()
  904. {
  905. $process = $this->getProcess('foo');
  906. $process->disableOutput();
  907. $this->assertSame($process, $process->setIdleTimeout(null));
  908. }
  909. /**
  910. * @dataProvider provideOutputFetchingMethods
  911. * @expectedException \Symfony\Component\Process\Exception\LogicException
  912. * @expectedExceptionMessage Output has been disabled.
  913. */
  914. public function testGetOutputWhileDisabled($fetchMethod)
  915. {
  916. $p = $this->getProcess(self::$phpBin.' -r "sleep(41);"');
  917. $p->disableOutput();
  918. $p->start();
  919. $p->{$fetchMethod}();
  920. }
  921. public function provideOutputFetchingMethods()
  922. {
  923. return array(
  924. array('getOutput'),
  925. array('getIncrementalOutput'),
  926. array('getErrorOutput'),
  927. array('getIncrementalErrorOutput'),
  928. );
  929. }
  930. public function testStopTerminatesProcessCleanly()
  931. {
  932. $process = $this->getProcess(self::$phpBin.' -r "echo 123; sleep(42);"');
  933. $process->run(function () use ($process) {
  934. $process->stop();
  935. });
  936. $this->assertTrue(true, 'A call to stop() is not expected to cause wait() to throw a RuntimeException');
  937. }
  938. public function testKillSignalTerminatesProcessCleanly()
  939. {
  940. $process = $this->getProcess(self::$phpBin.' -r "echo 123; sleep(43);"');
  941. $process->run(function () use ($process) {
  942. $process->signal(9); // SIGKILL
  943. });
  944. $this->assertTrue(true, 'A call to signal() is not expected to cause wait() to throw a RuntimeException');
  945. }
  946. public function testTermSignalTerminatesProcessCleanly()
  947. {
  948. $process = $this->getProcess(self::$phpBin.' -r "echo 123; sleep(44);"');
  949. $process->run(function () use ($process) {
  950. $process->signal(15); // SIGTERM
  951. });
  952. $this->assertTrue(true, 'A call to signal() is not expected to cause wait() to throw a RuntimeException');
  953. }
  954. public function responsesCodeProvider()
  955. {
  956. return array(
  957. //expected output / getter / code to execute
  958. //array(1,'getExitCode','exit(1);'),
  959. //array(true,'isSuccessful','exit();'),
  960. array('output', 'getOutput', 'echo \'output\';'),
  961. );
  962. }
  963. public function pipesCodeProvider()
  964. {
  965. $variations = array(
  966. 'fwrite(STDOUT, $in = file_get_contents(\'php://stdin\')); fwrite(STDERR, $in);',
  967. 'include \''.__DIR__.'/PipeStdinInStdoutStdErrStreamSelect.php\';',
  968. );
  969. if ('\\' === DIRECTORY_SEPARATOR) {
  970. // Avoid XL buffers on Windows because of https://bugs.php.net/bug.php?id=65650
  971. $sizes = array(1, 2, 4, 8);
  972. } else {
  973. $sizes = array(1, 16, 64, 1024, 4096);
  974. }
  975. $codes = array();
  976. foreach ($sizes as $size) {
  977. foreach ($variations as $code) {
  978. $codes[] = array($code, $size);
  979. }
  980. }
  981. return $codes;
  982. }
  983. /**
  984. * @dataProvider provideVariousIncrementals
  985. */
  986. public function testIncrementalOutputDoesNotRequireAnotherCall($stream, $method)
  987. {
  988. $process = $this->getProcess(self::$phpBin.' -r '.escapeshellarg('$n = 0; while ($n < 3) { file_put_contents(\''.$stream.'\', $n, 1); $n++; usleep(1000); }'), null, null, null, null);
  989. $process->start();
  990. $result = '';
  991. $limit = microtime(true) + 3;
  992. $expected = '012';
  993. while ($result !== $expected && microtime(true) < $limit) {
  994. $result .= $process->$method();
  995. }
  996. $this->assertSame($expected, $result);
  997. $process->stop();
  998. }
  999. public function provideVariousIncrementals()
  1000. {
  1001. return array(
  1002. array('php://stdout', 'getIncrementalOutput'),
  1003. array('php://stderr', 'getIncrementalErrorOutput'),
  1004. );
  1005. }
  1006. public function testIteratorInput()
  1007. {
  1008. $input = function () {
  1009. yield 'ping';
  1010. yield 'pong';
  1011. };
  1012. $process = $this->getProcess(self::$phpBin.' -r '.escapeshellarg('stream_copy_to_stream(STDIN, STDOUT);'), null, null, $input());
  1013. $process->run();
  1014. $this->assertSame('pingpong', $process->getOutput());
  1015. }
  1016. public function testSimpleInputStream()
  1017. {
  1018. $input = new InputStream();
  1019. $process = $this->getProcess(self::$phpBin.' -r '.escapeshellarg('echo \'ping\'; stream_copy_to_stream(STDIN, STDOUT);'));
  1020. $process->setInput($input);
  1021. $process->start(function ($type, $data) use ($input) {
  1022. if ('ping' === $data) {
  1023. $input->write('pang');
  1024. } elseif (!$input->isClosed()) {
  1025. $input->write('pong');
  1026. $input->close();
  1027. }
  1028. });
  1029. $process->wait();
  1030. $this->assertSame('pingpangpong', $process->getOutput());
  1031. }
  1032. public function testInputStreamWithCallable()
  1033. {
  1034. $i = 0;
  1035. $stream = fopen('php://memory', 'w+');
  1036. $stream = function () use ($stream, &$i) {
  1037. if ($i < 3) {
  1038. rewind($stream);
  1039. fwrite($stream, ++$i);
  1040. rewind($stream);
  1041. return $stream;
  1042. }
  1043. };
  1044. $input = new InputStream();
  1045. $input->onEmpty($stream);
  1046. $input->write($stream());
  1047. $process = $this->getProcess(self::$phpBin.' -r '.escapeshellarg('echo fread(STDIN, 3);'));
  1048. $process->setInput($input);
  1049. $process->start(function ($type, $data) use ($input) {
  1050. $input->close();
  1051. });
  1052. $process->wait();
  1053. $this->assertSame('123', $process->getOutput());
  1054. }
  1055. public function testInputStreamWithGenerator()
  1056. {
  1057. $input = new InputStream();
  1058. $input->onEmpty(function ($input) {
  1059. yield 'pong';
  1060. $input->close();
  1061. });
  1062. $process = $this->getProcess(self::$phpBin.' -r '.escapeshellarg('stream_copy_to_stream(STDIN, STDOUT);'));
  1063. $process->setInput($input);
  1064. $process->start();
  1065. $input->write('ping');
  1066. $process->wait();
  1067. $this->assertSame('pingpong', $process->getOutput());
  1068. }
  1069. public function testInputStreamOnEmpty()
  1070. {
  1071. $i = 0;
  1072. $input = new InputStream();
  1073. $input->onEmpty(function () use (&$i) { ++$i; });
  1074. $process = $this->getProcess(self::$phpBin.' -r '.escapeshellarg('echo 123; echo fread(STDIN, 1); echo 456;'));
  1075. $process->setInput($input);
  1076. $process->start(function ($type, $data) use ($input) {
  1077. if ('123' === $data) {
  1078. $input->close();
  1079. }
  1080. });
  1081. $process->wait();
  1082. $this->assertSame(0, $i, 'InputStream->onEmpty callback should be called only when the input *becomes* empty');
  1083. $this->assertSame('123456', $process->getOutput());
  1084. }
  1085. public function testIteratorOutput()
  1086. {
  1087. $input = new InputStream();
  1088. $process = $this->getProcess(self::$phpBin.' -r '.escapeshellarg('fwrite(STDOUT, 123); fwrite(STDERR, 234); flush(); usleep(10000); fwrite(STDOUT, fread(STDIN, 3)); fwrite(STDERR, 456);'));
  1089. $process->setInput($input);
  1090. $process->start();
  1091. $output = array();
  1092. foreach ($process as $type => $data) {
  1093. $output[] = array($type, $data);
  1094. break;
  1095. }
  1096. $expectedOutput = array(
  1097. array($process::OUT, '123'),
  1098. );
  1099. $this->assertSame($expectedOutput, $output);
  1100. $input->write(345);
  1101. foreach ($process as $type => $data) {
  1102. $output[] = array($type, $data);
  1103. }
  1104. $this->assertSame('', $process->getOutput());
  1105. $this->assertFalse($process->isRunning());
  1106. $expectedOutput = array(
  1107. array($process::OUT, '123'),
  1108. array($process::ERR, '234'),
  1109. array($process::OUT, '345'),
  1110. array($process::ERR, '456'),
  1111. );
  1112. $this->assertSame($expectedOutput, $output);
  1113. }
  1114. public function testNonBlockingNorClearingIteratorOutput()
  1115. {
  1116. $input = new InputStream();
  1117. $process = $this->getProcess(self::$phpBin.' -r '.escapeshellarg('fwrite(STDOUT, fread(STDIN, 3));'));
  1118. $process->setInput($input);
  1119. $process->start();
  1120. $output = array();
  1121. foreach ($process->getIterator($process::ITER_NON_BLOCKING | $process::ITER_KEEP_OUTPUT) as $type => $data) {
  1122. $output[] = array($type, $data);
  1123. break;
  1124. }
  1125. $expectedOutput = array(
  1126. array($process::OUT, ''),
  1127. );
  1128. $this->assertSame($expectedOutput, $output);
  1129. $input->write(123);
  1130. foreach ($process->getIterator($process::ITER_NON_BLOCKING | $process::ITER_KEEP_OUTPUT) as $type => $data) {
  1131. if ('' !== $data) {
  1132. $output[] = array($type, $data);
  1133. }
  1134. }
  1135. $this->assertSame('123', $process->getOutput());
  1136. $this->assertFalse($process->isRunning());
  1137. $expectedOutput = array(
  1138. array($process::OUT, ''),
  1139. array($process::OUT, '123'),
  1140. );
  1141. $this->assertSame($expectedOutput, $output);
  1142. }
  1143. public function testChainedProcesses()
  1144. {
  1145. $p1 = new Process(self::$phpBin.' -r '.escapeshellarg('fwrite(STDERR, 123); fwrite(STDOUT, 456);'));
  1146. $p2 = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('stream_copy_to_stream(STDIN, STDOUT);')));
  1147. $p2->setInput($p1);
  1148. $p1->start();
  1149. $p2->run();
  1150. $this->assertSame('123', $p1->getErrorOutput());
  1151. $this->assertSame('', $p1->getOutput());
  1152. $this->assertSame('', $p2->getErrorOutput());
  1153. $this->assertSame('456', $p2->getOutput());
  1154. }
  1155. /**
  1156. * @param string $commandline
  1157. * @param null|string $cwd
  1158. * @param null|array $env
  1159. * @param null|string $input
  1160. * @param int $timeout
  1161. * @param array $options
  1162. *
  1163. * @return Process
  1164. */
  1165. private function getProcess($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60, array $options = array())
  1166. {
  1167. $process = new Process($commandline, $cwd, $env, $input, $timeout, $options);
  1168. if (false !== $enhance = getenv('ENHANCE_SIGCHLD')) {
  1169. try {
  1170. $process->setEnhanceSigchildCompatibility(false);
  1171. $process->getExitCode();
  1172. $this->fail('ENHANCE_SIGCHLD must be used together with a sigchild-enabled PHP.');
  1173. } catch (RuntimeException $e) {
  1174. $this->assertSame('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.', $e->getMessage());
  1175. if ($enhance) {
  1176. $process->setEnhanceSigchildCompatibility(true);
  1177. } else {
  1178. self::$notEnhancedSigchild = true;
  1179. }
  1180. }
  1181. }
  1182. if (self::$process) {
  1183. self::$process->stop(0);
  1184. }
  1185. return self::$process = $process;
  1186. }
  1187. private function skipIfNotEnhancedSigchild($expectException = true)
  1188. {
  1189. if (self::$sigchild) {
  1190. if (!$expectException) {
  1191. $this->markTestSkipped('PHP is compiled with --enable-sigchild.');
  1192. } elseif (self::$notEnhancedSigchild) {
  1193. $this->setExpectedException('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild.');
  1194. }
  1195. }
  1196. }
  1197. }
  1198. class NonStringifiable
  1199. {
  1200. }