ProcessTest.php 50 KB

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