AbstractProcessTest.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  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\ProcessTimedOutException;
  12. use Symfony\Component\Process\Exception\LogicException;
  13. use Symfony\Component\Process\Process;
  14. use Symfony\Component\Process\Exception\RuntimeException;
  15. use Symfony\Component\Process\ProcessPipes;
  16. /**
  17. * @author Robert Schönthal <seroscho@googlemail.com>
  18. */
  19. abstract class AbstractProcessTest extends \PHPUnit_Framework_TestCase
  20. {
  21. public function testThatProcessDoesNotThrowWarningDuringRun()
  22. {
  23. @trigger_error('Test Error', E_USER_NOTICE);
  24. $process = $this->getProcess("php -r 'sleep(3)'");
  25. $process->run();
  26. $actualError = error_get_last();
  27. $this->assertEquals('Test Error', $actualError['message']);
  28. $this->assertEquals(E_USER_NOTICE, $actualError['type']);
  29. }
  30. /**
  31. * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
  32. */
  33. public function testNegativeTimeoutFromConstructor()
  34. {
  35. $this->getProcess('', null, null, null, -1);
  36. }
  37. /**
  38. * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
  39. */
  40. public function testNegativeTimeoutFromSetter()
  41. {
  42. $p = $this->getProcess('');
  43. $p->setTimeout(-1);
  44. }
  45. public function testFloatAndNullTimeout()
  46. {
  47. $p = $this->getProcess('');
  48. $p->setTimeout(10);
  49. $this->assertSame(10.0, $p->getTimeout());
  50. $p->setTimeout(null);
  51. $this->assertNull($p->getTimeout());
  52. $p->setTimeout(0.0);
  53. $this->assertNull($p->getTimeout());
  54. }
  55. public function testStopWithTimeoutIsActuallyWorking()
  56. {
  57. $this->verifyPosixIsEnabled();
  58. // exec is mandatory here since we send a signal to the process
  59. // see https://github.com/symfony/symfony/issues/5030 about prepending
  60. // command with exec
  61. $p = $this->getProcess('exec php '.__DIR__.'/NonStopableProcess.php 3');
  62. $p->start();
  63. usleep(100000);
  64. $start = microtime(true);
  65. $p->stop(1.1, SIGKILL);
  66. while ($p->isRunning()) {
  67. usleep(1000);
  68. }
  69. $this->assertLessThan(4, microtime(true) - $start);
  70. }
  71. public function testAllOutputIsActuallyReadOnTermination()
  72. {
  73. // this code will result in a maximum of 2 reads of 8192 bytes by calling
  74. // start() and isRunning(). by the time getOutput() is called the process
  75. // has terminated so the internal pipes array is already empty. normally
  76. // the call to start() will not read any data as the process will not have
  77. // generated output, but this is non-deterministic so we must count it as
  78. // a possibility. therefore we need 2 * ProcessPipes::CHUNK_SIZE plus
  79. // another byte which will never be read.
  80. $expectedOutputSize = ProcessPipes::CHUNK_SIZE * 2 + 2;
  81. $code = sprintf('echo str_repeat(\'*\', %d);', $expectedOutputSize);
  82. $p = $this->getProcess(sprintf('php -r %s', escapeshellarg($code)));
  83. $p->start();
  84. // Let's wait enough time for process to finish...
  85. // Here we don't call Process::run or Process::wait to avoid any read of pipes
  86. usleep(500000);
  87. if ($p->isRunning()) {
  88. $this->markTestSkipped('Process execution did not complete in the required time frame');
  89. }
  90. $o = $p->getOutput();
  91. $this->assertEquals($expectedOutputSize, strlen($o));
  92. }
  93. public function testCallbacksAreExecutedWithStart()
  94. {
  95. $data = '';
  96. $process = $this->getProcess('echo foo && php -r "sleep(1);" && echo foo');
  97. $process->start(function ($type, $buffer) use (&$data) {
  98. $data .= $buffer;
  99. });
  100. while ($process->isRunning()) {
  101. usleep(10000);
  102. }
  103. $this->assertEquals(2, preg_match_all('/foo/', $data, $matches));
  104. }
  105. /**
  106. * tests results from sub processes
  107. *
  108. * @dataProvider responsesCodeProvider
  109. */
  110. public function testProcessResponses($expected, $getter, $code)
  111. {
  112. $p = $this->getProcess(sprintf('php -r %s', escapeshellarg($code)));
  113. $p->run();
  114. $this->assertSame($expected, $p->$getter());
  115. }
  116. /**
  117. * tests results from sub processes
  118. *
  119. * @dataProvider pipesCodeProvider
  120. */
  121. public function testProcessPipes($code, $size)
  122. {
  123. $expected = str_repeat(str_repeat('*', 1024), $size).'!';
  124. $expectedLength = (1024 * $size) + 1;
  125. $p = $this->getProcess(sprintf('php -r %s', escapeshellarg($code)));
  126. $p->setStdin($expected);
  127. $p->run();
  128. $this->assertEquals($expectedLength, strlen($p->getOutput()));
  129. $this->assertEquals($expectedLength, strlen($p->getErrorOutput()));
  130. }
  131. public function testSetStdinWhileRunningThrowsAnException()
  132. {
  133. $process = $this->getProcess('php -r "usleep(500000);"');
  134. $process->start();
  135. try {
  136. $process->setStdin('foobar');
  137. $process->stop();
  138. $this->fail('A LogicException should have been raised.');
  139. } catch (LogicException $e) {
  140. $this->assertEquals('STDIN can not be set while the process is running.', $e->getMessage());
  141. }
  142. $process->stop();
  143. }
  144. /**
  145. * @dataProvider provideInvalidStdinValues
  146. * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
  147. * @expectedExceptionMessage Symfony\Component\Process\Process::setStdin only accepts strings.
  148. */
  149. public function testInvalidStdin($value)
  150. {
  151. $process = $this->getProcess('php -v');
  152. $process->setStdin($value);
  153. }
  154. public function provideInvalidStdinValues()
  155. {
  156. return array(
  157. array(array()),
  158. array(new NonStringifiable()),
  159. array(fopen('php://temporary', 'w')),
  160. );
  161. }
  162. /**
  163. * @dataProvider provideStdinValues
  164. */
  165. public function testValidStdin($expected, $value)
  166. {
  167. $process = $this->getProcess('php -v');
  168. $process->setStdin($value);
  169. $this->assertSame($expected, $process->getStdin());
  170. }
  171. public function provideStdinValues()
  172. {
  173. return array(
  174. array(null, null),
  175. array('24.5', 24.5),
  176. array('input data', 'input data'),
  177. // to maintain BC, supposed to be removed in 3.0
  178. array('stringifiable', new Stringifiable()),
  179. );
  180. }
  181. public function chainedCommandsOutputProvider()
  182. {
  183. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  184. return array(
  185. array("2 \r\n2\r\n", '&&', '2'),
  186. );
  187. }
  188. return array(
  189. array("1\n1\n", ';', '1'),
  190. array("2\n2\n", '&&', '2'),
  191. );
  192. }
  193. /**
  194. *
  195. * @dataProvider chainedCommandsOutputProvider
  196. */
  197. public function testChainedCommandsOutput($expected, $operator, $input)
  198. {
  199. $process = $this->getProcess(sprintf('echo %s %s echo %s', $input, $operator, $input));
  200. $process->run();
  201. $this->assertEquals($expected, $process->getOutput());
  202. }
  203. public function testCallbackIsExecutedForOutput()
  204. {
  205. $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('echo \'foo\';')));
  206. $called = false;
  207. $p->run(function ($type, $buffer) use (&$called) {
  208. $called = $buffer === 'foo';
  209. });
  210. $this->assertTrue($called, 'The callback should be executed with the output');
  211. }
  212. public function testGetErrorOutput()
  213. {
  214. $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }')));
  215. $p->run();
  216. $this->assertEquals(3, preg_match_all('/ERROR/', $p->getErrorOutput(), $matches));
  217. }
  218. public function testGetIncrementalErrorOutput()
  219. {
  220. // use a lock file to toggle between writing ("W") and reading ("R") the
  221. // error stream
  222. $lock = tempnam(sys_get_temp_dir(), get_class($this).'Lock');
  223. file_put_contents($lock, 'W');
  224. $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('$n = 0; while ($n < 3) { if (\'W\' === file_get_contents('.var_export($lock, true).')) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; file_put_contents('.var_export($lock, true).', \'R\'); } usleep(100); }')));
  225. $p->start();
  226. while ($p->isRunning()) {
  227. if ('R' === file_get_contents($lock)) {
  228. $this->assertLessThanOrEqual(1, preg_match_all('/ERROR/', $p->getIncrementalErrorOutput(), $matches));
  229. file_put_contents($lock, 'W');
  230. }
  231. usleep(100);
  232. }
  233. unlink($lock);
  234. }
  235. public function testFlushErrorOutput()
  236. {
  237. $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }')));
  238. $p->run();
  239. $p->clearErrorOutput();
  240. $this->assertEmpty($p->getErrorOutput());
  241. }
  242. public function testGetOutput()
  243. {
  244. $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('$n = 0; while ($n < 3) { echo \' foo \'; $n++; }')));
  245. $p->run();
  246. $this->assertEquals(3, preg_match_all('/foo/', $p->getOutput(), $matches));
  247. }
  248. public function testGetIncrementalOutput()
  249. {
  250. // use a lock file to toggle between writing ("W") and reading ("R") the
  251. // output stream
  252. $lock = tempnam(sys_get_temp_dir(), get_class($this).'Lock');
  253. file_put_contents($lock, 'W');
  254. $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('$n = 0; while ($n < 3) { if (\'W\' === file_get_contents('.var_export($lock, true).')) { echo \' foo \'; $n++; file_put_contents('.var_export($lock, true).', \'R\'); } usleep(100); }')));
  255. $p->start();
  256. while ($p->isRunning()) {
  257. if ('R' === file_get_contents($lock)) {
  258. $this->assertLessThanOrEqual(1, preg_match_all('/foo/', $p->getIncrementalOutput(), $matches));
  259. file_put_contents($lock, 'W');
  260. }
  261. usleep(100);
  262. }
  263. unlink($lock);
  264. }
  265. public function testFlushOutput()
  266. {
  267. $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('$n=0;while ($n<3) {echo \' foo \';$n++;}')));
  268. $p->run();
  269. $p->clearOutput();
  270. $this->assertEmpty($p->getOutput());
  271. }
  272. public function testZeroAsOutput()
  273. {
  274. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  275. // see http://stackoverflow.com/questions/7105433/windows-batch-echo-without-new-line
  276. $p = $this->getProcess('echo | set /p dummyName=0');
  277. } else {
  278. $p = $this->getProcess('printf 0');
  279. }
  280. $p->run();
  281. $this->assertSame('0', $p->getOutput());
  282. }
  283. public function testExitCodeCommandFailed()
  284. {
  285. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  286. $this->markTestSkipped('Windows does not support POSIX exit code');
  287. }
  288. // such command run in bash return an exitcode 127
  289. $process = $this->getProcess('nonexistingcommandIhopeneversomeonewouldnameacommandlikethis');
  290. $process->run();
  291. $this->assertGreaterThan(0, $process->getExitCode());
  292. }
  293. public function testTTYCommand()
  294. {
  295. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  296. $this->markTestSkipped('Windows does have /dev/tty support');
  297. }
  298. $process = $this->getProcess('echo "foo" >> /dev/null && php -r "usleep(100000);"');
  299. $process->setTty(true);
  300. $process->start();
  301. $this->assertTrue($process->isRunning());
  302. $process->wait();
  303. $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
  304. }
  305. public function testTTYCommandExitCode()
  306. {
  307. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  308. $this->markTestSkipped('Windows does have /dev/tty support');
  309. }
  310. $process = $this->getProcess('echo "foo" >> /dev/null');
  311. $process->setTty(true);
  312. $process->run();
  313. $this->assertTrue($process->isSuccessful());
  314. }
  315. public function testTTYInWindowsEnvironment()
  316. {
  317. if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
  318. $this->markTestSkipped('This test is for Windows platform only');
  319. }
  320. $process = $this->getProcess('echo "foo" >> /dev/null');
  321. $process->setTty(false);
  322. $this->setExpectedException('Symfony\Component\Process\Exception\RuntimeException', 'TTY mode is not supported on Windows platform.');
  323. $process->setTty(true);
  324. }
  325. public function testExitCodeTextIsNullWhenExitCodeIsNull()
  326. {
  327. $process = $this->getProcess('');
  328. $this->assertNull($process->getExitCodeText());
  329. }
  330. public function testExitCodeText()
  331. {
  332. $process = $this->getProcess('');
  333. $r = new \ReflectionObject($process);
  334. $p = $r->getProperty('exitcode');
  335. $p->setAccessible(true);
  336. $p->setValue($process, 2);
  337. $this->assertEquals('Misuse of shell builtins', $process->getExitCodeText());
  338. }
  339. public function testStartIsNonBlocking()
  340. {
  341. $process = $this->getProcess('php -r "usleep(500000);"');
  342. $start = microtime(true);
  343. $process->start();
  344. $end = microtime(true);
  345. $this->assertLessThan(1, $end - $start);
  346. $process->wait();
  347. }
  348. public function testUpdateStatus()
  349. {
  350. $process = $this->getProcess('php -h');
  351. $process->run();
  352. $this->assertTrue(strlen($process->getOutput()) > 0);
  353. }
  354. public function testGetExitCodeIsNullOnStart()
  355. {
  356. $process = $this->getProcess('php -r "usleep(200000);"');
  357. $this->assertNull($process->getExitCode());
  358. $process->start();
  359. $this->assertNull($process->getExitCode());
  360. $process->wait();
  361. $this->assertEquals(0, $process->getExitCode());
  362. }
  363. public function testGetExitCodeIsNullOnWhenStartingAgain()
  364. {
  365. $process = $this->getProcess('php -r "usleep(200000);"');
  366. $process->run();
  367. $this->assertEquals(0, $process->getExitCode());
  368. $process->start();
  369. $this->assertNull($process->getExitCode());
  370. $process->wait();
  371. $this->assertEquals(0, $process->getExitCode());
  372. }
  373. public function testGetExitCode()
  374. {
  375. $process = $this->getProcess('php -m');
  376. $process->run();
  377. $this->assertSame(0, $process->getExitCode());
  378. }
  379. public function testStatus()
  380. {
  381. $process = $this->getProcess('php -r "usleep(500000);"');
  382. $this->assertFalse($process->isRunning());
  383. $this->assertFalse($process->isStarted());
  384. $this->assertFalse($process->isTerminated());
  385. $this->assertSame(Process::STATUS_READY, $process->getStatus());
  386. $process->start();
  387. $this->assertTrue($process->isRunning());
  388. $this->assertTrue($process->isStarted());
  389. $this->assertFalse($process->isTerminated());
  390. $this->assertSame(Process::STATUS_STARTED, $process->getStatus());
  391. $process->wait();
  392. $this->assertFalse($process->isRunning());
  393. $this->assertTrue($process->isStarted());
  394. $this->assertTrue($process->isTerminated());
  395. $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
  396. }
  397. public function testStop()
  398. {
  399. $process = $this->getProcess('php -r "sleep(4);"');
  400. $process->start();
  401. $this->assertTrue($process->isRunning());
  402. $process->stop();
  403. $this->assertFalse($process->isRunning());
  404. }
  405. public function testIsSuccessful()
  406. {
  407. $process = $this->getProcess('php -m');
  408. $process->run();
  409. $this->assertTrue($process->isSuccessful());
  410. }
  411. public function testIsSuccessfulOnlyAfterTerminated()
  412. {
  413. $process = $this->getProcess('php -r "sleep(1);"');
  414. $process->start();
  415. while ($process->isRunning()) {
  416. $this->assertFalse($process->isSuccessful());
  417. usleep(300000);
  418. }
  419. $this->assertTrue($process->isSuccessful());
  420. }
  421. public function testIsNotSuccessful()
  422. {
  423. $process = $this->getProcess('php -r "usleep(500000);throw new \Exception(\'BOUM\');"');
  424. $process->start();
  425. $this->assertTrue($process->isRunning());
  426. $process->wait();
  427. $this->assertFalse($process->isSuccessful());
  428. }
  429. public function testProcessIsNotSignaled()
  430. {
  431. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  432. $this->markTestSkipped('Windows does not support POSIX signals');
  433. }
  434. $process = $this->getProcess('php -m');
  435. $process->run();
  436. $this->assertFalse($process->hasBeenSignaled());
  437. }
  438. public function testProcessWithoutTermSignalIsNotSignaled()
  439. {
  440. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  441. $this->markTestSkipped('Windows does not support POSIX signals');
  442. }
  443. $process = $this->getProcess('php -m');
  444. $process->run();
  445. $this->assertFalse($process->hasBeenSignaled());
  446. }
  447. public function testProcessWithoutTermSignal()
  448. {
  449. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  450. $this->markTestSkipped('Windows does not support POSIX signals');
  451. }
  452. $process = $this->getProcess('php -m');
  453. $process->run();
  454. $this->assertEquals(0, $process->getTermSignal());
  455. }
  456. public function testProcessIsSignaledIfStopped()
  457. {
  458. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  459. $this->markTestSkipped('Windows does not support POSIX signals');
  460. }
  461. $process = $this->getProcess('php -r "sleep(4);"');
  462. $process->start();
  463. $process->stop();
  464. $this->assertTrue($process->hasBeenSignaled());
  465. }
  466. public function testProcessWithTermSignal()
  467. {
  468. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  469. $this->markTestSkipped('Windows does not support POSIX signals');
  470. }
  471. // SIGTERM is only defined if pcntl extension is present
  472. $termSignal = defined('SIGTERM') ? SIGTERM : 15;
  473. $process = $this->getProcess('php -r "sleep(4);"');
  474. $process->start();
  475. $process->stop();
  476. $this->assertEquals($termSignal, $process->getTermSignal());
  477. }
  478. public function testProcessThrowsExceptionWhenExternallySignaled()
  479. {
  480. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  481. $this->markTestSkipped('Windows does not support POSIX signals');
  482. }
  483. if (!function_exists('posix_kill')) {
  484. $this->markTestSkipped('posix_kill is required for this test');
  485. }
  486. $termSignal = defined('SIGKILL') ? SIGKILL : 9;
  487. $process = $this->getProcess('exec php -r "while (true) {}"');
  488. $process->start();
  489. posix_kill($process->getPid(), $termSignal);
  490. $this->setExpectedException('Symfony\Component\Process\Exception\RuntimeException', 'The process has been signaled with signal "9".');
  491. $process->wait();
  492. }
  493. public function testRestart()
  494. {
  495. $process1 = $this->getProcess('php -r "echo getmypid();"');
  496. $process1->run();
  497. $process2 = $process1->restart();
  498. $process2->wait(); // wait for output
  499. // Ensure that both processed finished and the output is numeric
  500. $this->assertFalse($process1->isRunning());
  501. $this->assertFalse($process2->isRunning());
  502. $this->assertTrue(is_numeric($process1->getOutput()));
  503. $this->assertTrue(is_numeric($process2->getOutput()));
  504. // Ensure that restart returned a new process by check that the output is different
  505. $this->assertNotEquals($process1->getOutput(), $process2->getOutput());
  506. }
  507. public function testPhpDeadlock()
  508. {
  509. $this->markTestSkipped('Can cause PHP to hang');
  510. // Sleep doesn't work as it will allow the process to handle signals and close
  511. // file handles from the other end.
  512. $process = $this->getProcess('php -r "while (true) {}"');
  513. $process->start();
  514. // PHP will deadlock when it tries to cleanup $process
  515. }
  516. public function testRunProcessWithTimeout()
  517. {
  518. $timeout = 0.5;
  519. $process = $this->getProcess('php -r "usleep(600000);"');
  520. $process->setTimeout($timeout);
  521. $start = microtime(true);
  522. try {
  523. $process->run();
  524. $this->fail('A RuntimeException should have been raised');
  525. } catch (RuntimeException $e) {
  526. }
  527. $duration = microtime(true) - $start;
  528. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  529. // Windows is a bit slower as it read file handles, then allow twice the precision
  530. $maxDuration = $timeout + 2 * Process::TIMEOUT_PRECISION;
  531. } else {
  532. $maxDuration = $timeout + Process::TIMEOUT_PRECISION;
  533. }
  534. $this->assertLessThan($maxDuration, $duration);
  535. }
  536. public function testCheckTimeoutOnNonStartedProcess()
  537. {
  538. $process = $this->getProcess('php -r "sleep(3);"');
  539. $process->checkTimeout();
  540. }
  541. public function testCheckTimeoutOnTerminatedProcess()
  542. {
  543. $process = $this->getProcess('php -v');
  544. $process->run();
  545. $process->checkTimeout();
  546. }
  547. public function testCheckTimeoutOnStartedProcess()
  548. {
  549. $timeout = 0.5;
  550. $precision = 100000;
  551. $process = $this->getProcess('php -r "sleep(3);"');
  552. $process->setTimeout($timeout);
  553. $start = microtime(true);
  554. $process->start();
  555. try {
  556. while ($process->isRunning()) {
  557. $process->checkTimeout();
  558. usleep($precision);
  559. }
  560. $this->fail('A RuntimeException should have been raised');
  561. } catch (RuntimeException $e) {
  562. }
  563. $duration = microtime(true) - $start;
  564. $this->assertLessThan($timeout + $precision, $duration);
  565. $this->assertFalse($process->isSuccessful());
  566. }
  567. /**
  568. * @group idle-timeout
  569. */
  570. public function testIdleTimeout()
  571. {
  572. $process = $this->getProcess('sleep 3');
  573. $process->setTimeout(10);
  574. $process->setIdleTimeout(1);
  575. try {
  576. $process->run();
  577. $this->fail('A timeout exception was expected.');
  578. } catch (ProcessTimedOutException $ex) {
  579. $this->assertTrue($ex->isIdleTimeout());
  580. $this->assertFalse($ex->isGeneralTimeout());
  581. $this->assertEquals(1.0, $ex->getExceededTimeout());
  582. }
  583. }
  584. /**
  585. * @group idle-timeout
  586. */
  587. public function testIdleTimeoutNotExceededWhenOutputIsSent()
  588. {
  589. $process = $this->getProcess('echo "foo" && sleep 1 && echo "foo" && sleep 1 && echo "foo" && sleep 1 && echo "foo" && sleep 5');
  590. $process->setTimeout(5);
  591. $process->setIdleTimeout(3);
  592. try {
  593. $process->run();
  594. $this->fail('A timeout exception was expected.');
  595. } catch (ProcessTimedOutException $ex) {
  596. $this->assertTrue($ex->isGeneralTimeout());
  597. $this->assertFalse($ex->isIdleTimeout());
  598. $this->assertEquals(5.0, $ex->getExceededTimeout());
  599. }
  600. }
  601. public function testStartAfterATimeout()
  602. {
  603. $process = $this->getProcess('php -r "$n = 1000; while ($n--) {echo \'\'; usleep(1000); }"');
  604. $process->setTimeout(0.1);
  605. try {
  606. $process->run();
  607. $this->fail('An exception should have been raised.');
  608. } catch (\Exception $e) {
  609. }
  610. $process->start();
  611. usleep(10000);
  612. $process->stop();
  613. }
  614. public function testGetPid()
  615. {
  616. $process = $this->getProcess('php -r "usleep(500000);"');
  617. $process->start();
  618. $this->assertGreaterThan(0, $process->getPid());
  619. $process->wait();
  620. }
  621. public function testGetPidIsNullBeforeStart()
  622. {
  623. $process = $this->getProcess('php -r "sleep(1);"');
  624. $this->assertNull($process->getPid());
  625. }
  626. public function testGetPidIsNullAfterRun()
  627. {
  628. $process = $this->getProcess('php -m');
  629. $process->run();
  630. $this->assertNull($process->getPid());
  631. }
  632. public function testSignal()
  633. {
  634. $this->verifyPosixIsEnabled();
  635. $process = $this->getProcess('exec php -f '.__DIR__.'/SignalListener.php');
  636. $process->start();
  637. usleep(500000);
  638. $process->signal(SIGUSR1);
  639. while ($process->isRunning() && false === strpos($process->getOutput(), 'Caught SIGUSR1')) {
  640. usleep(10000);
  641. }
  642. $this->assertEquals('Caught SIGUSR1', $process->getOutput());
  643. }
  644. public function testExitCodeIsAvailableAfterSignal()
  645. {
  646. $this->verifyPosixIsEnabled();
  647. $process = $this->getProcess('sleep 4');
  648. $process->start();
  649. $process->signal(SIGKILL);
  650. while ($process->isRunning()) {
  651. usleep(10000);
  652. }
  653. $this->assertFalse($process->isRunning());
  654. $this->assertTrue($process->hasBeenSignaled());
  655. $this->assertFalse($process->isSuccessful());
  656. $this->assertEquals(137, $process->getExitCode());
  657. }
  658. /**
  659. * @expectedException \Symfony\Component\Process\Exception\LogicException
  660. */
  661. public function testSignalProcessNotRunning()
  662. {
  663. $this->verifyPosixIsEnabled();
  664. $process = $this->getProcess('php -m');
  665. $process->signal(SIGHUP);
  666. }
  667. /**
  668. * @dataProvider provideMethodsThatNeedARunningProcess
  669. */
  670. public function testMethodsThatNeedARunningProcess($method)
  671. {
  672. $process = $this->getProcess('php -m');
  673. $this->setExpectedException('Symfony\Component\Process\Exception\LogicException', sprintf('Process must be started before calling %s.', $method));
  674. call_user_func(array($process, $method));
  675. }
  676. public function provideMethodsThatNeedARunningProcess()
  677. {
  678. return array(
  679. array('getOutput'),
  680. array('getIncrementalOutput'),
  681. array('getErrorOutput'),
  682. array('getIncrementalErrorOutput'),
  683. array('wait'),
  684. );
  685. }
  686. /**
  687. * @dataProvider provideMethodsThatNeedATerminatedProcess
  688. */
  689. public function testMethodsThatNeedATerminatedProcess($method)
  690. {
  691. $process = $this->getProcess('php -r "sleep(1);"');
  692. $process->start();
  693. try {
  694. call_user_func(array($process, $method));
  695. $process->stop(0);
  696. $this->fail('A LogicException must have been thrown');
  697. } catch (\Exception $e) {
  698. $this->assertInstanceOf('Symfony\Component\Process\Exception\LogicException', $e);
  699. $this->assertEquals(sprintf('Process must be terminated before calling %s.', $method), $e->getMessage());
  700. }
  701. $process->stop(0);
  702. }
  703. public function provideMethodsThatNeedATerminatedProcess()
  704. {
  705. return array(
  706. array('hasBeenSignaled'),
  707. array('getTermSignal'),
  708. array('hasBeenStopped'),
  709. array('getStopSignal'),
  710. );
  711. }
  712. private function verifyPosixIsEnabled()
  713. {
  714. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  715. $this->markTestSkipped('POSIX signals do not work on Windows');
  716. }
  717. if (!defined('SIGUSR1')) {
  718. $this->markTestSkipped('The pcntl extension is not enabled');
  719. }
  720. }
  721. /**
  722. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  723. */
  724. public function testSignalWithWrongIntSignal()
  725. {
  726. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  727. $this->markTestSkipped('POSIX signals do not work on Windows');
  728. }
  729. $process = $this->getProcess('php -r "sleep(3);"');
  730. $process->start();
  731. $process->signal(-4);
  732. }
  733. /**
  734. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  735. */
  736. public function testSignalWithWrongNonIntSignal()
  737. {
  738. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  739. $this->markTestSkipped('POSIX signals do not work on Windows');
  740. }
  741. $process = $this->getProcess('php -r "sleep(3);"');
  742. $process->start();
  743. $process->signal('Céphalopodes');
  744. }
  745. public function responsesCodeProvider()
  746. {
  747. return array(
  748. //expected output / getter / code to execute
  749. //array(1,'getExitCode','exit(1);'),
  750. //array(true,'isSuccessful','exit();'),
  751. array('output', 'getOutput', 'echo \'output\';'),
  752. );
  753. }
  754. public function pipesCodeProvider()
  755. {
  756. $variations = array(
  757. 'fwrite(STDOUT, $in = file_get_contents(\'php://stdin\')); fwrite(STDERR, $in);',
  758. 'include \''.__DIR__.'/PipeStdinInStdoutStdErrStreamSelect.php\';',
  759. );
  760. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  761. // Avoid XL buffers on Windows because of https://bugs.php.net/bug.php?id=65650
  762. $sizes = array(1, 2, 4, 8);
  763. } else {
  764. $sizes = array(1, 16, 64, 1024, 4096);
  765. }
  766. $codes = array();
  767. foreach ($sizes as $size) {
  768. foreach ($variations as $code) {
  769. $codes[] = array($code, $size);
  770. }
  771. }
  772. return $codes;
  773. }
  774. /**
  775. * provides default method names for simple getter/setter
  776. */
  777. public function methodProvider()
  778. {
  779. $defaults = array(
  780. array('CommandLine'),
  781. array('Timeout'),
  782. array('WorkingDirectory'),
  783. array('Env'),
  784. array('Stdin'),
  785. array('Options'),
  786. );
  787. return $defaults;
  788. }
  789. /**
  790. * @param string $commandline
  791. * @param null $cwd
  792. * @param array $env
  793. * @param null $stdin
  794. * @param int $timeout
  795. * @param array $options
  796. *
  797. * @return Process
  798. */
  799. abstract protected function getProcess($commandline, $cwd = null, array $env = null, $stdin = null, $timeout = 60, array $options = array());
  800. }
  801. class Stringifiable
  802. {
  803. public function __toString()
  804. {
  805. return 'stringifiable';
  806. }
  807. }
  808. class NonStringifiable
  809. {
  810. }