No Description

AbstractProcessTest.php 38KB

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