ProcessTest.php 48 KB

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