ProcessTest.php 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Process\Tests;
  11. use PHPUnit\Framework\TestCase;
  12. use Symfony\Component\Process\Exception\LogicException;
  13. use Symfony\Component\Process\Exception\ProcessTimedOutException;
  14. use Symfony\Component\Process\Exception\RuntimeException;
  15. use Symfony\Component\Process\InputStream;
  16. use Symfony\Component\Process\PhpExecutableFinder;
  17. use Symfony\Component\Process\Pipes\PipesInterface;
  18. use Symfony\Component\Process\Process;
  19. /**
  20. * @author Robert Schönthal <seroscho@googlemail.com>
  21. */
  22. class ProcessTest extends TestCase
  23. {
  24. private static $phpBin;
  25. private static $process;
  26. private static $sigchild;
  27. private static $notEnhancedSigchild = false;
  28. public static function setUpBeforeClass()
  29. {
  30. $phpBin = new PhpExecutableFinder();
  31. self::$phpBin = getenv('SYMFONY_PROCESS_PHP_TEST_BINARY') ?: ('phpdbg' === PHP_SAPI ? 'php' : $phpBin->find());
  32. ob_start();
  33. phpinfo(INFO_GENERAL);
  34. self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
  35. }
  36. protected function tearDown()
  37. {
  38. if (self::$process) {
  39. self::$process->stop(0);
  40. self::$process = null;
  41. }
  42. }
  43. public function testThatProcessDoesNotThrowWarningDuringRun()
  44. {
  45. if ('\\' === DIRECTORY_SEPARATOR) {
  46. $this->markTestSkipped('This test is transient on Windows');
  47. }
  48. @trigger_error('Test Error', E_USER_NOTICE);
  49. $process = $this->getProcessForCode('sleep(3)');
  50. $process->run();
  51. $actualError = error_get_last();
  52. $this->assertEquals('Test Error', $actualError['message']);
  53. $this->assertEquals(E_USER_NOTICE, $actualError['type']);
  54. }
  55. /**
  56. * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
  57. */
  58. public function testNegativeTimeoutFromConstructor()
  59. {
  60. $this->getProcess('', null, null, null, -1);
  61. }
  62. /**
  63. * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
  64. */
  65. public function testNegativeTimeoutFromSetter()
  66. {
  67. $p = $this->getProcess('');
  68. $p->setTimeout(-1);
  69. }
  70. public function testFloatAndNullTimeout()
  71. {
  72. $p = $this->getProcess('');
  73. $p->setTimeout(10);
  74. $this->assertSame(10.0, $p->getTimeout());
  75. $p->setTimeout(null);
  76. $this->assertNull($p->getTimeout());
  77. $p->setTimeout(0.0);
  78. $this->assertNull($p->getTimeout());
  79. }
  80. /**
  81. * @requires extension pcntl
  82. */
  83. public function testStopWithTimeoutIsActuallyWorking()
  84. {
  85. $p = $this->getProcess(array(self::$phpBin, __DIR__.'/NonStopableProcess.php', 30));
  86. $p->start();
  87. while (false === strpos($p->getOutput(), 'received')) {
  88. usleep(1000);
  89. }
  90. $start = microtime(true);
  91. $p->stop(0.1);
  92. $p->wait();
  93. $this->assertLessThan(15, microtime(true) - $start);
  94. }
  95. public function testAllOutputIsActuallyReadOnTermination()
  96. {
  97. // this code will result in a maximum of 2 reads of 8192 bytes by calling
  98. // start() and isRunning(). by the time getOutput() is called the process
  99. // has terminated so the internal pipes array is already empty. normally
  100. // the call to start() will not read any data as the process will not have
  101. // generated output, but this is non-deterministic so we must count it as
  102. // a possibility. therefore we need 2 * PipesInterface::CHUNK_SIZE plus
  103. // another byte which will never be read.
  104. $expectedOutputSize = PipesInterface::CHUNK_SIZE * 2 + 2;
  105. $code = sprintf('echo str_repeat(\'*\', %d);', $expectedOutputSize);
  106. $p = $this->getProcessForCode($code);
  107. $p->start();
  108. // Don't call Process::run nor Process::wait to avoid any read of pipes
  109. $h = new \ReflectionProperty($p, 'process');
  110. $h->setAccessible(true);
  111. $h = $h->getValue($p);
  112. $s = @proc_get_status($h);
  113. while (!empty($s['running'])) {
  114. usleep(1000);
  115. $s = proc_get_status($h);
  116. }
  117. $o = $p->getOutput();
  118. $this->assertEquals($expectedOutputSize, strlen($o));
  119. }
  120. public function testCallbacksAreExecutedWithStart()
  121. {
  122. $process = $this->getProcess('echo foo');
  123. $process->start(function ($type, $buffer) use (&$data) {
  124. $data .= $buffer;
  125. });
  126. $process->wait();
  127. $this->assertSame('foo'.PHP_EOL, $data);
  128. }
  129. /**
  130. * tests results from sub processes.
  131. *
  132. * @dataProvider responsesCodeProvider
  133. */
  134. public function testProcessResponses($expected, $getter, $code)
  135. {
  136. $p = $this->getProcessForCode($code);
  137. $p->run();
  138. $this->assertSame($expected, $p->$getter());
  139. }
  140. /**
  141. * tests results from sub processes.
  142. *
  143. * @dataProvider pipesCodeProvider
  144. */
  145. public function testProcessPipes($code, $size)
  146. {
  147. $expected = str_repeat(str_repeat('*', 1024), $size).'!';
  148. $expectedLength = (1024 * $size) + 1;
  149. $p = $this->getProcessForCode($code);
  150. $p->setInput($expected);
  151. $p->run();
  152. $this->assertEquals($expectedLength, strlen($p->getOutput()));
  153. $this->assertEquals($expectedLength, strlen($p->getErrorOutput()));
  154. }
  155. /**
  156. * @dataProvider pipesCodeProvider
  157. */
  158. public function testSetStreamAsInput($code, $size)
  159. {
  160. $expected = str_repeat(str_repeat('*', 1024), $size).'!';
  161. $expectedLength = (1024 * $size) + 1;
  162. $stream = fopen('php://temporary', 'w+');
  163. fwrite($stream, $expected);
  164. rewind($stream);
  165. $p = $this->getProcessForCode($code);
  166. $p->setInput($stream);
  167. $p->run();
  168. fclose($stream);
  169. $this->assertEquals($expectedLength, strlen($p->getOutput()));
  170. $this->assertEquals($expectedLength, strlen($p->getErrorOutput()));
  171. }
  172. public function testLiveStreamAsInput()
  173. {
  174. $stream = fopen('php://memory', 'r+');
  175. fwrite($stream, 'hello');
  176. rewind($stream);
  177. $p = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);');
  178. $p->setInput($stream);
  179. $p->start(function ($type, $data) use ($stream) {
  180. if ('hello' === $data) {
  181. fclose($stream);
  182. }
  183. });
  184. $p->wait();
  185. $this->assertSame('hello', $p->getOutput());
  186. }
  187. /**
  188. * @expectedException \Symfony\Component\Process\Exception\LogicException
  189. * @expectedExceptionMessage Input can not be set while the process is running.
  190. */
  191. public function testSetInputWhileRunningThrowsAnException()
  192. {
  193. $process = $this->getProcessForCode('sleep(30);');
  194. $process->start();
  195. try {
  196. $process->setInput('foobar');
  197. $process->stop();
  198. $this->fail('A LogicException should have been raised.');
  199. } catch (LogicException $e) {
  200. }
  201. $process->stop();
  202. throw $e;
  203. }
  204. /**
  205. * @dataProvider provideInvalidInputValues
  206. * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
  207. * @expectedExceptionMessage Symfony\Component\Process\Process::setInput only accepts strings, Traversable objects or stream resources.
  208. */
  209. public function testInvalidInput($value)
  210. {
  211. $process = $this->getProcess('foo');
  212. $process->setInput($value);
  213. }
  214. public function provideInvalidInputValues()
  215. {
  216. return array(
  217. array(array()),
  218. array(new NonStringifiable()),
  219. );
  220. }
  221. /**
  222. * @dataProvider provideInputValues
  223. */
  224. public function testValidInput($expected, $value)
  225. {
  226. $process = $this->getProcess('foo');
  227. $process->setInput($value);
  228. $this->assertSame($expected, $process->getInput());
  229. }
  230. public function provideInputValues()
  231. {
  232. return array(
  233. array(null, null),
  234. array('24.5', 24.5),
  235. array('input data', 'input data'),
  236. );
  237. }
  238. public function chainedCommandsOutputProvider()
  239. {
  240. if ('\\' === DIRECTORY_SEPARATOR) {
  241. return array(
  242. array("2 \r\n2\r\n", '&&', '2'),
  243. );
  244. }
  245. return array(
  246. array("1\n1\n", ';', '1'),
  247. array("2\n2\n", '&&', '2'),
  248. );
  249. }
  250. /**
  251. * @dataProvider chainedCommandsOutputProvider
  252. */
  253. public function testChainedCommandsOutput($expected, $operator, $input)
  254. {
  255. $process = $this->getProcess(sprintf('echo %s %s echo %s', $input, $operator, $input));
  256. $process->run();
  257. $this->assertEquals($expected, $process->getOutput());
  258. }
  259. public function testCallbackIsExecutedForOutput()
  260. {
  261. $p = $this->getProcessForCode('echo \'foo\';');
  262. $called = false;
  263. $p->run(function ($type, $buffer) use (&$called) {
  264. $called = $buffer === 'foo';
  265. });
  266. $this->assertTrue($called, 'The callback should be executed with the output');
  267. }
  268. public function testCallbackIsExecutedForOutputWheneverOutputIsDisabled()
  269. {
  270. $p = $this->getProcessForCode('echo \'foo\';');
  271. $p->disableOutput();
  272. $called = false;
  273. $p->run(function ($type, $buffer) use (&$called) {
  274. $called = $buffer === 'foo';
  275. });
  276. $this->assertTrue($called, 'The callback should be executed with the output');
  277. }
  278. public function testGetErrorOutput()
  279. {
  280. $p = $this->getProcessForCode('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }');
  281. $p->run();
  282. $this->assertEquals(3, preg_match_all('/ERROR/', $p->getErrorOutput(), $matches));
  283. }
  284. public function testFlushErrorOutput()
  285. {
  286. $p = $this->getProcessForCode('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }');
  287. $p->run();
  288. $p->clearErrorOutput();
  289. $this->assertEmpty($p->getErrorOutput());
  290. }
  291. /**
  292. * @dataProvider provideIncrementalOutput
  293. */
  294. public function testIncrementalOutput($getOutput, $getIncrementalOutput, $uri)
  295. {
  296. $lock = tempnam(sys_get_temp_dir(), __FUNCTION__);
  297. $p = $this->getProcessForCode('file_put_contents($s = \''.$uri.'\', \'foo\'); flock(fopen('.var_export($lock, true).', \'r\'), LOCK_EX); file_put_contents($s, \'bar\');');
  298. $h = fopen($lock, 'w');
  299. flock($h, LOCK_EX);
  300. $p->start();
  301. foreach (array('foo', 'bar') as $s) {
  302. while (false === strpos($p->$getOutput(), $s)) {
  303. usleep(1000);
  304. }
  305. $this->assertSame($s, $p->$getIncrementalOutput());
  306. $this->assertSame('', $p->$getIncrementalOutput());
  307. flock($h, LOCK_UN);
  308. }
  309. fclose($h);
  310. }
  311. public function provideIncrementalOutput()
  312. {
  313. return array(
  314. array('getOutput', 'getIncrementalOutput', 'php://stdout'),
  315. array('getErrorOutput', 'getIncrementalErrorOutput', 'php://stderr'),
  316. );
  317. }
  318. public function testGetOutput()
  319. {
  320. $p = $this->getProcessForCode('$n = 0; while ($n < 3) { echo \' foo \'; $n++; }');
  321. $p->run();
  322. $this->assertEquals(3, preg_match_all('/foo/', $p->getOutput(), $matches));
  323. }
  324. public function testFlushOutput()
  325. {
  326. $p = $this->getProcessForCode('$n=0;while ($n<3) {echo \' foo \';$n++;}');
  327. $p->run();
  328. $p->clearOutput();
  329. $this->assertEmpty($p->getOutput());
  330. }
  331. public function testZeroAsOutput()
  332. {
  333. if ('\\' === DIRECTORY_SEPARATOR) {
  334. // see http://stackoverflow.com/questions/7105433/windows-batch-echo-without-new-line
  335. $p = $this->getProcess('echo | set /p dummyName=0');
  336. } else {
  337. $p = $this->getProcess('printf 0');
  338. }
  339. $p->run();
  340. $this->assertSame('0', $p->getOutput());
  341. }
  342. public function testExitCodeCommandFailed()
  343. {
  344. if ('\\' === DIRECTORY_SEPARATOR) {
  345. $this->markTestSkipped('Windows does not support POSIX exit code');
  346. }
  347. $this->skipIfNotEnhancedSigchild();
  348. // such command run in bash return an exitcode 127
  349. $process = $this->getProcess('nonexistingcommandIhopeneversomeonewouldnameacommandlikethis');
  350. $process->run();
  351. $this->assertGreaterThan(0, $process->getExitCode());
  352. }
  353. public function testTTYCommand()
  354. {
  355. if ('\\' === DIRECTORY_SEPARATOR) {
  356. $this->markTestSkipped('Windows does not have /dev/tty support');
  357. }
  358. $process = $this->getProcess('echo "foo" >> /dev/null && '.$this->getProcessForCode('usleep(100000);')->getCommandLine());
  359. $process->setTty(true);
  360. $process->start();
  361. $this->assertTrue($process->isRunning());
  362. $process->wait();
  363. $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
  364. }
  365. public function testTTYCommandExitCode()
  366. {
  367. if ('\\' === DIRECTORY_SEPARATOR) {
  368. $this->markTestSkipped('Windows does have /dev/tty support');
  369. }
  370. $this->skipIfNotEnhancedSigchild();
  371. $process = $this->getProcess('echo "foo" >> /dev/null');
  372. $process->setTty(true);
  373. $process->run();
  374. $this->assertTrue($process->isSuccessful());
  375. }
  376. /**
  377. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  378. * @expectedExceptionMessage TTY mode is not supported on Windows platform.
  379. */
  380. public function testTTYInWindowsEnvironment()
  381. {
  382. if ('\\' !== DIRECTORY_SEPARATOR) {
  383. $this->markTestSkipped('This test is for Windows platform only');
  384. }
  385. $process = $this->getProcess('echo "foo" >> /dev/null');
  386. $process->setTty(false);
  387. $process->setTty(true);
  388. }
  389. public function testExitCodeTextIsNullWhenExitCodeIsNull()
  390. {
  391. $this->skipIfNotEnhancedSigchild();
  392. $process = $this->getProcess('');
  393. $this->assertNull($process->getExitCodeText());
  394. }
  395. public function testPTYCommand()
  396. {
  397. if (!Process::isPtySupported()) {
  398. $this->markTestSkipped('PTY is not supported on this operating system.');
  399. }
  400. $process = $this->getProcess('echo "foo"');
  401. $process->setPty(true);
  402. $process->run();
  403. $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
  404. $this->assertEquals("foo\r\n", $process->getOutput());
  405. }
  406. public function testMustRun()
  407. {
  408. $this->skipIfNotEnhancedSigchild();
  409. $process = $this->getProcess('echo foo');
  410. $this->assertSame($process, $process->mustRun());
  411. $this->assertEquals('foo'.PHP_EOL, $process->getOutput());
  412. }
  413. public function testSuccessfulMustRunHasCorrectExitCode()
  414. {
  415. $this->skipIfNotEnhancedSigchild();
  416. $process = $this->getProcess('echo foo')->mustRun();
  417. $this->assertEquals(0, $process->getExitCode());
  418. }
  419. /**
  420. * @expectedException \Symfony\Component\Process\Exception\ProcessFailedException
  421. */
  422. public function testMustRunThrowsException()
  423. {
  424. $this->skipIfNotEnhancedSigchild();
  425. $process = $this->getProcess('exit 1');
  426. $process->mustRun();
  427. }
  428. public function testExitCodeText()
  429. {
  430. $this->skipIfNotEnhancedSigchild();
  431. $process = $this->getProcess('');
  432. $r = new \ReflectionObject($process);
  433. $p = $r->getProperty('exitcode');
  434. $p->setAccessible(true);
  435. $p->setValue($process, 2);
  436. $this->assertEquals('Misuse of shell builtins', $process->getExitCodeText());
  437. }
  438. public function testStartIsNonBlocking()
  439. {
  440. $process = $this->getProcessForCode('usleep(500000);');
  441. $start = microtime(true);
  442. $process->start();
  443. $end = microtime(true);
  444. $this->assertLessThan(0.4, $end - $start);
  445. $process->stop();
  446. }
  447. public function testUpdateStatus()
  448. {
  449. $process = $this->getProcess('echo foo');
  450. $process->run();
  451. $this->assertTrue(strlen($process->getOutput()) > 0);
  452. }
  453. public function testGetExitCodeIsNullOnStart()
  454. {
  455. $this->skipIfNotEnhancedSigchild();
  456. $process = $this->getProcessForCode('usleep(100000);');
  457. $this->assertNull($process->getExitCode());
  458. $process->start();
  459. $this->assertNull($process->getExitCode());
  460. $process->wait();
  461. $this->assertEquals(0, $process->getExitCode());
  462. }
  463. public function testGetExitCodeIsNullOnWhenStartingAgain()
  464. {
  465. $this->skipIfNotEnhancedSigchild();
  466. $process = $this->getProcessForCode('usleep(100000);');
  467. $process->run();
  468. $this->assertEquals(0, $process->getExitCode());
  469. $process->start();
  470. $this->assertNull($process->getExitCode());
  471. $process->wait();
  472. $this->assertEquals(0, $process->getExitCode());
  473. }
  474. public function testGetExitCode()
  475. {
  476. $this->skipIfNotEnhancedSigchild();
  477. $process = $this->getProcess('echo foo');
  478. $process->run();
  479. $this->assertSame(0, $process->getExitCode());
  480. }
  481. public function testStatus()
  482. {
  483. $process = $this->getProcessForCode('usleep(100000);');
  484. $this->assertFalse($process->isRunning());
  485. $this->assertFalse($process->isStarted());
  486. $this->assertFalse($process->isTerminated());
  487. $this->assertSame(Process::STATUS_READY, $process->getStatus());
  488. $process->start();
  489. $this->assertTrue($process->isRunning());
  490. $this->assertTrue($process->isStarted());
  491. $this->assertFalse($process->isTerminated());
  492. $this->assertSame(Process::STATUS_STARTED, $process->getStatus());
  493. $process->wait();
  494. $this->assertFalse($process->isRunning());
  495. $this->assertTrue($process->isStarted());
  496. $this->assertTrue($process->isTerminated());
  497. $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
  498. }
  499. public function testStop()
  500. {
  501. $process = $this->getProcessForCode('sleep(31);');
  502. $process->start();
  503. $this->assertTrue($process->isRunning());
  504. $process->stop();
  505. $this->assertFalse($process->isRunning());
  506. }
  507. public function testIsSuccessful()
  508. {
  509. $this->skipIfNotEnhancedSigchild();
  510. $process = $this->getProcess('echo foo');
  511. $process->run();
  512. $this->assertTrue($process->isSuccessful());
  513. }
  514. public function testIsSuccessfulOnlyAfterTerminated()
  515. {
  516. $this->skipIfNotEnhancedSigchild();
  517. $process = $this->getProcessForCode('usleep(100000);');
  518. $process->start();
  519. $this->assertFalse($process->isSuccessful());
  520. $process->wait();
  521. $this->assertTrue($process->isSuccessful());
  522. }
  523. public function testIsNotSuccessful()
  524. {
  525. $this->skipIfNotEnhancedSigchild();
  526. $process = $this->getProcessForCode('throw new \Exception(\'BOUM\');');
  527. $process->run();
  528. $this->assertFalse($process->isSuccessful());
  529. }
  530. public function testProcessIsNotSignaled()
  531. {
  532. if ('\\' === DIRECTORY_SEPARATOR) {
  533. $this->markTestSkipped('Windows does not support POSIX signals');
  534. }
  535. $this->skipIfNotEnhancedSigchild();
  536. $process = $this->getProcess('echo foo');
  537. $process->run();
  538. $this->assertFalse($process->hasBeenSignaled());
  539. }
  540. public function testProcessWithoutTermSignal()
  541. {
  542. if ('\\' === DIRECTORY_SEPARATOR) {
  543. $this->markTestSkipped('Windows does not support POSIX signals');
  544. }
  545. $this->skipIfNotEnhancedSigchild();
  546. $process = $this->getProcess('echo foo');
  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. $this->skipIfNotEnhancedSigchild();
  556. $process = $this->getProcessForCode('sleep(32);');
  557. $process->start();
  558. $process->stop();
  559. $this->assertTrue($process->hasBeenSignaled());
  560. $this->assertEquals(15, $process->getTermSignal()); // SIGTERM
  561. }
  562. /**
  563. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  564. * @expectedExceptionMessage The process has been signaled
  565. */
  566. public function testProcessThrowsExceptionWhenExternallySignaled()
  567. {
  568. if (!function_exists('posix_kill')) {
  569. $this->markTestSkipped('Function posix_kill is required.');
  570. }
  571. $this->skipIfNotEnhancedSigchild(false);
  572. $process = $this->getProcessForCode('sleep(32.1);');
  573. $process->start();
  574. posix_kill($process->getPid(), 9); // SIGKILL
  575. $process->wait();
  576. }
  577. public function testRestart()
  578. {
  579. $process1 = $this->getProcessForCode('echo getmypid();');
  580. $process1->run();
  581. $process2 = $process1->restart();
  582. $process2->wait(); // wait for output
  583. // Ensure that both processed finished and the output is numeric
  584. $this->assertFalse($process1->isRunning());
  585. $this->assertFalse($process2->isRunning());
  586. $this->assertInternalType('numeric', $process1->getOutput());
  587. $this->assertInternalType('numeric', $process2->getOutput());
  588. // Ensure that restart returned a new process by check that the output is different
  589. $this->assertNotEquals($process1->getOutput(), $process2->getOutput());
  590. }
  591. /**
  592. * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
  593. * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
  594. */
  595. public function testRunProcessWithTimeout()
  596. {
  597. $process = $this->getProcessForCode('sleep(30);');
  598. $process->setTimeout(0.1);
  599. $start = microtime(true);
  600. try {
  601. $process->run();
  602. $this->fail('A RuntimeException should have been raised');
  603. } catch (RuntimeException $e) {
  604. }
  605. $this->assertLessThan(15, microtime(true) - $start);
  606. throw $e;
  607. }
  608. /**
  609. * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
  610. * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
  611. */
  612. public function testIterateOverProcessWithTimeout()
  613. {
  614. $process = $this->getProcessForCode('sleep(30);');
  615. $process->setTimeout(0.1);
  616. $start = microtime(true);
  617. try {
  618. $process->start();
  619. foreach ($process as $buffer);
  620. $this->fail('A RuntimeException should have been raised');
  621. } catch (RuntimeException $e) {
  622. }
  623. $this->assertLessThan(15, microtime(true) - $start);
  624. throw $e;
  625. }
  626. public function testCheckTimeoutOnNonStartedProcess()
  627. {
  628. $process = $this->getProcess('echo foo');
  629. $this->assertNull($process->checkTimeout());
  630. }
  631. public function testCheckTimeoutOnTerminatedProcess()
  632. {
  633. $process = $this->getProcess('echo foo');
  634. $process->run();
  635. $this->assertNull($process->checkTimeout());
  636. }
  637. /**
  638. * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
  639. * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
  640. */
  641. public function testCheckTimeoutOnStartedProcess()
  642. {
  643. $process = $this->getProcessForCode('sleep(33);');
  644. $process->setTimeout(0.1);
  645. $process->start();
  646. $start = microtime(true);
  647. try {
  648. while ($process->isRunning()) {
  649. $process->checkTimeout();
  650. usleep(100000);
  651. }
  652. $this->fail('A ProcessTimedOutException should have been raised');
  653. } catch (ProcessTimedOutException $e) {
  654. }
  655. $this->assertLessThan(15, microtime(true) - $start);
  656. throw $e;
  657. }
  658. public function testIdleTimeout()
  659. {
  660. $process = $this->getProcessForCode('sleep(34);');
  661. $process->setTimeout(60);
  662. $process->setIdleTimeout(0.1);
  663. try {
  664. $process->run();
  665. $this->fail('A timeout exception was expected.');
  666. } catch (ProcessTimedOutException $e) {
  667. $this->assertTrue($e->isIdleTimeout());
  668. $this->assertFalse($e->isGeneralTimeout());
  669. $this->assertEquals(0.1, $e->getExceededTimeout());
  670. }
  671. }
  672. public function testIdleTimeoutNotExceededWhenOutputIsSent()
  673. {
  674. $process = $this->getProcessForCode('while (true) {echo \'foo \'; usleep(1000);}');
  675. $process->setTimeout(1);
  676. $process->start();
  677. while (false === strpos($process->getOutput(), 'foo')) {
  678. usleep(1000);
  679. }
  680. $process->setIdleTimeout(0.5);
  681. try {
  682. $process->wait();
  683. $this->fail('A timeout exception was expected.');
  684. } catch (ProcessTimedOutException $e) {
  685. $this->assertTrue($e->isGeneralTimeout(), 'A general timeout is expected.');
  686. $this->assertFalse($e->isIdleTimeout(), 'No idle timeout is expected.');
  687. $this->assertEquals(1, $e->getExceededTimeout());
  688. }
  689. }
  690. /**
  691. * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
  692. * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
  693. */
  694. public function testStartAfterATimeout()
  695. {
  696. $process = $this->getProcessForCode('sleep(35);');
  697. $process->setTimeout(0.1);
  698. try {
  699. $process->run();
  700. $this->fail('A ProcessTimedOutException should have been raised.');
  701. } catch (ProcessTimedOutException $e) {
  702. }
  703. $this->assertFalse($process->isRunning());
  704. $process->start();
  705. $this->assertTrue($process->isRunning());
  706. $process->stop(0);
  707. throw $e;
  708. }
  709. public function testGetPid()
  710. {
  711. $process = $this->getProcessForCode('sleep(36);');
  712. $process->start();
  713. $this->assertGreaterThan(0, $process->getPid());
  714. $process->stop(0);
  715. }
  716. public function testGetPidIsNullBeforeStart()
  717. {
  718. $process = $this->getProcess('foo');
  719. $this->assertNull($process->getPid());
  720. }
  721. public function testGetPidIsNullAfterRun()
  722. {
  723. $process = $this->getProcess('echo foo');
  724. $process->run();
  725. $this->assertNull($process->getPid());
  726. }
  727. /**
  728. * @requires extension pcntl
  729. */
  730. public function testSignal()
  731. {
  732. $process = $this->getProcess(array(self::$phpBin, __DIR__.'/SignalListener.php'));
  733. $process->start();
  734. while (false === strpos($process->getOutput(), 'Caught')) {
  735. usleep(1000);
  736. }
  737. $process->signal(SIGUSR1);
  738. $process->wait();
  739. $this->assertEquals('Caught SIGUSR1', $process->getOutput());
  740. }
  741. /**
  742. * @requires extension pcntl
  743. */
  744. public function testExitCodeIsAvailableAfterSignal()
  745. {
  746. $this->skipIfNotEnhancedSigchild();
  747. $process = $this->getProcess('sleep 4');
  748. $process->start();
  749. $process->signal(SIGKILL);
  750. while ($process->isRunning()) {
  751. usleep(10000);
  752. }
  753. $this->assertFalse($process->isRunning());
  754. $this->assertTrue($process->hasBeenSignaled());
  755. $this->assertFalse($process->isSuccessful());
  756. $this->assertEquals(137, $process->getExitCode());
  757. }
  758. /**
  759. * @expectedException \Symfony\Component\Process\Exception\LogicException
  760. * @expectedExceptionMessage Can not send signal on a non running process.
  761. */
  762. public function testSignalProcessNotRunning()
  763. {
  764. $process = $this->getProcess('foo');
  765. $process->signal(1); // SIGHUP
  766. }
  767. /**
  768. * @dataProvider provideMethodsThatNeedARunningProcess
  769. */
  770. public function testMethodsThatNeedARunningProcess($method)
  771. {
  772. $process = $this->getProcess('foo');
  773. if (method_exists($this, 'expectException')) {
  774. $this->expectException('Symfony\Component\Process\Exception\LogicException');
  775. $this->expectExceptionMessage(sprintf('Process must be started before calling %s.', $method));
  776. } else {
  777. $this->setExpectedException('Symfony\Component\Process\Exception\LogicException', sprintf('Process must be started before calling %s.', $method));
  778. }
  779. $process->{$method}();
  780. }
  781. public function provideMethodsThatNeedARunningProcess()
  782. {
  783. return array(
  784. array('getOutput'),
  785. array('getIncrementalOutput'),
  786. array('getErrorOutput'),
  787. array('getIncrementalErrorOutput'),
  788. array('wait'),
  789. );
  790. }
  791. /**
  792. * @dataProvider provideMethodsThatNeedATerminatedProcess
  793. * @expectedException \Symfony\Component\Process\Exception\LogicException
  794. * @expectedExceptionMessage Process must be terminated before calling
  795. */
  796. public function testMethodsThatNeedATerminatedProcess($method)
  797. {
  798. $process = $this->getProcessForCode('sleep(37);');
  799. $process->start();
  800. try {
  801. $process->{$method}();
  802. $process->stop(0);
  803. $this->fail('A LogicException must have been thrown');
  804. } catch (\Exception $e) {
  805. }
  806. $process->stop(0);
  807. throw $e;
  808. }
  809. public function provideMethodsThatNeedATerminatedProcess()
  810. {
  811. return array(
  812. array('hasBeenSignaled'),
  813. array('getTermSignal'),
  814. array('hasBeenStopped'),
  815. array('getStopSignal'),
  816. );
  817. }
  818. /**
  819. * @dataProvider provideWrongSignal
  820. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  821. */
  822. public function testWrongSignal($signal)
  823. {
  824. if ('\\' === DIRECTORY_SEPARATOR) {
  825. $this->markTestSkipped('POSIX signals do not work on Windows');
  826. }
  827. $process = $this->getProcessForCode('sleep(38);');
  828. $process->start();
  829. try {
  830. $process->signal($signal);
  831. $this->fail('A RuntimeException must have been thrown');
  832. } catch (RuntimeException $e) {
  833. $process->stop(0);
  834. }
  835. throw $e;
  836. }
  837. public function provideWrongSignal()
  838. {
  839. return array(
  840. array(-4),
  841. array('Céphalopodes'),
  842. );
  843. }
  844. public function testDisableOutputDisablesTheOutput()
  845. {
  846. $p = $this->getProcess('foo');
  847. $this->assertFalse($p->isOutputDisabled());
  848. $p->disableOutput();
  849. $this->assertTrue($p->isOutputDisabled());
  850. $p->enableOutput();
  851. $this->assertFalse($p->isOutputDisabled());
  852. }
  853. /**
  854. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  855. * @expectedExceptionMessage Disabling output while the process is running is not possible.
  856. */
  857. public function testDisableOutputWhileRunningThrowsException()
  858. {
  859. $p = $this->getProcessForCode('sleep(39);');
  860. $p->start();
  861. $p->disableOutput();
  862. }
  863. /**
  864. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  865. * @expectedExceptionMessage Enabling output while the process is running is not possible.
  866. */
  867. public function testEnableOutputWhileRunningThrowsException()
  868. {
  869. $p = $this->getProcessForCode('sleep(40);');
  870. $p->disableOutput();
  871. $p->start();
  872. $p->enableOutput();
  873. }
  874. public function testEnableOrDisableOutputAfterRunDoesNotThrowException()
  875. {
  876. $p = $this->getProcess('echo foo');
  877. $p->disableOutput();
  878. $p->run();
  879. $p->enableOutput();
  880. $p->disableOutput();
  881. $this->assertTrue($p->isOutputDisabled());
  882. }
  883. /**
  884. * @expectedException \Symfony\Component\Process\Exception\LogicException
  885. * @expectedExceptionMessage Output can not be disabled while an idle timeout is set.
  886. */
  887. public function testDisableOutputWhileIdleTimeoutIsSet()
  888. {
  889. $process = $this->getProcess('foo');
  890. $process->setIdleTimeout(1);
  891. $process->disableOutput();
  892. }
  893. /**
  894. * @expectedException \Symfony\Component\Process\Exception\LogicException
  895. * @expectedExceptionMessage timeout can not be set while the output is disabled.
  896. */
  897. public function testSetIdleTimeoutWhileOutputIsDisabled()
  898. {
  899. $process = $this->getProcess('foo');
  900. $process->disableOutput();
  901. $process->setIdleTimeout(1);
  902. }
  903. public function testSetNullIdleTimeoutWhileOutputIsDisabled()
  904. {
  905. $process = $this->getProcess('foo');
  906. $process->disableOutput();
  907. $this->assertSame($process, $process->setIdleTimeout(null));
  908. }
  909. /**
  910. * @dataProvider provideOutputFetchingMethods
  911. * @expectedException \Symfony\Component\Process\Exception\LogicException
  912. * @expectedExceptionMessage Output has been disabled.
  913. */
  914. public function testGetOutputWhileDisabled($fetchMethod)
  915. {
  916. $p = $this->getProcessForCode('sleep(41);');
  917. $p->disableOutput();
  918. $p->start();
  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 testStopTerminatesProcessCleanly()
  931. {
  932. $process = $this->getProcessForCode('echo 123; sleep(42);');
  933. $process->run(function () use ($process) {
  934. $process->stop();
  935. });
  936. $this->assertTrue(true, 'A call to stop() is not expected to cause wait() to throw a RuntimeException');
  937. }
  938. public function testKillSignalTerminatesProcessCleanly()
  939. {
  940. $process = $this->getProcessForCode('echo 123; sleep(43);');
  941. $process->run(function () use ($process) {
  942. $process->signal(9); // SIGKILL
  943. });
  944. $this->assertTrue(true, 'A call to signal() is not expected to cause wait() to throw a RuntimeException');
  945. }
  946. public function testTermSignalTerminatesProcessCleanly()
  947. {
  948. $process = $this->getProcessForCode('echo 123; sleep(44);');
  949. $process->run(function () use ($process) {
  950. $process->signal(15); // SIGTERM
  951. });
  952. $this->assertTrue(true, 'A call to signal() is not expected to cause wait() to throw a RuntimeException');
  953. }
  954. public function responsesCodeProvider()
  955. {
  956. return array(
  957. //expected output / getter / code to execute
  958. //array(1,'getExitCode','exit(1);'),
  959. //array(true,'isSuccessful','exit();'),
  960. array('output', 'getOutput', 'echo \'output\';'),
  961. );
  962. }
  963. public function pipesCodeProvider()
  964. {
  965. $variations = array(
  966. 'fwrite(STDOUT, $in = file_get_contents(\'php://stdin\')); fwrite(STDERR, $in);',
  967. 'include \''.__DIR__.'/PipeStdinInStdoutStdErrStreamSelect.php\';',
  968. );
  969. if ('\\' === DIRECTORY_SEPARATOR) {
  970. // Avoid XL buffers on Windows because of https://bugs.php.net/bug.php?id=65650
  971. $sizes = array(1, 2, 4, 8);
  972. } else {
  973. $sizes = array(1, 16, 64, 1024, 4096);
  974. }
  975. $codes = array();
  976. foreach ($sizes as $size) {
  977. foreach ($variations as $code) {
  978. $codes[] = array($code, $size);
  979. }
  980. }
  981. return $codes;
  982. }
  983. /**
  984. * @dataProvider provideVariousIncrementals
  985. */
  986. public function testIncrementalOutputDoesNotRequireAnotherCall($stream, $method)
  987. {
  988. $process = $this->getProcessForCode('$n = 0; while ($n < 3) { file_put_contents(\''.$stream.'\', $n, 1); $n++; usleep(1000); }', null, null, null, null);
  989. $process->start();
  990. $result = '';
  991. $limit = microtime(true) + 3;
  992. $expected = '012';
  993. while ($result !== $expected && microtime(true) < $limit) {
  994. $result .= $process->$method();
  995. }
  996. $this->assertSame($expected, $result);
  997. $process->stop();
  998. }
  999. public function provideVariousIncrementals()
  1000. {
  1001. return array(
  1002. array('php://stdout', 'getIncrementalOutput'),
  1003. array('php://stderr', 'getIncrementalErrorOutput'),
  1004. );
  1005. }
  1006. public function testIteratorInput()
  1007. {
  1008. $input = function () {
  1009. yield 'ping';
  1010. yield 'pong';
  1011. };
  1012. $process = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);', null, null, $input());
  1013. $process->run();
  1014. $this->assertSame('pingpong', $process->getOutput());
  1015. }
  1016. public function testSimpleInputStream()
  1017. {
  1018. $input = new InputStream();
  1019. $process = $this->getProcessForCode('echo \'ping\'; stream_copy_to_stream(STDIN, STDOUT);');
  1020. $process->setInput($input);
  1021. $process->start(function ($type, $data) use ($input) {
  1022. if ('ping' === $data) {
  1023. $input->write('pang');
  1024. } elseif (!$input->isClosed()) {
  1025. $input->write('pong');
  1026. $input->close();
  1027. }
  1028. });
  1029. $process->wait();
  1030. $this->assertSame('pingpangpong', $process->getOutput());
  1031. }
  1032. public function testInputStreamWithCallable()
  1033. {
  1034. $i = 0;
  1035. $stream = fopen('php://memory', 'w+');
  1036. $stream = function () use ($stream, &$i) {
  1037. if ($i < 3) {
  1038. rewind($stream);
  1039. fwrite($stream, ++$i);
  1040. rewind($stream);
  1041. return $stream;
  1042. }
  1043. };
  1044. $input = new InputStream();
  1045. $input->onEmpty($stream);
  1046. $input->write($stream());
  1047. $process = $this->getProcessForCode('echo fread(STDIN, 3);');
  1048. $process->setInput($input);
  1049. $process->start(function ($type, $data) use ($input) {
  1050. $input->close();
  1051. });
  1052. $process->wait();
  1053. $this->assertSame('123', $process->getOutput());
  1054. }
  1055. public function testInputStreamWithGenerator()
  1056. {
  1057. $input = new InputStream();
  1058. $input->onEmpty(function ($input) {
  1059. yield 'pong';
  1060. $input->close();
  1061. });
  1062. $process = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);');
  1063. $process->setInput($input);
  1064. $process->start();
  1065. $input->write('ping');
  1066. $process->wait();
  1067. $this->assertSame('pingpong', $process->getOutput());
  1068. }
  1069. public function testInputStreamOnEmpty()
  1070. {
  1071. $i = 0;
  1072. $input = new InputStream();
  1073. $input->onEmpty(function () use (&$i) { ++$i; });
  1074. $process = $this->getProcessForCode('echo 123; echo fread(STDIN, 1); echo 456;');
  1075. $process->setInput($input);
  1076. $process->start(function ($type, $data) use ($input) {
  1077. if ('123' === $data) {
  1078. $input->close();
  1079. }
  1080. });
  1081. $process->wait();
  1082. $this->assertSame(0, $i, 'InputStream->onEmpty callback should be called only when the input *becomes* empty');
  1083. $this->assertSame('123456', $process->getOutput());
  1084. }
  1085. public function testIteratorOutput()
  1086. {
  1087. $input = new InputStream();
  1088. $process = $this->getProcessForCode('fwrite(STDOUT, 123); fwrite(STDERR, 234); flush(); usleep(10000); fwrite(STDOUT, fread(STDIN, 3)); fwrite(STDERR, 456);');
  1089. $process->setInput($input);
  1090. $process->start();
  1091. $output = array();
  1092. foreach ($process as $type => $data) {
  1093. $output[] = array($type, $data);
  1094. break;
  1095. }
  1096. $expectedOutput = array(
  1097. array($process::OUT, '123'),
  1098. );
  1099. $this->assertSame($expectedOutput, $output);
  1100. $input->write(345);
  1101. foreach ($process as $type => $data) {
  1102. $output[] = array($type, $data);
  1103. }
  1104. $this->assertSame('', $process->getOutput());
  1105. $this->assertFalse($process->isRunning());
  1106. $expectedOutput = array(
  1107. array($process::OUT, '123'),
  1108. array($process::ERR, '234'),
  1109. array($process::OUT, '345'),
  1110. array($process::ERR, '456'),
  1111. );
  1112. $this->assertSame($expectedOutput, $output);
  1113. }
  1114. public function testNonBlockingNorClearingIteratorOutput()
  1115. {
  1116. $input = new InputStream();
  1117. $process = $this->getProcessForCode('fwrite(STDOUT, fread(STDIN, 3));');
  1118. $process->setInput($input);
  1119. $process->start();
  1120. $output = array();
  1121. foreach ($process->getIterator($process::ITER_NON_BLOCKING | $process::ITER_KEEP_OUTPUT) as $type => $data) {
  1122. $output[] = array($type, $data);
  1123. break;
  1124. }
  1125. $expectedOutput = array(
  1126. array($process::OUT, ''),
  1127. );
  1128. $this->assertSame($expectedOutput, $output);
  1129. $input->write(123);
  1130. foreach ($process->getIterator($process::ITER_NON_BLOCKING | $process::ITER_KEEP_OUTPUT) as $type => $data) {
  1131. if ('' !== $data) {
  1132. $output[] = array($type, $data);
  1133. }
  1134. }
  1135. $this->assertSame('123', $process->getOutput());
  1136. $this->assertFalse($process->isRunning());
  1137. $expectedOutput = array(
  1138. array($process::OUT, ''),
  1139. array($process::OUT, '123'),
  1140. );
  1141. $this->assertSame($expectedOutput, $output);
  1142. }
  1143. public function testChainedProcesses()
  1144. {
  1145. $p1 = $this->getProcessForCode('fwrite(STDERR, 123); fwrite(STDOUT, 456);');
  1146. $p2 = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);');
  1147. $p2->setInput($p1);
  1148. $p1->start();
  1149. $p2->run();
  1150. $this->assertSame('123', $p1->getErrorOutput());
  1151. $this->assertSame('', $p1->getOutput());
  1152. $this->assertSame('', $p2->getErrorOutput());
  1153. $this->assertSame('456', $p2->getOutput());
  1154. }
  1155. public function testSetBadEnv()
  1156. {
  1157. $process = $this->getProcess('echo hello');
  1158. $process->setEnv(array('bad%%' => '123'));
  1159. $process->inheritEnvironmentVariables(true);
  1160. $process->run();
  1161. $this->assertSame('hello'.PHP_EOL, $process->getOutput());
  1162. $this->assertSame('', $process->getErrorOutput());
  1163. }
  1164. public function testEnvBackupDoesNotDeleteExistingVars()
  1165. {
  1166. putenv('existing_var=foo');
  1167. $process = $this->getProcess('php -r "echo getenv(\'new_test_var\');"');
  1168. $process->setEnv(array('existing_var' => 'bar', 'new_test_var' => 'foo'));
  1169. $process->inheritEnvironmentVariables();
  1170. $process->run();
  1171. $this->assertSame('foo', $process->getOutput());
  1172. $this->assertSame('foo', getenv('existing_var'));
  1173. $this->assertFalse(getenv('new_test_var'));
  1174. }
  1175. public function testEnvIsInherited()
  1176. {
  1177. $process = $this->getProcessForCode('echo serialize($_SERVER);', null, array('BAR' => 'BAZ'));
  1178. putenv('FOO=BAR');
  1179. $process->run();
  1180. $expected = array('BAR' => 'BAZ', 'FOO' => 'BAR');
  1181. $env = array_intersect_key(unserialize($process->getOutput()), $expected);
  1182. $this->assertEquals($expected, $env);
  1183. }
  1184. /**
  1185. * @group legacy
  1186. */
  1187. public function testInheritEnvDisabled()
  1188. {
  1189. $process = $this->getProcessForCode('echo serialize($_SERVER);', null, array('BAR' => 'BAZ'));
  1190. putenv('FOO=BAR');
  1191. $this->assertSame($process, $process->inheritEnvironmentVariables(false));
  1192. $this->assertFalse($process->areEnvironmentVariablesInherited());
  1193. $process->run();
  1194. $expected = array('BAR' => 'BAZ', 'FOO' => 'BAR');
  1195. $env = array_intersect_key(unserialize($process->getOutput()), $expected);
  1196. unset($expected['FOO']);
  1197. $this->assertSame($expected, $env);
  1198. }
  1199. public function testGetCommandLine()
  1200. {
  1201. $p = new Process(array('/usr/bin/php'));
  1202. $expected = '\\' === DIRECTORY_SEPARATOR ? '"/usr/bin/php"' : "'/usr/bin/php'";
  1203. $this->assertSame($expected, $p->getCommandLine());
  1204. }
  1205. /**
  1206. * @dataProvider provideEscapeArgument
  1207. */
  1208. public function testEscapeArgument($arg)
  1209. {
  1210. $p = new Process(array(self::$phpBin, '-r', 'echo $argv[1];', $arg));
  1211. $p->run();
  1212. $this->assertSame($arg, $p->getOutput());
  1213. }
  1214. /**
  1215. * @dataProvider provideEscapeArgument
  1216. * @group legacy
  1217. */
  1218. public function testEscapeArgumentWhenInheritEnvDisabled($arg)
  1219. {
  1220. $p = new Process(array(self::$phpBin, '-r', 'echo $argv[1];', $arg), null, array('BAR' => 'BAZ'));
  1221. $p->inheritEnvironmentVariables(false);
  1222. $p->run();
  1223. $this->assertSame($arg, $p->getOutput());
  1224. }
  1225. public function provideEscapeArgument()
  1226. {
  1227. yield array('a"b%c%');
  1228. yield array('a"b^c^');
  1229. yield array("a\nb'c");
  1230. yield array('a^b c!');
  1231. yield array("a!b\tc");
  1232. yield array('a\\\\"\\"');
  1233. yield array('éÉèÈàÀöä');
  1234. }
  1235. public function testEnvArgument()
  1236. {
  1237. $env = array('FOO' => 'Foo', 'BAR' => 'Bar');
  1238. $cmd = '\\' === DIRECTORY_SEPARATOR ? 'echo !FOO! !BAR! !BAZ!' : 'echo $FOO $BAR $BAZ';
  1239. $p = new Process($cmd, null, $env);
  1240. $p->run(null, array('BAR' => 'baR', 'BAZ' => 'baZ'));
  1241. $this->assertSame('Foo baR baZ', rtrim($p->getOutput()));
  1242. $this->assertSame($env, $p->getEnv());
  1243. }
  1244. /**
  1245. * @param string $commandline
  1246. * @param null|string $cwd
  1247. * @param null|array $env
  1248. * @param null|string $input
  1249. * @param int $timeout
  1250. * @param array $options
  1251. *
  1252. * @return Process
  1253. */
  1254. private function getProcess($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60)
  1255. {
  1256. $process = new Process($commandline, $cwd, $env, $input, $timeout);
  1257. $process->inheritEnvironmentVariables();
  1258. if (false !== $enhance = getenv('ENHANCE_SIGCHLD')) {
  1259. try {
  1260. $process->setEnhanceSigchildCompatibility(false);
  1261. $process->getExitCode();
  1262. $this->fail('ENHANCE_SIGCHLD must be used together with a sigchild-enabled PHP.');
  1263. } catch (RuntimeException $e) {
  1264. $this->assertSame('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.', $e->getMessage());
  1265. if ($enhance) {
  1266. $process->setEnhanceSigchildCompatibility(true);
  1267. } else {
  1268. self::$notEnhancedSigchild = true;
  1269. }
  1270. }
  1271. }
  1272. if (self::$process) {
  1273. self::$process->stop(0);
  1274. }
  1275. return self::$process = $process;
  1276. }
  1277. /**
  1278. * @return Process
  1279. */
  1280. private function getProcessForCode($code, $cwd = null, array $env = null, $input = null, $timeout = 60)
  1281. {
  1282. return $this->getProcess(array(self::$phpBin, '-r', $code), $cwd, $env, $input, $timeout);
  1283. }
  1284. private function skipIfNotEnhancedSigchild($expectException = true)
  1285. {
  1286. if (self::$sigchild) {
  1287. if (!$expectException) {
  1288. $this->markTestSkipped('PHP is compiled with --enable-sigchild.');
  1289. } elseif (self::$notEnhancedSigchild) {
  1290. if (method_exists($this, 'expectException')) {
  1291. $this->expectException('Symfony\Component\Process\Exception\RuntimeException');
  1292. $this->expectExceptionMessage('This PHP has been compiled with --enable-sigchild.');
  1293. } else {
  1294. $this->setExpectedException('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild.');
  1295. }
  1296. }
  1297. }
  1298. }
  1299. }
  1300. class NonStringifiable
  1301. {
  1302. }