AbstractProcessTest.php 37 KB

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