ProcessTest.php 47 KB

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