ProcessTest.php 46 KB

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