ProcessTest.php 52 KB

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