ProcessTest.php 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644
  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. }
  1194. /**
  1195. * @dataProvider provideEscapeArgument
  1196. */
  1197. public function testEscapeArgument($arg)
  1198. {
  1199. $p = new Process([self::$phpBin, '-r', 'echo $argv[1];', $arg]);
  1200. $p->run();
  1201. $this->assertSame((string) $arg, $p->getOutput());
  1202. }
  1203. public function testRawCommandLine()
  1204. {
  1205. $p = Process::fromShellCommandline(sprintf('"%s" -r %s "a" "" "b"', self::$phpBin, escapeshellarg('print_r($argv);')));
  1206. $p->run();
  1207. $expected = "Array\n(\n [0] => -\n [1] => a\n [2] => \n [3] => b\n)\n";
  1208. $this->assertSame($expected, str_replace('Standard input code', '-', $p->getOutput()));
  1209. }
  1210. public static function provideEscapeArgument()
  1211. {
  1212. yield ['a"b%c%'];
  1213. yield ['a"b^c^'];
  1214. yield ["a\nb'c"];
  1215. yield ['a^b c!'];
  1216. yield ["a!b\tc"];
  1217. yield ['a\\\\"\\"'];
  1218. yield ['éÉèÈàÀöä'];
  1219. yield [null];
  1220. yield [1];
  1221. yield [1.1];
  1222. }
  1223. public function testPreparedCommand()
  1224. {
  1225. $p = Process::fromShellCommandline('echo "${:abc}"DEF');
  1226. $p->run(null, ['abc' => 'ABC']);
  1227. $this->assertSame('ABCDEF', rtrim($p->getOutput()));
  1228. }
  1229. public function testPreparedCommandMulti()
  1230. {
  1231. $p = Process::fromShellCommandline('echo "${:abc}""${:def}"');
  1232. $p->run(null, ['abc' => 'ABC', 'def' => 'DEF']);
  1233. $this->assertSame('ABCDEF', rtrim($p->getOutput()));
  1234. }
  1235. public function testPreparedCommandWithQuoteInIt()
  1236. {
  1237. $p = Process::fromShellCommandline('php -r "${:code}" "${:def}"');
  1238. $p->run(null, ['code' => 'echo $argv[1];', 'def' => '"DEF"']);
  1239. $this->assertSame('"DEF"', rtrim($p->getOutput()));
  1240. }
  1241. public function testPreparedCommandWithMissingValue()
  1242. {
  1243. $this->expectException(InvalidArgumentException::class);
  1244. $this->expectExceptionMessage('Command line is missing a value for parameter "abc": echo "${:abc}"');
  1245. $p = Process::fromShellCommandline('echo "${:abc}"');
  1246. $p->run(null, ['bcd' => 'BCD']);
  1247. }
  1248. public function testPreparedCommandWithNoValues()
  1249. {
  1250. $this->expectException(InvalidArgumentException::class);
  1251. $this->expectExceptionMessage('Command line is missing a value for parameter "abc": echo "${:abc}"');
  1252. $p = Process::fromShellCommandline('echo "${:abc}"');
  1253. $p->run(null, []);
  1254. }
  1255. public function testEnvArgument()
  1256. {
  1257. $cmd = '\\' === \DIRECTORY_SEPARATOR ? 'echo !FOO! !BAR! !BAZ!' : 'echo $FOO $BAR $BAZ';
  1258. $p = Process::fromShellCommandline($cmd);
  1259. $this->assertSame([], $p->getEnv());
  1260. $env = ['FOO' => 'Foo', 'BAR' => 'Bar'];
  1261. $p = Process::fromShellCommandline($cmd, null, $env);
  1262. $p->run(null, ['BAR' => 'baR', 'BAZ' => 'baZ']);
  1263. $this->assertSame('Foo baR baZ', rtrim($p->getOutput()));
  1264. $this->assertSame($env, $p->getEnv());
  1265. }
  1266. public function testWaitStoppedDeadProcess()
  1267. {
  1268. $process = $this->getProcess(self::$phpBin.' '.__DIR__.'/ErrorProcessInitiator.php -e '.self::$phpBin);
  1269. $process->start();
  1270. $process->setTimeout(2);
  1271. $process->wait();
  1272. $this->assertFalse($process->isRunning());
  1273. if ('\\' !== \DIRECTORY_SEPARATOR && !\Closure::bind(fn () => $this->isSigchildEnabled(), $process, $process)()) {
  1274. $this->assertSame(0, $process->getExitCode());
  1275. }
  1276. }
  1277. public function testEnvCaseInsensitiveOnWindows()
  1278. {
  1279. $p = $this->getProcessForCode('print_r([$_SERVER[\'PATH\'] ?? 1, $_SERVER[\'Path\'] ?? 2]);', null, ['PATH' => 'bar/baz']);
  1280. $p->run(null, ['Path' => 'foo/bar']);
  1281. if ('\\' === \DIRECTORY_SEPARATOR) {
  1282. $this->assertSame('Array ( [0] => 1 [1] => foo/bar )', preg_replace('/\s++/', ' ', trim($p->getOutput())));
  1283. } else {
  1284. $this->assertSame('Array ( [0] => bar/baz [1] => foo/bar )', preg_replace('/\s++/', ' ', trim($p->getOutput())));
  1285. }
  1286. }
  1287. public function testMultipleCallsToProcGetStatus()
  1288. {
  1289. $process = $this->getProcess('echo foo');
  1290. $process->start(static function () use ($process) {
  1291. return $process->isRunning();
  1292. });
  1293. while ($process->isRunning()) {
  1294. usleep(1000);
  1295. }
  1296. $this->assertSame(0, $process->getExitCode());
  1297. }
  1298. public function testFailingProcessWithMultipleCallsToProcGetStatus()
  1299. {
  1300. $process = $this->getProcess('exit 123');
  1301. $process->start(static function () use ($process) {
  1302. return $process->isRunning();
  1303. });
  1304. while ($process->isRunning()) {
  1305. usleep(1000);
  1306. }
  1307. $this->assertSame(123, $process->getExitCode());
  1308. }
  1309. /**
  1310. * @group slow
  1311. */
  1312. public function testLongRunningProcessWithMultipleCallsToProcGetStatus()
  1313. {
  1314. $process = $this->getProcess('sleep 1 && echo "done" && php -r "exit(0);"');
  1315. $process->start(static function () use ($process) {
  1316. return $process->isRunning();
  1317. });
  1318. while ($process->isRunning()) {
  1319. usleep(1000);
  1320. }
  1321. $this->assertSame(0, $process->getExitCode());
  1322. }
  1323. /**
  1324. * @group slow
  1325. */
  1326. public function testLongRunningProcessWithMultipleCallsToProcGetStatusError()
  1327. {
  1328. $process = $this->getProcess('sleep 1 && echo "failure" && php -r "exit(123);"');
  1329. $process->start(static function () use ($process) {
  1330. return $process->isRunning();
  1331. });
  1332. while ($process->isRunning()) {
  1333. usleep(1000);
  1334. }
  1335. $this->assertSame(123, $process->getExitCode());
  1336. }
  1337. /**
  1338. * @group transient-on-windows
  1339. */
  1340. public function testNotTerminableInputPipe()
  1341. {
  1342. $process = $this->getProcess('echo foo');
  1343. $process->setInput(\STDIN);
  1344. $process->start();
  1345. $process->setTimeout(2);
  1346. $process->wait();
  1347. $this->assertFalse($process->isRunning());
  1348. }
  1349. private function getProcess(string|array $commandline, ?string $cwd = null, ?array $env = null, mixed $input = null, ?int $timeout = 60): Process
  1350. {
  1351. if (\is_string($commandline)) {
  1352. $process = Process::fromShellCommandline($commandline, $cwd, $env, $input, $timeout);
  1353. } else {
  1354. $process = new Process($commandline, $cwd, $env, $input, $timeout);
  1355. }
  1356. self::$process?->stop(0);
  1357. return self::$process = $process;
  1358. }
  1359. private function getProcessForCode(string $code, ?string $cwd = null, ?array $env = null, $input = null, ?int $timeout = 60): Process
  1360. {
  1361. return $this->getProcess([self::$phpBin, '-r', $code], $cwd, $env, $input, $timeout);
  1362. }
  1363. }
  1364. class NonStringifiable
  1365. {
  1366. }