ProcessTest.php 48 KB

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