ProcessTest.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289
  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 PHPUnit\Framework\TestCase;
  12. use Symfony\Component\Process\Exception\LogicException;
  13. use Symfony\Component\Process\Exception\ProcessTimedOutException;
  14. use Symfony\Component\Process\Exception\RuntimeException;
  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 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 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. /**
  244. * @dataProvider provideLegacyInputValues
  245. * @group legacy
  246. */
  247. public function testLegacyValidInput($expected, $value)
  248. {
  249. $process = $this->getProcess(self::$phpBin.' -v');
  250. $process->setInput($value);
  251. $this->assertSame($expected, $process->getInput());
  252. }
  253. public function provideLegacyInputValues()
  254. {
  255. return array(
  256. array('stringifiable', new Stringifiable()),
  257. );
  258. }
  259. public function chainedCommandsOutputProvider()
  260. {
  261. if ('\\' === \DIRECTORY_SEPARATOR) {
  262. return array(
  263. array("2 \r\n2\r\n", '&&', '2'),
  264. );
  265. }
  266. return array(
  267. array("1\n1\n", ';', '1'),
  268. array("2\n2\n", '&&', '2'),
  269. );
  270. }
  271. /**
  272. * @dataProvider chainedCommandsOutputProvider
  273. */
  274. public function testChainedCommandsOutput($expected, $operator, $input)
  275. {
  276. $process = $this->getProcess(sprintf('echo %s %s echo %s', $input, $operator, $input));
  277. $process->run();
  278. $this->assertEquals($expected, $process->getOutput());
  279. }
  280. public function testCallbackIsExecutedForOutput()
  281. {
  282. $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('echo \'foo\';')));
  283. $called = false;
  284. $p->run(function ($type, $buffer) use (&$called) {
  285. $called = 'foo' === $buffer;
  286. });
  287. $this->assertTrue($called, 'The callback should be executed with the output');
  288. }
  289. public function testGetErrorOutput()
  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. $this->assertEquals(3, preg_match_all('/ERROR/', $p->getErrorOutput(), $matches));
  294. }
  295. public function testFlushErrorOutput()
  296. {
  297. $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }')));
  298. $p->run();
  299. $p->clearErrorOutput();
  300. $this->assertEmpty($p->getErrorOutput());
  301. }
  302. /**
  303. * @dataProvider provideIncrementalOutput
  304. */
  305. public function testIncrementalOutput($getOutput, $getIncrementalOutput, $uri)
  306. {
  307. $lock = tempnam(sys_get_temp_dir(), __FUNCTION__);
  308. $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\');')));
  309. $h = fopen($lock, 'w');
  310. flock($h, LOCK_EX);
  311. $p->start();
  312. foreach (array('foo', 'bar') as $s) {
  313. while (false === strpos($p->$getOutput(), $s)) {
  314. usleep(1000);
  315. }
  316. $this->assertSame($s, $p->$getIncrementalOutput());
  317. $this->assertSame('', $p->$getIncrementalOutput());
  318. flock($h, LOCK_UN);
  319. }
  320. fclose($h);
  321. }
  322. public function provideIncrementalOutput()
  323. {
  324. return array(
  325. array('getOutput', 'getIncrementalOutput', 'php://stdout'),
  326. array('getErrorOutput', 'getIncrementalErrorOutput', 'php://stderr'),
  327. );
  328. }
  329. public function testGetOutput()
  330. {
  331. $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('$n = 0; while ($n < 3) { echo \' foo \'; $n++; }')));
  332. $p->run();
  333. $this->assertEquals(3, preg_match_all('/foo/', $p->getOutput(), $matches));
  334. }
  335. public function testFlushOutput()
  336. {
  337. $p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('$n=0;while ($n<3) {echo \' foo \';$n++;}')));
  338. $p->run();
  339. $p->clearOutput();
  340. $this->assertEmpty($p->getOutput());
  341. }
  342. public function testZeroAsOutput()
  343. {
  344. if ('\\' === \DIRECTORY_SEPARATOR) {
  345. // see http://stackoverflow.com/questions/7105433/windows-batch-echo-without-new-line
  346. $p = $this->getProcess('echo | set /p dummyName=0');
  347. } else {
  348. $p = $this->getProcess('printf 0');
  349. }
  350. $p->run();
  351. $this->assertSame('0', $p->getOutput());
  352. }
  353. public function testExitCodeCommandFailed()
  354. {
  355. if ('\\' === \DIRECTORY_SEPARATOR) {
  356. $this->markTestSkipped('Windows does not support POSIX exit code');
  357. }
  358. $this->skipIfNotEnhancedSigchild();
  359. // such command run in bash return an exitcode 127
  360. $process = $this->getProcess('nonexistingcommandIhopeneversomeonewouldnameacommandlikethis');
  361. $process->run();
  362. $this->assertGreaterThan(0, $process->getExitCode());
  363. }
  364. public function testTTYCommand()
  365. {
  366. if ('\\' === \DIRECTORY_SEPARATOR) {
  367. $this->markTestSkipped('Windows does not have /dev/tty support');
  368. }
  369. $process = $this->getProcess('echo "foo" >> /dev/null && '.self::$phpBin.' -r "usleep(100000);"');
  370. $process->setTty(true);
  371. $process->start();
  372. $this->assertTrue($process->isRunning());
  373. $process->wait();
  374. $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
  375. }
  376. public function testTTYCommandExitCode()
  377. {
  378. if ('\\' === \DIRECTORY_SEPARATOR) {
  379. $this->markTestSkipped('Windows does have /dev/tty support');
  380. }
  381. $this->skipIfNotEnhancedSigchild();
  382. $process = $this->getProcess('echo "foo" >> /dev/null');
  383. $process->setTty(true);
  384. $process->run();
  385. $this->assertTrue($process->isSuccessful());
  386. }
  387. /**
  388. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  389. * @expectedExceptionMessage TTY mode is not supported on Windows platform.
  390. */
  391. public function testTTYInWindowsEnvironment()
  392. {
  393. if ('\\' !== \DIRECTORY_SEPARATOR) {
  394. $this->markTestSkipped('This test is for Windows platform only');
  395. }
  396. $process = $this->getProcess('echo "foo" >> /dev/null');
  397. $process->setTty(false);
  398. $process->setTty(true);
  399. }
  400. public function testExitCodeTextIsNullWhenExitCodeIsNull()
  401. {
  402. $this->skipIfNotEnhancedSigchild();
  403. $process = $this->getProcess('');
  404. $this->assertNull($process->getExitCodeText());
  405. }
  406. public function testPTYCommand()
  407. {
  408. if (!Process::isPtySupported()) {
  409. $this->markTestSkipped('PTY is not supported on this operating system.');
  410. }
  411. $process = $this->getProcess('echo "foo"');
  412. $process->setPty(true);
  413. $process->run();
  414. $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
  415. $this->assertEquals("foo\r\n", $process->getOutput());
  416. }
  417. public function testMustRun()
  418. {
  419. $this->skipIfNotEnhancedSigchild();
  420. $process = $this->getProcess('echo foo');
  421. $this->assertSame($process, $process->mustRun());
  422. $this->assertEquals('foo'.PHP_EOL, $process->getOutput());
  423. }
  424. public function testSuccessfulMustRunHasCorrectExitCode()
  425. {
  426. $this->skipIfNotEnhancedSigchild();
  427. $process = $this->getProcess('echo foo')->mustRun();
  428. $this->assertEquals(0, $process->getExitCode());
  429. }
  430. /**
  431. * @expectedException \Symfony\Component\Process\Exception\ProcessFailedException
  432. */
  433. public function testMustRunThrowsException()
  434. {
  435. $this->skipIfNotEnhancedSigchild();
  436. $process = $this->getProcess('exit 1');
  437. $process->mustRun();
  438. }
  439. public function testExitCodeText()
  440. {
  441. $this->skipIfNotEnhancedSigchild();
  442. $process = $this->getProcess('');
  443. $r = new \ReflectionObject($process);
  444. $p = $r->getProperty('exitcode');
  445. $p->setAccessible(true);
  446. $p->setValue($process, 2);
  447. $this->assertEquals('Misuse of shell builtins', $process->getExitCodeText());
  448. }
  449. public function testStartIsNonBlocking()
  450. {
  451. $process = $this->getProcess(self::$phpBin.' -r "usleep(500000);"');
  452. $start = microtime(true);
  453. $process->start();
  454. $end = microtime(true);
  455. $this->assertLessThan(0.4, $end - $start);
  456. $process->stop();
  457. }
  458. public function testUpdateStatus()
  459. {
  460. $process = $this->getProcess('echo foo');
  461. $process->run();
  462. $this->assertGreaterThan(0, \strlen($process->getOutput()));
  463. }
  464. public function testGetExitCodeIsNullOnStart()
  465. {
  466. $this->skipIfNotEnhancedSigchild();
  467. $process = $this->getProcess(self::$phpBin.' -r "usleep(100000);"');
  468. $this->assertNull($process->getExitCode());
  469. $process->start();
  470. $this->assertNull($process->getExitCode());
  471. $process->wait();
  472. $this->assertEquals(0, $process->getExitCode());
  473. }
  474. public function testGetExitCodeIsNullOnWhenStartingAgain()
  475. {
  476. $this->skipIfNotEnhancedSigchild();
  477. $process = $this->getProcess(self::$phpBin.' -r "usleep(100000);"');
  478. $process->run();
  479. $this->assertEquals(0, $process->getExitCode());
  480. $process->start();
  481. $this->assertNull($process->getExitCode());
  482. $process->wait();
  483. $this->assertEquals(0, $process->getExitCode());
  484. }
  485. public function testGetExitCode()
  486. {
  487. $this->skipIfNotEnhancedSigchild();
  488. $process = $this->getProcess('echo foo');
  489. $process->run();
  490. $this->assertSame(0, $process->getExitCode());
  491. }
  492. public function testStatus()
  493. {
  494. $process = $this->getProcess(self::$phpBin.' -r "usleep(100000);"');
  495. $this->assertFalse($process->isRunning());
  496. $this->assertFalse($process->isStarted());
  497. $this->assertFalse($process->isTerminated());
  498. $this->assertSame(Process::STATUS_READY, $process->getStatus());
  499. $process->start();
  500. $this->assertTrue($process->isRunning());
  501. $this->assertTrue($process->isStarted());
  502. $this->assertFalse($process->isTerminated());
  503. $this->assertSame(Process::STATUS_STARTED, $process->getStatus());
  504. $process->wait();
  505. $this->assertFalse($process->isRunning());
  506. $this->assertTrue($process->isStarted());
  507. $this->assertTrue($process->isTerminated());
  508. $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
  509. }
  510. public function testStop()
  511. {
  512. $process = $this->getProcess(self::$phpBin.' -r "sleep(31);"');
  513. $process->start();
  514. $this->assertTrue($process->isRunning());
  515. $process->stop();
  516. $this->assertFalse($process->isRunning());
  517. }
  518. public function testIsSuccessful()
  519. {
  520. $this->skipIfNotEnhancedSigchild();
  521. $process = $this->getProcess('echo foo');
  522. $process->run();
  523. $this->assertTrue($process->isSuccessful());
  524. }
  525. public function testIsSuccessfulOnlyAfterTerminated()
  526. {
  527. $this->skipIfNotEnhancedSigchild();
  528. $process = $this->getProcess(self::$phpBin.' -r "usleep(100000);"');
  529. $process->start();
  530. $this->assertFalse($process->isSuccessful());
  531. $process->wait();
  532. $this->assertTrue($process->isSuccessful());
  533. }
  534. public function testIsNotSuccessful()
  535. {
  536. $this->skipIfNotEnhancedSigchild();
  537. $process = $this->getProcess(self::$phpBin.' -r "throw new \Exception(\'BOUM\');"');
  538. $process->run();
  539. $this->assertFalse($process->isSuccessful());
  540. }
  541. public function testProcessIsNotSignaled()
  542. {
  543. if ('\\' === \DIRECTORY_SEPARATOR) {
  544. $this->markTestSkipped('Windows does not support POSIX signals');
  545. }
  546. $this->skipIfNotEnhancedSigchild();
  547. $process = $this->getProcess('echo foo');
  548. $process->run();
  549. $this->assertFalse($process->hasBeenSignaled());
  550. }
  551. public function testProcessWithoutTermSignal()
  552. {
  553. if ('\\' === \DIRECTORY_SEPARATOR) {
  554. $this->markTestSkipped('Windows does not support POSIX signals');
  555. }
  556. $this->skipIfNotEnhancedSigchild();
  557. $process = $this->getProcess('echo foo');
  558. $process->run();
  559. $this->assertEquals(0, $process->getTermSignal());
  560. }
  561. public function testProcessIsSignaledIfStopped()
  562. {
  563. if ('\\' === \DIRECTORY_SEPARATOR) {
  564. $this->markTestSkipped('Windows does not support POSIX signals');
  565. }
  566. $this->skipIfNotEnhancedSigchild();
  567. $process = $this->getProcess(self::$phpBin.' -r "sleep(32);"');
  568. $process->start();
  569. $process->stop();
  570. $this->assertTrue($process->hasBeenSignaled());
  571. $this->assertEquals(15, $process->getTermSignal()); // SIGTERM
  572. }
  573. /**
  574. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  575. * @expectedExceptionMessage The process has been signaled
  576. */
  577. public function testProcessThrowsExceptionWhenExternallySignaled()
  578. {
  579. if (!\function_exists('posix_kill')) {
  580. $this->markTestSkipped('Function posix_kill is required.');
  581. }
  582. $this->skipIfNotEnhancedSigchild(false);
  583. $process = $this->getProcess(self::$phpBin.' -r "sleep(32.1)"');
  584. $process->start();
  585. posix_kill($process->getPid(), 9); // SIGKILL
  586. $process->wait();
  587. }
  588. public function testRestart()
  589. {
  590. $process1 = $this->getProcess(self::$phpBin.' -r "echo getmypid();"');
  591. $process1->run();
  592. $process2 = $process1->restart();
  593. $process2->wait(); // wait for output
  594. // Ensure that both processed finished and the output is numeric
  595. $this->assertFalse($process1->isRunning());
  596. $this->assertFalse($process2->isRunning());
  597. $this->assertInternalType('numeric', $process1->getOutput());
  598. $this->assertInternalType('numeric', $process2->getOutput());
  599. // Ensure that restart returned a new process by check that the output is different
  600. $this->assertNotEquals($process1->getOutput(), $process2->getOutput());
  601. }
  602. /**
  603. * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
  604. * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
  605. */
  606. public function testRunProcessWithTimeout()
  607. {
  608. $process = $this->getProcess(self::$phpBin.' -r "sleep(30);"');
  609. $process->setTimeout(0.1);
  610. $start = microtime(true);
  611. try {
  612. $process->run();
  613. $this->fail('A RuntimeException should have been raised');
  614. } catch (RuntimeException $e) {
  615. }
  616. $this->assertLessThan(15, microtime(true) - $start);
  617. throw $e;
  618. }
  619. public function testCheckTimeoutOnNonStartedProcess()
  620. {
  621. $process = $this->getProcess('echo foo');
  622. $this->assertNull($process->checkTimeout());
  623. }
  624. public function testCheckTimeoutOnTerminatedProcess()
  625. {
  626. $process = $this->getProcess('echo foo');
  627. $process->run();
  628. $this->assertNull($process->checkTimeout());
  629. }
  630. /**
  631. * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
  632. * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
  633. */
  634. public function testCheckTimeoutOnStartedProcess()
  635. {
  636. $process = $this->getProcess(self::$phpBin.' -r "sleep(33);"');
  637. $process->setTimeout(0.1);
  638. $process->start();
  639. $start = microtime(true);
  640. try {
  641. while ($process->isRunning()) {
  642. $process->checkTimeout();
  643. usleep(100000);
  644. }
  645. $this->fail('A ProcessTimedOutException should have been raised');
  646. } catch (ProcessTimedOutException $e) {
  647. }
  648. $this->assertLessThan(15, microtime(true) - $start);
  649. throw $e;
  650. }
  651. public function testIdleTimeout()
  652. {
  653. $process = $this->getProcess(self::$phpBin.' -r "sleep(34);"');
  654. $process->setTimeout(60);
  655. $process->setIdleTimeout(0.1);
  656. try {
  657. $process->run();
  658. $this->fail('A timeout exception was expected.');
  659. } catch (ProcessTimedOutException $e) {
  660. $this->assertTrue($e->isIdleTimeout());
  661. $this->assertFalse($e->isGeneralTimeout());
  662. $this->assertEquals(0.1, $e->getExceededTimeout());
  663. }
  664. }
  665. public function testIdleTimeoutNotExceededWhenOutputIsSent()
  666. {
  667. $process = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('while (true) {echo \'foo \'; usleep(1000);}')));
  668. $process->setTimeout(1);
  669. $process->start();
  670. while (false === strpos($process->getOutput(), 'foo')) {
  671. usleep(1000);
  672. }
  673. $process->setIdleTimeout(0.5);
  674. try {
  675. $process->wait();
  676. $this->fail('A timeout exception was expected.');
  677. } catch (ProcessTimedOutException $e) {
  678. $this->assertTrue($e->isGeneralTimeout(), 'A general timeout is expected.');
  679. $this->assertFalse($e->isIdleTimeout(), 'No idle timeout is expected.');
  680. $this->assertEquals(1, $e->getExceededTimeout());
  681. }
  682. }
  683. /**
  684. * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
  685. * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
  686. */
  687. public function testStartAfterATimeout()
  688. {
  689. $process = $this->getProcess(self::$phpBin.' -r "sleep(35);"');
  690. $process->setTimeout(0.1);
  691. try {
  692. $process->run();
  693. $this->fail('A ProcessTimedOutException should have been raised.');
  694. } catch (ProcessTimedOutException $e) {
  695. }
  696. $this->assertFalse($process->isRunning());
  697. $process->start();
  698. $this->assertTrue($process->isRunning());
  699. $process->stop(0);
  700. throw $e;
  701. }
  702. public function testGetPid()
  703. {
  704. $process = $this->getProcess(self::$phpBin.' -r "sleep(36);"');
  705. $process->start();
  706. $this->assertGreaterThan(0, $process->getPid());
  707. $process->stop(0);
  708. }
  709. public function testGetPidIsNullBeforeStart()
  710. {
  711. $process = $this->getProcess('foo');
  712. $this->assertNull($process->getPid());
  713. }
  714. public function testGetPidIsNullAfterRun()
  715. {
  716. $process = $this->getProcess('echo foo');
  717. $process->run();
  718. $this->assertNull($process->getPid());
  719. }
  720. /**
  721. * @requires extension pcntl
  722. */
  723. public function testSignal()
  724. {
  725. $process = $this->getProcess(self::$phpBin.' '.__DIR__.'/SignalListener.php');
  726. $process->start();
  727. while (false === strpos($process->getOutput(), 'Caught')) {
  728. usleep(1000);
  729. }
  730. $process->signal(SIGUSR1);
  731. $process->wait();
  732. $this->assertEquals('Caught SIGUSR1', $process->getOutput());
  733. }
  734. /**
  735. * @requires extension pcntl
  736. */
  737. public function testExitCodeIsAvailableAfterSignal()
  738. {
  739. $this->skipIfNotEnhancedSigchild();
  740. $process = $this->getProcess('sleep 4');
  741. $process->start();
  742. $process->signal(SIGKILL);
  743. while ($process->isRunning()) {
  744. usleep(10000);
  745. }
  746. $this->assertFalse($process->isRunning());
  747. $this->assertTrue($process->hasBeenSignaled());
  748. $this->assertFalse($process->isSuccessful());
  749. $this->assertEquals(137, $process->getExitCode());
  750. }
  751. /**
  752. * @expectedException \Symfony\Component\Process\Exception\LogicException
  753. * @expectedExceptionMessage Can not send signal on a non running process.
  754. */
  755. public function testSignalProcessNotRunning()
  756. {
  757. $process = $this->getProcess('foo');
  758. $process->signal(1); // SIGHUP
  759. }
  760. /**
  761. * @dataProvider provideMethodsThatNeedARunningProcess
  762. */
  763. public function testMethodsThatNeedARunningProcess($method)
  764. {
  765. $process = $this->getProcess('foo');
  766. if (method_exists($this, 'expectException')) {
  767. $this->expectException('Symfony\Component\Process\Exception\LogicException');
  768. $this->expectExceptionMessage(sprintf('Process must be started before calling %s.', $method));
  769. } else {
  770. $this->setExpectedException('Symfony\Component\Process\Exception\LogicException', sprintf('Process must be started before calling %s.', $method));
  771. }
  772. $process->{$method}();
  773. }
  774. public function provideMethodsThatNeedARunningProcess()
  775. {
  776. return array(
  777. array('getOutput'),
  778. array('getIncrementalOutput'),
  779. array('getErrorOutput'),
  780. array('getIncrementalErrorOutput'),
  781. array('wait'),
  782. );
  783. }
  784. /**
  785. * @dataProvider provideMethodsThatNeedATerminatedProcess
  786. * @expectedException \Symfony\Component\Process\Exception\LogicException
  787. * @expectedExceptionMessage Process must be terminated before calling
  788. */
  789. public function testMethodsThatNeedATerminatedProcess($method)
  790. {
  791. $process = $this->getProcess(self::$phpBin.' -r "sleep(37);"');
  792. $process->start();
  793. try {
  794. $process->{$method}();
  795. $process->stop(0);
  796. $this->fail('A LogicException must have been thrown');
  797. } catch (\Exception $e) {
  798. }
  799. $process->stop(0);
  800. throw $e;
  801. }
  802. public function provideMethodsThatNeedATerminatedProcess()
  803. {
  804. return array(
  805. array('hasBeenSignaled'),
  806. array('getTermSignal'),
  807. array('hasBeenStopped'),
  808. array('getStopSignal'),
  809. );
  810. }
  811. /**
  812. * @dataProvider provideWrongSignal
  813. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  814. */
  815. public function testWrongSignal($signal)
  816. {
  817. if ('\\' === \DIRECTORY_SEPARATOR) {
  818. $this->markTestSkipped('POSIX signals do not work on Windows');
  819. }
  820. $process = $this->getProcess(self::$phpBin.' -r "sleep(38);"');
  821. $process->start();
  822. try {
  823. $process->signal($signal);
  824. $this->fail('A RuntimeException must have been thrown');
  825. } catch (RuntimeException $e) {
  826. $process->stop(0);
  827. }
  828. throw $e;
  829. }
  830. public function provideWrongSignal()
  831. {
  832. return array(
  833. array(-4),
  834. array('Céphalopodes'),
  835. );
  836. }
  837. public function testDisableOutputDisablesTheOutput()
  838. {
  839. $p = $this->getProcess('foo');
  840. $this->assertFalse($p->isOutputDisabled());
  841. $p->disableOutput();
  842. $this->assertTrue($p->isOutputDisabled());
  843. $p->enableOutput();
  844. $this->assertFalse($p->isOutputDisabled());
  845. }
  846. /**
  847. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  848. * @expectedExceptionMessage Disabling output while the process is running is not possible.
  849. */
  850. public function testDisableOutputWhileRunningThrowsException()
  851. {
  852. $p = $this->getProcess(self::$phpBin.' -r "sleep(39);"');
  853. $p->start();
  854. $p->disableOutput();
  855. }
  856. /**
  857. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  858. * @expectedExceptionMessage Enabling output while the process is running is not possible.
  859. */
  860. public function testEnableOutputWhileRunningThrowsException()
  861. {
  862. $p = $this->getProcess(self::$phpBin.' -r "sleep(40);"');
  863. $p->disableOutput();
  864. $p->start();
  865. $p->enableOutput();
  866. }
  867. public function testEnableOrDisableOutputAfterRunDoesNotThrowException()
  868. {
  869. $p = $this->getProcess('echo foo');
  870. $p->disableOutput();
  871. $p->run();
  872. $p->enableOutput();
  873. $p->disableOutput();
  874. $this->assertTrue($p->isOutputDisabled());
  875. }
  876. /**
  877. * @expectedException \Symfony\Component\Process\Exception\LogicException
  878. * @expectedExceptionMessage Output can not be disabled while an idle timeout is set.
  879. */
  880. public function testDisableOutputWhileIdleTimeoutIsSet()
  881. {
  882. $process = $this->getProcess('foo');
  883. $process->setIdleTimeout(1);
  884. $process->disableOutput();
  885. }
  886. /**
  887. * @expectedException \Symfony\Component\Process\Exception\LogicException
  888. * @expectedExceptionMessage timeout can not be set while the output is disabled.
  889. */
  890. public function testSetIdleTimeoutWhileOutputIsDisabled()
  891. {
  892. $process = $this->getProcess('foo');
  893. $process->disableOutput();
  894. $process->setIdleTimeout(1);
  895. }
  896. public function testSetNullIdleTimeoutWhileOutputIsDisabled()
  897. {
  898. $process = $this->getProcess('foo');
  899. $process->disableOutput();
  900. $this->assertSame($process, $process->setIdleTimeout(null));
  901. }
  902. /**
  903. * @dataProvider provideStartMethods
  904. */
  905. public function testStartWithACallbackAndDisabledOutput($startMethod, $exception, $exceptionMessage)
  906. {
  907. $p = $this->getProcess('foo');
  908. $p->disableOutput();
  909. if (method_exists($this, 'expectException')) {
  910. $this->expectException($exception);
  911. $this->expectExceptionMessage($exceptionMessage);
  912. } else {
  913. $this->setExpectedException($exception, $exceptionMessage);
  914. }
  915. if ('mustRun' === $startMethod) {
  916. $this->skipIfNotEnhancedSigchild();
  917. }
  918. $p->{$startMethod}(function () {});
  919. }
  920. public function provideStartMethods()
  921. {
  922. return array(
  923. array('start', 'Symfony\Component\Process\Exception\LogicException', 'Output has been disabled, enable it to allow the use of a callback.'),
  924. array('run', 'Symfony\Component\Process\Exception\LogicException', 'Output has been disabled, enable it to allow the use of a callback.'),
  925. array('mustRun', 'Symfony\Component\Process\Exception\LogicException', 'Output has been disabled, enable it to allow the use of a callback.'),
  926. );
  927. }
  928. /**
  929. * @dataProvider provideOutputFetchingMethods
  930. * @expectedException \Symfony\Component\Process\Exception\LogicException
  931. * @expectedExceptionMessage Output has been disabled.
  932. */
  933. public function testGetOutputWhileDisabled($fetchMethod)
  934. {
  935. $p = $this->getProcess(self::$phpBin.' -r "sleep(41);"');
  936. $p->disableOutput();
  937. $p->start();
  938. $p->{$fetchMethod}();
  939. }
  940. public function provideOutputFetchingMethods()
  941. {
  942. return array(
  943. array('getOutput'),
  944. array('getIncrementalOutput'),
  945. array('getErrorOutput'),
  946. array('getIncrementalErrorOutput'),
  947. );
  948. }
  949. public function testStopTerminatesProcessCleanly()
  950. {
  951. $process = $this->getProcess(self::$phpBin.' -r "echo 123; sleep(42);"');
  952. $process->run(function () use ($process) {
  953. $process->stop();
  954. });
  955. $this->assertTrue(true, 'A call to stop() is not expected to cause wait() to throw a RuntimeException');
  956. }
  957. public function testKillSignalTerminatesProcessCleanly()
  958. {
  959. $process = $this->getProcess(self::$phpBin.' -r "echo 123; sleep(43);"');
  960. $process->run(function () use ($process) {
  961. $process->signal(9); // SIGKILL
  962. });
  963. $this->assertTrue(true, 'A call to signal() is not expected to cause wait() to throw a RuntimeException');
  964. }
  965. public function testTermSignalTerminatesProcessCleanly()
  966. {
  967. $process = $this->getProcess(self::$phpBin.' -r "echo 123; sleep(44);"');
  968. $process->run(function () use ($process) {
  969. $process->signal(15); // SIGTERM
  970. });
  971. $this->assertTrue(true, 'A call to signal() is not expected to cause wait() to throw a RuntimeException');
  972. }
  973. public function responsesCodeProvider()
  974. {
  975. return array(
  976. //expected output / getter / code to execute
  977. //array(1,'getExitCode','exit(1);'),
  978. //array(true,'isSuccessful','exit();'),
  979. array('output', 'getOutput', 'echo \'output\';'),
  980. );
  981. }
  982. public function pipesCodeProvider()
  983. {
  984. $variations = array(
  985. 'fwrite(STDOUT, $in = file_get_contents(\'php://stdin\')); fwrite(STDERR, $in);',
  986. 'include \''.__DIR__.'/PipeStdinInStdoutStdErrStreamSelect.php\';',
  987. );
  988. if ('\\' === \DIRECTORY_SEPARATOR) {
  989. // Avoid XL buffers on Windows because of https://bugs.php.net/bug.php?id=65650
  990. $sizes = array(1, 2, 4, 8);
  991. } else {
  992. $sizes = array(1, 16, 64, 1024, 4096);
  993. }
  994. $codes = array();
  995. foreach ($sizes as $size) {
  996. foreach ($variations as $code) {
  997. $codes[] = array($code, $size);
  998. }
  999. }
  1000. return $codes;
  1001. }
  1002. /**
  1003. * @dataProvider provideVariousIncrementals
  1004. */
  1005. public function testIncrementalOutputDoesNotRequireAnotherCall($stream, $method)
  1006. {
  1007. $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);
  1008. $process->start();
  1009. $result = '';
  1010. $limit = microtime(true) + 3;
  1011. $expected = '012';
  1012. while ($result !== $expected && microtime(true) < $limit) {
  1013. $result .= $process->$method();
  1014. }
  1015. $this->assertSame($expected, $result);
  1016. $process->stop();
  1017. }
  1018. public function provideVariousIncrementals()
  1019. {
  1020. return array(
  1021. array('php://stdout', 'getIncrementalOutput'),
  1022. array('php://stderr', 'getIncrementalErrorOutput'),
  1023. );
  1024. }
  1025. /**
  1026. * @param string $commandline
  1027. * @param string|null $cwd
  1028. * @param array|null $env
  1029. * @param string|null $input
  1030. * @param int $timeout
  1031. * @param array $options
  1032. *
  1033. * @return Process
  1034. */
  1035. private function getProcess($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60, array $options = array())
  1036. {
  1037. $process = new Process($commandline, $cwd, $env, $input, $timeout, $options);
  1038. if (false !== $enhance = getenv('ENHANCE_SIGCHLD')) {
  1039. try {
  1040. $process->setEnhanceSigchildCompatibility(false);
  1041. $process->getExitCode();
  1042. $this->fail('ENHANCE_SIGCHLD must be used together with a sigchild-enabled PHP.');
  1043. } catch (RuntimeException $e) {
  1044. $this->assertSame('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.', $e->getMessage());
  1045. if ($enhance) {
  1046. $process->setEnhanceSigchildCompatibility(true);
  1047. } else {
  1048. self::$notEnhancedSigchild = true;
  1049. }
  1050. }
  1051. }
  1052. if (self::$process) {
  1053. self::$process->stop(0);
  1054. }
  1055. return self::$process = $process;
  1056. }
  1057. private function skipIfNotEnhancedSigchild($expectException = true)
  1058. {
  1059. if (self::$sigchild) {
  1060. if (!$expectException) {
  1061. $this->markTestSkipped('PHP is compiled with --enable-sigchild.');
  1062. } elseif (self::$notEnhancedSigchild) {
  1063. if (method_exists($this, 'expectException')) {
  1064. $this->expectException('Symfony\Component\Process\Exception\RuntimeException');
  1065. $this->expectExceptionMessage('This PHP has been compiled with --enable-sigchild.');
  1066. } else {
  1067. $this->setExpectedException('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild.');
  1068. }
  1069. }
  1070. }
  1071. }
  1072. }
  1073. class Stringifiable
  1074. {
  1075. public function __toString()
  1076. {
  1077. return 'stringifiable';
  1078. }
  1079. }
  1080. class NonStringifiable
  1081. {
  1082. }