PageRenderTime 48ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/symfony/symfony/src/Symfony/Component/Process/Tests/AbstractProcessTest.php

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