ProcessTest.php 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  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 null|string $cwd
  1028. * @param null|array $env
  1029. * @param null|string $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. }