ProcessTest.php 50 KB

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