菜谱项目

ProcessTest.php 48KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592
  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 = 'foo' === $buffer;
  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 = 'foo' === $buffer;
  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. /**
  354. * @group tty
  355. */
  356. public function testTTYCommand()
  357. {
  358. if ('\\' === DIRECTORY_SEPARATOR) {
  359. $this->markTestSkipped('Windows does not have /dev/tty support');
  360. }
  361. $process = $this->getProcess('echo "foo" >> /dev/null && '.$this->getProcessForCode('usleep(100000);')->getCommandLine());
  362. $process->setTty(true);
  363. $process->start();
  364. $this->assertTrue($process->isRunning());
  365. $process->wait();
  366. $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
  367. }
  368. /**
  369. * @group tty
  370. */
  371. public function testTTYCommandExitCode()
  372. {
  373. if ('\\' === DIRECTORY_SEPARATOR) {
  374. $this->markTestSkipped('Windows does have /dev/tty support');
  375. }
  376. $this->skipIfNotEnhancedSigchild();
  377. $process = $this->getProcess('echo "foo" >> /dev/null');
  378. $process->setTty(true);
  379. $process->run();
  380. $this->assertTrue($process->isSuccessful());
  381. }
  382. /**
  383. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  384. * @expectedExceptionMessage TTY mode is not supported on Windows platform.
  385. */
  386. public function testTTYInWindowsEnvironment()
  387. {
  388. if ('\\' !== DIRECTORY_SEPARATOR) {
  389. $this->markTestSkipped('This test is for Windows platform only');
  390. }
  391. $process = $this->getProcess('echo "foo" >> /dev/null');
  392. $process->setTty(false);
  393. $process->setTty(true);
  394. }
  395. public function testExitCodeTextIsNullWhenExitCodeIsNull()
  396. {
  397. $this->skipIfNotEnhancedSigchild();
  398. $process = $this->getProcess('');
  399. $this->assertNull($process->getExitCodeText());
  400. }
  401. public function testPTYCommand()
  402. {
  403. if (!Process::isPtySupported()) {
  404. $this->markTestSkipped('PTY is not supported on this operating system.');
  405. }
  406. $process = $this->getProcess('echo "foo"');
  407. $process->setPty(true);
  408. $process->run();
  409. $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
  410. $this->assertEquals("foo\r\n", $process->getOutput());
  411. }
  412. public function testMustRun()
  413. {
  414. $this->skipIfNotEnhancedSigchild();
  415. $process = $this->getProcess('echo foo');
  416. $this->assertSame($process, $process->mustRun());
  417. $this->assertEquals('foo'.PHP_EOL, $process->getOutput());
  418. }
  419. public function testSuccessfulMustRunHasCorrectExitCode()
  420. {
  421. $this->skipIfNotEnhancedSigchild();
  422. $process = $this->getProcess('echo foo')->mustRun();
  423. $this->assertEquals(0, $process->getExitCode());
  424. }
  425. /**
  426. * @expectedException \Symfony\Component\Process\Exception\ProcessFailedException
  427. */
  428. public function testMustRunThrowsException()
  429. {
  430. $this->skipIfNotEnhancedSigchild();
  431. $process = $this->getProcess('exit 1');
  432. $process->mustRun();
  433. }
  434. public function testExitCodeText()
  435. {
  436. $this->skipIfNotEnhancedSigchild();
  437. $process = $this->getProcess('');
  438. $r = new \ReflectionObject($process);
  439. $p = $r->getProperty('exitcode');
  440. $p->setAccessible(true);
  441. $p->setValue($process, 2);
  442. $this->assertEquals('Misuse of shell builtins', $process->getExitCodeText());
  443. }
  444. public function testStartIsNonBlocking()
  445. {
  446. $process = $this->getProcessForCode('usleep(500000);');
  447. $start = microtime(true);
  448. $process->start();
  449. $end = microtime(true);
  450. $this->assertLessThan(0.4, $end - $start);
  451. $process->stop();
  452. }
  453. public function testUpdateStatus()
  454. {
  455. $process = $this->getProcess('echo foo');
  456. $process->run();
  457. $this->assertTrue(strlen($process->getOutput()) > 0);
  458. }
  459. public function testGetExitCodeIsNullOnStart()
  460. {
  461. $this->skipIfNotEnhancedSigchild();
  462. $process = $this->getProcessForCode('usleep(100000);');
  463. $this->assertNull($process->getExitCode());
  464. $process->start();
  465. $this->assertNull($process->getExitCode());
  466. $process->wait();
  467. $this->assertEquals(0, $process->getExitCode());
  468. }
  469. public function testGetExitCodeIsNullOnWhenStartingAgain()
  470. {
  471. $this->skipIfNotEnhancedSigchild();
  472. $process = $this->getProcessForCode('usleep(100000);');
  473. $process->run();
  474. $this->assertEquals(0, $process->getExitCode());
  475. $process->start();
  476. $this->assertNull($process->getExitCode());
  477. $process->wait();
  478. $this->assertEquals(0, $process->getExitCode());
  479. }
  480. public function testGetExitCode()
  481. {
  482. $this->skipIfNotEnhancedSigchild();
  483. $process = $this->getProcess('echo foo');
  484. $process->run();
  485. $this->assertSame(0, $process->getExitCode());
  486. }
  487. public function testStatus()
  488. {
  489. $process = $this->getProcessForCode('usleep(100000);');
  490. $this->assertFalse($process->isRunning());
  491. $this->assertFalse($process->isStarted());
  492. $this->assertFalse($process->isTerminated());
  493. $this->assertSame(Process::STATUS_READY, $process->getStatus());
  494. $process->start();
  495. $this->assertTrue($process->isRunning());
  496. $this->assertTrue($process->isStarted());
  497. $this->assertFalse($process->isTerminated());
  498. $this->assertSame(Process::STATUS_STARTED, $process->getStatus());
  499. $process->wait();
  500. $this->assertFalse($process->isRunning());
  501. $this->assertTrue($process->isStarted());
  502. $this->assertTrue($process->isTerminated());
  503. $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
  504. }
  505. public function testStop()
  506. {
  507. $process = $this->getProcessForCode('sleep(31);');
  508. $process->start();
  509. $this->assertTrue($process->isRunning());
  510. $process->stop();
  511. $this->assertFalse($process->isRunning());
  512. }
  513. public function testIsSuccessful()
  514. {
  515. $this->skipIfNotEnhancedSigchild();
  516. $process = $this->getProcess('echo foo');
  517. $process->run();
  518. $this->assertTrue($process->isSuccessful());
  519. }
  520. public function testIsSuccessfulOnlyAfterTerminated()
  521. {
  522. $this->skipIfNotEnhancedSigchild();
  523. $process = $this->getProcessForCode('usleep(100000);');
  524. $process->start();
  525. $this->assertFalse($process->isSuccessful());
  526. $process->wait();
  527. $this->assertTrue($process->isSuccessful());
  528. }
  529. public function testIsNotSuccessful()
  530. {
  531. $this->skipIfNotEnhancedSigchild();
  532. $process = $this->getProcessForCode('throw new \Exception(\'BOUM\');');
  533. $process->run();
  534. $this->assertFalse($process->isSuccessful());
  535. }
  536. public function testProcessIsNotSignaled()
  537. {
  538. if ('\\' === DIRECTORY_SEPARATOR) {
  539. $this->markTestSkipped('Windows does not support POSIX signals');
  540. }
  541. $this->skipIfNotEnhancedSigchild();
  542. $process = $this->getProcess('echo foo');
  543. $process->run();
  544. $this->assertFalse($process->hasBeenSignaled());
  545. }
  546. public function testProcessWithoutTermSignal()
  547. {
  548. if ('\\' === DIRECTORY_SEPARATOR) {
  549. $this->markTestSkipped('Windows does not support POSIX signals');
  550. }
  551. $this->skipIfNotEnhancedSigchild();
  552. $process = $this->getProcess('echo foo');
  553. $process->run();
  554. $this->assertEquals(0, $process->getTermSignal());
  555. }
  556. public function testProcessIsSignaledIfStopped()
  557. {
  558. if ('\\' === DIRECTORY_SEPARATOR) {
  559. $this->markTestSkipped('Windows does not support POSIX signals');
  560. }
  561. $this->skipIfNotEnhancedSigchild();
  562. $process = $this->getProcessForCode('sleep(32);');
  563. $process->start();
  564. $process->stop();
  565. $this->assertTrue($process->hasBeenSignaled());
  566. $this->assertEquals(15, $process->getTermSignal()); // SIGTERM
  567. }
  568. /**
  569. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  570. * @expectedExceptionMessage The process has been signaled
  571. */
  572. public function testProcessThrowsExceptionWhenExternallySignaled()
  573. {
  574. if (!function_exists('posix_kill')) {
  575. $this->markTestSkipped('Function posix_kill is required.');
  576. }
  577. $this->skipIfNotEnhancedSigchild(false);
  578. $process = $this->getProcessForCode('sleep(32.1);');
  579. $process->start();
  580. posix_kill($process->getPid(), 9); // SIGKILL
  581. $process->wait();
  582. }
  583. public function testRestart()
  584. {
  585. $process1 = $this->getProcessForCode('echo getmypid();');
  586. $process1->run();
  587. $process2 = $process1->restart();
  588. $process2->wait(); // wait for output
  589. // Ensure that both processed finished and the output is numeric
  590. $this->assertFalse($process1->isRunning());
  591. $this->assertFalse($process2->isRunning());
  592. $this->assertInternalType('numeric', $process1->getOutput());
  593. $this->assertInternalType('numeric', $process2->getOutput());
  594. // Ensure that restart returned a new process by check that the output is different
  595. $this->assertNotEquals($process1->getOutput(), $process2->getOutput());
  596. }
  597. /**
  598. * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
  599. * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
  600. */
  601. public function testRunProcessWithTimeout()
  602. {
  603. $process = $this->getProcessForCode('sleep(30);');
  604. $process->setTimeout(0.1);
  605. $start = microtime(true);
  606. try {
  607. $process->run();
  608. $this->fail('A RuntimeException should have been raised');
  609. } catch (RuntimeException $e) {
  610. }
  611. $this->assertLessThan(15, microtime(true) - $start);
  612. throw $e;
  613. }
  614. /**
  615. * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
  616. * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
  617. */
  618. public function testIterateOverProcessWithTimeout()
  619. {
  620. $process = $this->getProcessForCode('sleep(30);');
  621. $process->setTimeout(0.1);
  622. $start = microtime(true);
  623. try {
  624. $process->start();
  625. foreach ($process as $buffer);
  626. $this->fail('A RuntimeException should have been raised');
  627. } catch (RuntimeException $e) {
  628. }
  629. $this->assertLessThan(15, microtime(true) - $start);
  630. throw $e;
  631. }
  632. public function testCheckTimeoutOnNonStartedProcess()
  633. {
  634. $process = $this->getProcess('echo foo');
  635. $this->assertNull($process->checkTimeout());
  636. }
  637. public function testCheckTimeoutOnTerminatedProcess()
  638. {
  639. $process = $this->getProcess('echo foo');
  640. $process->run();
  641. $this->assertNull($process->checkTimeout());
  642. }
  643. /**
  644. * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
  645. * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
  646. */
  647. public function testCheckTimeoutOnStartedProcess()
  648. {
  649. $process = $this->getProcessForCode('sleep(33);');
  650. $process->setTimeout(0.1);
  651. $process->start();
  652. $start = microtime(true);
  653. try {
  654. while ($process->isRunning()) {
  655. $process->checkTimeout();
  656. usleep(100000);
  657. }
  658. $this->fail('A ProcessTimedOutException should have been raised');
  659. } catch (ProcessTimedOutException $e) {
  660. }
  661. $this->assertLessThan(15, microtime(true) - $start);
  662. throw $e;
  663. }
  664. public function testIdleTimeout()
  665. {
  666. $process = $this->getProcessForCode('sleep(34);');
  667. $process->setTimeout(60);
  668. $process->setIdleTimeout(0.1);
  669. try {
  670. $process->run();
  671. $this->fail('A timeout exception was expected.');
  672. } catch (ProcessTimedOutException $e) {
  673. $this->assertTrue($e->isIdleTimeout());
  674. $this->assertFalse($e->isGeneralTimeout());
  675. $this->assertEquals(0.1, $e->getExceededTimeout());
  676. }
  677. }
  678. public function testIdleTimeoutNotExceededWhenOutputIsSent()
  679. {
  680. $process = $this->getProcessForCode('while (true) {echo \'foo \'; usleep(1000);}');
  681. $process->setTimeout(1);
  682. $process->start();
  683. while (false === strpos($process->getOutput(), 'foo')) {
  684. usleep(1000);
  685. }
  686. $process->setIdleTimeout(0.5);
  687. try {
  688. $process->wait();
  689. $this->fail('A timeout exception was expected.');
  690. } catch (ProcessTimedOutException $e) {
  691. $this->assertTrue($e->isGeneralTimeout(), 'A general timeout is expected.');
  692. $this->assertFalse($e->isIdleTimeout(), 'No idle timeout is expected.');
  693. $this->assertEquals(1, $e->getExceededTimeout());
  694. }
  695. }
  696. /**
  697. * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
  698. * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
  699. */
  700. public function testStartAfterATimeout()
  701. {
  702. $process = $this->getProcessForCode('sleep(35);');
  703. $process->setTimeout(0.1);
  704. try {
  705. $process->run();
  706. $this->fail('A ProcessTimedOutException should have been raised.');
  707. } catch (ProcessTimedOutException $e) {
  708. }
  709. $this->assertFalse($process->isRunning());
  710. $process->start();
  711. $this->assertTrue($process->isRunning());
  712. $process->stop(0);
  713. throw $e;
  714. }
  715. public function testGetPid()
  716. {
  717. $process = $this->getProcessForCode('sleep(36);');
  718. $process->start();
  719. $this->assertGreaterThan(0, $process->getPid());
  720. $process->stop(0);
  721. }
  722. public function testGetPidIsNullBeforeStart()
  723. {
  724. $process = $this->getProcess('foo');
  725. $this->assertNull($process->getPid());
  726. }
  727. public function testGetPidIsNullAfterRun()
  728. {
  729. $process = $this->getProcess('echo foo');
  730. $process->run();
  731. $this->assertNull($process->getPid());
  732. }
  733. /**
  734. * @requires extension pcntl
  735. */
  736. public function testSignal()
  737. {
  738. $process = $this->getProcess(array(self::$phpBin, __DIR__.'/SignalListener.php'));
  739. $process->start();
  740. while (false === strpos($process->getOutput(), 'Caught')) {
  741. usleep(1000);
  742. }
  743. $process->signal(SIGUSR1);
  744. $process->wait();
  745. $this->assertEquals('Caught SIGUSR1', $process->getOutput());
  746. }
  747. /**
  748. * @requires extension pcntl
  749. */
  750. public function testExitCodeIsAvailableAfterSignal()
  751. {
  752. $this->skipIfNotEnhancedSigchild();
  753. $process = $this->getProcess('sleep 4');
  754. $process->start();
  755. $process->signal(SIGKILL);
  756. while ($process->isRunning()) {
  757. usleep(10000);
  758. }
  759. $this->assertFalse($process->isRunning());
  760. $this->assertTrue($process->hasBeenSignaled());
  761. $this->assertFalse($process->isSuccessful());
  762. $this->assertEquals(137, $process->getExitCode());
  763. }
  764. /**
  765. * @expectedException \Symfony\Component\Process\Exception\LogicException
  766. * @expectedExceptionMessage Can not send signal on a non running process.
  767. */
  768. public function testSignalProcessNotRunning()
  769. {
  770. $process = $this->getProcess('foo');
  771. $process->signal(1); // SIGHUP
  772. }
  773. /**
  774. * @dataProvider provideMethodsThatNeedARunningProcess
  775. */
  776. public function testMethodsThatNeedARunningProcess($method)
  777. {
  778. $process = $this->getProcess('foo');
  779. if (method_exists($this, 'expectException')) {
  780. $this->expectException('Symfony\Component\Process\Exception\LogicException');
  781. $this->expectExceptionMessage(sprintf('Process must be started before calling %s.', $method));
  782. } else {
  783. $this->setExpectedException('Symfony\Component\Process\Exception\LogicException', sprintf('Process must be started before calling %s.', $method));
  784. }
  785. $process->{$method}();
  786. }
  787. public function provideMethodsThatNeedARunningProcess()
  788. {
  789. return array(
  790. array('getOutput'),
  791. array('getIncrementalOutput'),
  792. array('getErrorOutput'),
  793. array('getIncrementalErrorOutput'),
  794. array('wait'),
  795. );
  796. }
  797. /**
  798. * @dataProvider provideMethodsThatNeedATerminatedProcess
  799. * @expectedException \Symfony\Component\Process\Exception\LogicException
  800. * @expectedExceptionMessage Process must be terminated before calling
  801. */
  802. public function testMethodsThatNeedATerminatedProcess($method)
  803. {
  804. $process = $this->getProcessForCode('sleep(37);');
  805. $process->start();
  806. try {
  807. $process->{$method}();
  808. $process->stop(0);
  809. $this->fail('A LogicException must have been thrown');
  810. } catch (\Exception $e) {
  811. }
  812. $process->stop(0);
  813. throw $e;
  814. }
  815. public function provideMethodsThatNeedATerminatedProcess()
  816. {
  817. return array(
  818. array('hasBeenSignaled'),
  819. array('getTermSignal'),
  820. array('hasBeenStopped'),
  821. array('getStopSignal'),
  822. );
  823. }
  824. /**
  825. * @dataProvider provideWrongSignal
  826. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  827. */
  828. public function testWrongSignal($signal)
  829. {
  830. if ('\\' === DIRECTORY_SEPARATOR) {
  831. $this->markTestSkipped('POSIX signals do not work on Windows');
  832. }
  833. $process = $this->getProcessForCode('sleep(38);');
  834. $process->start();
  835. try {
  836. $process->signal($signal);
  837. $this->fail('A RuntimeException must have been thrown');
  838. } catch (RuntimeException $e) {
  839. $process->stop(0);
  840. }
  841. throw $e;
  842. }
  843. public function provideWrongSignal()
  844. {
  845. return array(
  846. array(-4),
  847. array('Céphalopodes'),
  848. );
  849. }
  850. public function testDisableOutputDisablesTheOutput()
  851. {
  852. $p = $this->getProcess('foo');
  853. $this->assertFalse($p->isOutputDisabled());
  854. $p->disableOutput();
  855. $this->assertTrue($p->isOutputDisabled());
  856. $p->enableOutput();
  857. $this->assertFalse($p->isOutputDisabled());
  858. }
  859. /**
  860. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  861. * @expectedExceptionMessage Disabling output while the process is running is not possible.
  862. */
  863. public function testDisableOutputWhileRunningThrowsException()
  864. {
  865. $p = $this->getProcessForCode('sleep(39);');
  866. $p->start();
  867. $p->disableOutput();
  868. }
  869. /**
  870. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  871. * @expectedExceptionMessage Enabling output while the process is running is not possible.
  872. */
  873. public function testEnableOutputWhileRunningThrowsException()
  874. {
  875. $p = $this->getProcessForCode('sleep(40);');
  876. $p->disableOutput();
  877. $p->start();
  878. $p->enableOutput();
  879. }
  880. public function testEnableOrDisableOutputAfterRunDoesNotThrowException()
  881. {
  882. $p = $this->getProcess('echo foo');
  883. $p->disableOutput();
  884. $p->run();
  885. $p->enableOutput();
  886. $p->disableOutput();
  887. $this->assertTrue($p->isOutputDisabled());
  888. }
  889. /**
  890. * @expectedException \Symfony\Component\Process\Exception\LogicException
  891. * @expectedExceptionMessage Output can not be disabled while an idle timeout is set.
  892. */
  893. public function testDisableOutputWhileIdleTimeoutIsSet()
  894. {
  895. $process = $this->getProcess('foo');
  896. $process->setIdleTimeout(1);
  897. $process->disableOutput();
  898. }
  899. /**
  900. * @expectedException \Symfony\Component\Process\Exception\LogicException
  901. * @expectedExceptionMessage timeout can not be set while the output is disabled.
  902. */
  903. public function testSetIdleTimeoutWhileOutputIsDisabled()
  904. {
  905. $process = $this->getProcess('foo');
  906. $process->disableOutput();
  907. $process->setIdleTimeout(1);
  908. }
  909. public function testSetNullIdleTimeoutWhileOutputIsDisabled()
  910. {
  911. $process = $this->getProcess('foo');
  912. $process->disableOutput();
  913. $this->assertSame($process, $process->setIdleTimeout(null));
  914. }
  915. /**
  916. * @dataProvider provideOutputFetchingMethods
  917. * @expectedException \Symfony\Component\Process\Exception\LogicException
  918. * @expectedExceptionMessage Output has been disabled.
  919. */
  920. public function testGetOutputWhileDisabled($fetchMethod)
  921. {
  922. $p = $this->getProcessForCode('sleep(41);');
  923. $p->disableOutput();
  924. $p->start();
  925. $p->{$fetchMethod}();
  926. }
  927. public function provideOutputFetchingMethods()
  928. {
  929. return array(
  930. array('getOutput'),
  931. array('getIncrementalOutput'),
  932. array('getErrorOutput'),
  933. array('getIncrementalErrorOutput'),
  934. );
  935. }
  936. public function testStopTerminatesProcessCleanly()
  937. {
  938. $process = $this->getProcessForCode('echo 123; sleep(42);');
  939. $process->run(function () use ($process) {
  940. $process->stop();
  941. });
  942. $this->assertTrue(true, 'A call to stop() is not expected to cause wait() to throw a RuntimeException');
  943. }
  944. public function testKillSignalTerminatesProcessCleanly()
  945. {
  946. $process = $this->getProcessForCode('echo 123; sleep(43);');
  947. $process->run(function () use ($process) {
  948. $process->signal(9); // SIGKILL
  949. });
  950. $this->assertTrue(true, 'A call to signal() is not expected to cause wait() to throw a RuntimeException');
  951. }
  952. public function testTermSignalTerminatesProcessCleanly()
  953. {
  954. $process = $this->getProcessForCode('echo 123; sleep(44);');
  955. $process->run(function () use ($process) {
  956. $process->signal(15); // SIGTERM
  957. });
  958. $this->assertTrue(true, 'A call to signal() is not expected to cause wait() to throw a RuntimeException');
  959. }
  960. public function responsesCodeProvider()
  961. {
  962. return array(
  963. //expected output / getter / code to execute
  964. //array(1,'getExitCode','exit(1);'),
  965. //array(true,'isSuccessful','exit();'),
  966. array('output', 'getOutput', 'echo \'output\';'),
  967. );
  968. }
  969. public function pipesCodeProvider()
  970. {
  971. $variations = array(
  972. 'fwrite(STDOUT, $in = file_get_contents(\'php://stdin\')); fwrite(STDERR, $in);',
  973. 'include \''.__DIR__.'/PipeStdinInStdoutStdErrStreamSelect.php\';',
  974. );
  975. if ('\\' === DIRECTORY_SEPARATOR) {
  976. // Avoid XL buffers on Windows because of https://bugs.php.net/bug.php?id=65650
  977. $sizes = array(1, 2, 4, 8);
  978. } else {
  979. $sizes = array(1, 16, 64, 1024, 4096);
  980. }
  981. $codes = array();
  982. foreach ($sizes as $size) {
  983. foreach ($variations as $code) {
  984. $codes[] = array($code, $size);
  985. }
  986. }
  987. return $codes;
  988. }
  989. /**
  990. * @dataProvider provideVariousIncrementals
  991. */
  992. public function testIncrementalOutputDoesNotRequireAnotherCall($stream, $method)
  993. {
  994. $process = $this->getProcessForCode('$n = 0; while ($n < 3) { file_put_contents(\''.$stream.'\', $n, 1); $n++; usleep(1000); }', null, null, null, null);
  995. $process->start();
  996. $result = '';
  997. $limit = microtime(true) + 3;
  998. $expected = '012';
  999. while ($result !== $expected && microtime(true) < $limit) {
  1000. $result .= $process->$method();
  1001. }
  1002. $this->assertSame($expected, $result);
  1003. $process->stop();
  1004. }
  1005. public function provideVariousIncrementals()
  1006. {
  1007. return array(
  1008. array('php://stdout', 'getIncrementalOutput'),
  1009. array('php://stderr', 'getIncrementalErrorOutput'),
  1010. );
  1011. }
  1012. public function testIteratorInput()
  1013. {
  1014. $input = function () {
  1015. yield 'ping';
  1016. yield 'pong';
  1017. };
  1018. $process = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);', null, null, $input());
  1019. $process->run();
  1020. $this->assertSame('pingpong', $process->getOutput());
  1021. }
  1022. public function testSimpleInputStream()
  1023. {
  1024. $input = new InputStream();
  1025. $process = $this->getProcessForCode('echo \'ping\'; stream_copy_to_stream(STDIN, STDOUT);');
  1026. $process->setInput($input);
  1027. $process->start(function ($type, $data) use ($input) {
  1028. if ('ping' === $data) {
  1029. $input->write('pang');
  1030. } elseif (!$input->isClosed()) {
  1031. $input->write('pong');
  1032. $input->close();
  1033. }
  1034. });
  1035. $process->wait();
  1036. $this->assertSame('pingpangpong', $process->getOutput());
  1037. }
  1038. public function testInputStreamWithCallable()
  1039. {
  1040. $i = 0;
  1041. $stream = fopen('php://memory', 'w+');
  1042. $stream = function () use ($stream, &$i) {
  1043. if ($i < 3) {
  1044. rewind($stream);
  1045. fwrite($stream, ++$i);
  1046. rewind($stream);
  1047. return $stream;
  1048. }
  1049. };
  1050. $input = new InputStream();
  1051. $input->onEmpty($stream);
  1052. $input->write($stream());
  1053. $process = $this->getProcessForCode('echo fread(STDIN, 3);');
  1054. $process->setInput($input);
  1055. $process->start(function ($type, $data) use ($input) {
  1056. $input->close();
  1057. });
  1058. $process->wait();
  1059. $this->assertSame('123', $process->getOutput());
  1060. }
  1061. public function testInputStreamWithGenerator()
  1062. {
  1063. $input = new InputStream();
  1064. $input->onEmpty(function ($input) {
  1065. yield 'pong';
  1066. $input->close();
  1067. });
  1068. $process = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);');
  1069. $process->setInput($input);
  1070. $process->start();
  1071. $input->write('ping');
  1072. $process->wait();
  1073. $this->assertSame('pingpong', $process->getOutput());
  1074. }
  1075. public function testInputStreamOnEmpty()
  1076. {
  1077. $i = 0;
  1078. $input = new InputStream();
  1079. $input->onEmpty(function () use (&$i) { ++$i; });
  1080. $process = $this->getProcessForCode('echo 123; echo fread(STDIN, 1); echo 456;');
  1081. $process->setInput($input);
  1082. $process->start(function ($type, $data) use ($input) {
  1083. if ('123' === $data) {
  1084. $input->close();
  1085. }
  1086. });
  1087. $process->wait();
  1088. $this->assertSame(0, $i, 'InputStream->onEmpty callback should be called only when the input *becomes* empty');
  1089. $this->assertSame('123456', $process->getOutput());
  1090. }
  1091. public function testIteratorOutput()
  1092. {
  1093. $input = new InputStream();
  1094. $process = $this->getProcessForCode('fwrite(STDOUT, 123); fwrite(STDERR, 234); flush(); usleep(10000); fwrite(STDOUT, fread(STDIN, 3)); fwrite(STDERR, 456);');
  1095. $process->setInput($input);
  1096. $process->start();
  1097. $output = array();
  1098. foreach ($process as $type => $data) {
  1099. $output[] = array($type, $data);
  1100. break;
  1101. }
  1102. $expectedOutput = array(
  1103. array($process::OUT, '123'),
  1104. );
  1105. $this->assertSame($expectedOutput, $output);
  1106. $input->write(345);
  1107. foreach ($process as $type => $data) {
  1108. $output[] = array($type, $data);
  1109. }
  1110. $this->assertSame('', $process->getOutput());
  1111. $this->assertFalse($process->isRunning());
  1112. $expectedOutput = array(
  1113. array($process::OUT, '123'),
  1114. array($process::ERR, '234'),
  1115. array($process::OUT, '345'),
  1116. array($process::ERR, '456'),
  1117. );
  1118. $this->assertSame($expectedOutput, $output);
  1119. }
  1120. public function testNonBlockingNorClearingIteratorOutput()
  1121. {
  1122. $input = new InputStream();
  1123. $process = $this->getProcessForCode('fwrite(STDOUT, fread(STDIN, 3));');
  1124. $process->setInput($input);
  1125. $process->start();
  1126. $output = array();
  1127. foreach ($process->getIterator($process::ITER_NON_BLOCKING | $process::ITER_KEEP_OUTPUT) as $type => $data) {
  1128. $output[] = array($type, $data);
  1129. break;
  1130. }
  1131. $expectedOutput = array(
  1132. array($process::OUT, ''),
  1133. );
  1134. $this->assertSame($expectedOutput, $output);
  1135. $input->write(123);
  1136. foreach ($process->getIterator($process::ITER_NON_BLOCKING | $process::ITER_KEEP_OUTPUT) as $type => $data) {
  1137. if ('' !== $data) {
  1138. $output[] = array($type, $data);
  1139. }
  1140. }
  1141. $this->assertSame('123', $process->getOutput());
  1142. $this->assertFalse($process->isRunning());
  1143. $expectedOutput = array(
  1144. array($process::OUT, ''),
  1145. array($process::OUT, '123'),
  1146. );
  1147. $this->assertSame($expectedOutput, $output);
  1148. }
  1149. public function testChainedProcesses()
  1150. {
  1151. $p1 = $this->getProcessForCode('fwrite(STDERR, 123); fwrite(STDOUT, 456);');
  1152. $p2 = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);');
  1153. $p2->setInput($p1);
  1154. $p1->start();
  1155. $p2->run();
  1156. $this->assertSame('123', $p1->getErrorOutput());
  1157. $this->assertSame('', $p1->getOutput());
  1158. $this->assertSame('', $p2->getErrorOutput());
  1159. $this->assertSame('456', $p2->getOutput());
  1160. }
  1161. public function testSetBadEnv()
  1162. {
  1163. $process = $this->getProcess('echo hello');
  1164. $process->setEnv(array('bad%%' => '123'));
  1165. $process->inheritEnvironmentVariables(true);
  1166. $process->run();
  1167. $this->assertSame('hello'.PHP_EOL, $process->getOutput());
  1168. $this->assertSame('', $process->getErrorOutput());
  1169. }
  1170. public function testEnvBackupDoesNotDeleteExistingVars()
  1171. {
  1172. putenv('existing_var=foo');
  1173. $process = $this->getProcess('php -r "echo getenv(\'new_test_var\');"');
  1174. $process->setEnv(array('existing_var' => 'bar', 'new_test_var' => 'foo'));
  1175. $process->inheritEnvironmentVariables();
  1176. $process->run();
  1177. $this->assertSame('foo', $process->getOutput());
  1178. $this->assertSame('foo', getenv('existing_var'));
  1179. $this->assertFalse(getenv('new_test_var'));
  1180. }
  1181. public function testEnvIsInherited()
  1182. {
  1183. $process = $this->getProcessForCode('echo serialize($_SERVER);', null, array('BAR' => 'BAZ'));
  1184. putenv('FOO=BAR');
  1185. $process->run();
  1186. $expected = array('BAR' => 'BAZ', 'FOO' => 'BAR');
  1187. $env = array_intersect_key(unserialize($process->getOutput()), $expected);
  1188. $this->assertEquals($expected, $env);
  1189. }
  1190. /**
  1191. * @group legacy
  1192. */
  1193. public function testInheritEnvDisabled()
  1194. {
  1195. $process = $this->getProcessForCode('echo serialize($_SERVER);', null, array('BAR' => 'BAZ'));
  1196. putenv('FOO=BAR');
  1197. $this->assertSame($process, $process->inheritEnvironmentVariables(false));
  1198. $this->assertFalse($process->areEnvironmentVariablesInherited());
  1199. $process->run();
  1200. $expected = array('BAR' => 'BAZ', 'FOO' => 'BAR');
  1201. $env = array_intersect_key(unserialize($process->getOutput()), $expected);
  1202. unset($expected['FOO']);
  1203. $this->assertSame($expected, $env);
  1204. }
  1205. public function testGetCommandLine()
  1206. {
  1207. $p = new Process(array('/usr/bin/php'));
  1208. $expected = '\\' === DIRECTORY_SEPARATOR ? '"/usr/bin/php"' : "'/usr/bin/php'";
  1209. $this->assertSame($expected, $p->getCommandLine());
  1210. }
  1211. /**
  1212. * @dataProvider provideEscapeArgument
  1213. */
  1214. public function testEscapeArgument($arg)
  1215. {
  1216. $p = new Process(array(self::$phpBin, '-r', 'echo $argv[1];', $arg));
  1217. $p->run();
  1218. $this->assertSame($arg, $p->getOutput());
  1219. }
  1220. /**
  1221. * @dataProvider provideEscapeArgument
  1222. * @group legacy
  1223. */
  1224. public function testEscapeArgumentWhenInheritEnvDisabled($arg)
  1225. {
  1226. $p = new Process(array(self::$phpBin, '-r', 'echo $argv[1];', $arg), null, array('BAR' => 'BAZ'));
  1227. $p->inheritEnvironmentVariables(false);
  1228. $p->run();
  1229. $this->assertSame($arg, $p->getOutput());
  1230. }
  1231. public function testRawCommandLine()
  1232. {
  1233. $p = new Process(sprintf('"%s" -r %s "a" "" "b"', self::$phpBin, escapeshellarg('print_r($argv);')));
  1234. $p->run();
  1235. $expected = <<<EOTXT
  1236. Array
  1237. (
  1238. [0] => -
  1239. [1] => a
  1240. [2] =>
  1241. [3] => b
  1242. )
  1243. EOTXT;
  1244. $this->assertSame($expected, $p->getOutput());
  1245. }
  1246. public function provideEscapeArgument()
  1247. {
  1248. yield array('a"b%c%');
  1249. yield array('a"b^c^');
  1250. yield array("a\nb'c");
  1251. yield array('a^b c!');
  1252. yield array("a!b\tc");
  1253. yield array('a\\\\"\\"');
  1254. yield array('éÉèÈàÀöä');
  1255. }
  1256. public function testEnvArgument()
  1257. {
  1258. $env = array('FOO' => 'Foo', 'BAR' => 'Bar');
  1259. $cmd = '\\' === DIRECTORY_SEPARATOR ? 'echo !FOO! !BAR! !BAZ!' : 'echo $FOO $BAR $BAZ';
  1260. $p = new Process($cmd, null, $env);
  1261. $p->run(null, array('BAR' => 'baR', 'BAZ' => 'baZ'));
  1262. $this->assertSame('Foo baR baZ', rtrim($p->getOutput()));
  1263. $this->assertSame($env, $p->getEnv());
  1264. }
  1265. /**
  1266. * @param string $commandline
  1267. * @param null|string $cwd
  1268. * @param null|array $env
  1269. * @param null|string $input
  1270. * @param int $timeout
  1271. * @param array $options
  1272. *
  1273. * @return Process
  1274. */
  1275. private function getProcess($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60)
  1276. {
  1277. $process = new Process($commandline, $cwd, $env, $input, $timeout);
  1278. $process->inheritEnvironmentVariables();
  1279. if (false !== $enhance = getenv('ENHANCE_SIGCHLD')) {
  1280. try {
  1281. $process->setEnhanceSigchildCompatibility(false);
  1282. $process->getExitCode();
  1283. $this->fail('ENHANCE_SIGCHLD must be used together with a sigchild-enabled PHP.');
  1284. } catch (RuntimeException $e) {
  1285. $this->assertSame('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.', $e->getMessage());
  1286. if ($enhance) {
  1287. $process->setEnhanceSigchildCompatibility(true);
  1288. } else {
  1289. self::$notEnhancedSigchild = true;
  1290. }
  1291. }
  1292. }
  1293. if (self::$process) {
  1294. self::$process->stop(0);
  1295. }
  1296. return self::$process = $process;
  1297. }
  1298. /**
  1299. * @return Process
  1300. */
  1301. private function getProcessForCode($code, $cwd = null, array $env = null, $input = null, $timeout = 60)
  1302. {
  1303. return $this->getProcess(array(self::$phpBin, '-r', $code), $cwd, $env, $input, $timeout);
  1304. }
  1305. private function skipIfNotEnhancedSigchild($expectException = true)
  1306. {
  1307. if (self::$sigchild) {
  1308. if (!$expectException) {
  1309. $this->markTestSkipped('PHP is compiled with --enable-sigchild.');
  1310. } elseif (self::$notEnhancedSigchild) {
  1311. if (method_exists($this, 'expectException')) {
  1312. $this->expectException('Symfony\Component\Process\Exception\RuntimeException');
  1313. $this->expectExceptionMessage('This PHP has been compiled with --enable-sigchild.');
  1314. } else {
  1315. $this->setExpectedException('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild.');
  1316. }
  1317. }
  1318. }
  1319. }
  1320. }
  1321. class NonStringifiable
  1322. {
  1323. }